【Writing surface shaders]
Writing shaders that interact with lighting is complex. There are different light types, different shadow options, different rendering paths (forward and deferred rendering), and the shader shocould somehow handle all that complexity.
Surface shaders in unity isCode Generation ApproachThat makes it much easier to write your shaders than using low level vertex/pixel shader programs. note that there is no custom versions, magic or ninjas involved in surface shaders; it just generates all the repetitive code that wowould have to be written by hand. you still write shader code in CG/HLSL.
You define a "surface function" thatTakes any Uvs or dataYou need as input, and fills in output structureSurfaceOutput
. Surfaceoutput basically describesProperties of the surface(It's albedo color, normal, emission, specularity etc.). You write this code in CG/HLSL.
Surface shader compiler then figures out what inputs are needed, what outputs are filled and so on, and generates actual vertex & pixel shaders, as well as rendering passes to handle forward and deferred rendering.
【Surface shader compile directives]
Surface shader is placed insideCGPROGRAM..ENDCG
Block, just like any other shader. The differences are:
- It must be placed inside subshader block, not inside pass. Surface shader will compile into multiple passes itself.
- It uses
#pragma surface ...
Directive to indicate it's a surface shader.
The#pragma surface
Directive is:
Required parameters:
- Surfacefunction-which CG function has surface shader code. The function shocould have the form
void surf (Input IN, inout SurfaceOutput o)
, Where input is a structure you have defined. Input shoshould contain any texture coordinates and extra automatic variables needed by surface function.
- Lightmodel-lighting model to use. Built-in ones are
Lambert
(Diffuse)AndBlinnPhong
(Specular). See custom lighting models page for how to write your own.
【Optional parameters]
The Input StructureInput
Generally has any texture coordinates needed by the shader.Texture coordinates must be named"uv
"Followed by texture name(Or start it with"uv2
"To use second texture coordinate set ).
Reference: file: // C:/program % 20 Files % 20 (x86)/Unity/Editor/data/documentation/html/en/manual/SL-SurfaceShaders.html