Monday 25 March 2013

Unity3D and CG/HLSL shaders

I've been using Unity3D to make apps for iOS and Android for more than a year and half and its really powerful game engine with useful tools that make life easier for developers.

I didn't write alot of shaders before using Unity but the documentation for ShaderLab (Unity's cross platform shader solution) was a good start and I started to write my shaders using surface shader.

However, after having some performance issues with one of my apps on iPhone 4 which was running on 20fps I decided to rewrite my per-vertex lighting shaders (even the basic ones) using CG/HLSL and the results were very good as the frame rate jumped to 45fps.

After using Xcode's OpenGL debugger it seems that the generated GLSL vertex and fragment shaders from unity's surface shaders includes alot of not required code as well as light calculations inside the fragment shaders even if the LightMode set to Vertex.

I am not saying that you shouldn't use surface shaders but when performance matters (especially if you are targetting old iPhone/Android hardware) consider switching to writing vertex and fragment shaders directly using CG.

A good guide to start writing in CG/HLSL is Nvidia's CG tutorial which is available online
For lighting calculation inside CG shaders, Unity provide us with built in values and methods that can be used to get light related parameters such as location and color.

Samples and profiler results will follow

Note: I am refering to the generated shaders in Unity 3.5.7 so there might be different results in the latest versions of Unity.

No comments:

Post a Comment