Shader Reference
在Unity中内置的渲染管道中的着色器是这样写的:
- 表面着色器
- 顶点和片段着色器
- 固定功能着色器
无论何种类型,着色器代码总是由ShaderLab语言包装,它组织着色器结构. 下面是一个用shaderLab写的框架
Shader "MyShader" {Properties {_MyTexture ("My Texture", 2D) = "white" { }// place other properties here, such as colors or vectors.}__SubShader__ {// place the shader code here for your:// - surface shader,// - vertex and program shader, or// - fixed function shader}SubShader {// a simpler version of the subshader above goes here.// this version is for supporting older graphics cards.}
}
To learn about shader basics and fixed function shaders, consult the ShaderLab syntax section. For other supported shader types, see either Writing Surface Shaders or Writing vertex and fragment shaders. You can also use post-processing effects with shaders to create full-screen filters and other interesting effects.
See Also
- Writing Surface Shaders.
- Writing vertex and fragment shaders.
- ShaderLab Syntax Reference.
- Shader Assets.
- Advanced ShaderLab Topics.
Writing Surface Shaders
编写与灯光交互的着色器是复杂的.它们有不同的 light types, 不同的hadow options, 不同的rendering
paths (forward and deferred rendering), 着色器应该以某种方式处理所有的复杂性。
For some examples, take a look at Surface Shader Examples and Surface Shader Custom Lighting Examples.
How it works
你定义一个“surface function”,它接受你需要的任何uv或数据作为输入,输出到 SurfaceOutput
.
标准的着色器结构如下:
struct SurfaceOutput
{fixed3 Albedo; // diffuse colorfixed3 Normal; // tangent space normal, if writtenfixed3 Emission;half Specular; // specular power in 0..1 rangefixed Gloss; // specular intensityfixed Alpha; // alpha for transparencies
};
物理着色器模型,包括metallic 和smoothness
struct SurfaceOutputStandard
{fixed3 Albedo; // base (diffuse or specular) colorfixed3 Normal; // tangent space normal, if writtenhalf3 Emission;half Metallic; // 0=non-metal, 1=metalhalf Smoothness; // 0=rough, 1=smoothhalf Occlusion; // occlusion (default 1)fixed Alpha; // alpha for transparencies
};
struct SurfaceOutputStandardSpecular
{fixed3 Albedo; // diffuse colorfixed3 Specular; // specular colorfixed3 Normal; // tangent space normal, if writtenhalf3 Emission;half Smoothness; // 0=rough, 1=smoothhalf Occlusion; // occlusion (default 1)fixed Alpha; // alpha for transparencies
};
Samples
See Surface Shader Examples, Surface Shader Custom Lighting Examples and Surface Shader Tessellation pages.
Surface Shader compile directives:表面着色器编译指令
Surface shader 被放在CGPROGRAM..ENDCG
命令块之间,就像其它着色器一样,他们的不同在于:
- 必须在 SubShader之间, 不在 Pass. 表面着色器将自己编译成多个Pass。
- 它使用#pragma surface…指示它是一个表面着色器。
The #pragma surface
directive is:
#pragma surface surfaceFunction lightModel [optionalparams]
Required parameters
surfaceFunction
- Cg 函数含有的表面着色器代码,这个方法由void surf (Input IN, inout SurfaceOutput o)
组成, Input 是你自定义的结构体构成,输入应包含任何纹理坐标和额外的自动变量所需的表面函数。lightModel
- 使用光照模板,基于Standard
andStandardSpecular
, 简单的基于Lambert
(diffuse) andBlinnPhong
(specular). See Custom Lighting Models page for how to write your own.Standard
光照模型使用SurfaceOutputStandard
结构体, and 匹配 Standard (metallic )属性StandardSpecular
光照模型使用SurfaceOutputStandardSpecular 匹配
Standard (specular setup)属性.Lambert
andBlinnPhong
不基于物理模型,是unity4.0以前的版本,但是不耗性能
Optional parameters
Transparency and alpha testing 通过 alpha
and alphatest
指令控制. 透明度通常有两种: 传统的alpha混合(用于淡出物体) or 更合理的物理“预乘混合”(允许半透明表面保留适当的镜面反射)启用半透明使生成的表面着色器代码包含混合命令;启用alpha cutout将在生成的基于给定变量的像素着色器中执行片段丢弃。
alpha
oralpha:auto
- 简单的光照将选择fade-transparency (和alpha:fade
) , 预乘的透明度(与alpha:premul相同)用于基于物理的照明功能。alpha:blend
- 启用 alpha blending.alpha:fade
- 启用 traditional fade-transparency.alpha:premul
- Enable premultiplied alpha transparency.alphatest:VariableName
- 启用alpha剪切透明度. 把裁剪到的值和变量名一起放到一个float里面,你可能还想使用addshadow指令来生成proper shadow caster pass。keepalpha
- By default opaque surface shaders write 1.0 (white) into alpha channel, no matter what’s output in the Alpha of output struct or what’s returned by the lighting function. Using this option allows keeping lighting function’s alpha value even for opaque surface shaders.decal:add
- Additive decal shader (e.g. terrain AddPass). This is meant for objects that lie atop of other surfaces, and use additive blending. See Surface Shader Examplesdecal:blend
- Semitransparent decal shader. This is meant for objects that lie atop of other surfaces, and use alpha blending. See Surface Shader Examples
Custom modifier functions can be used to alter or compute incoming vertex data, or to alter final computed fragment color.
vertex:VertexFunction
- Custom vertex modification function. This function is invoked at start of generated vertex shader
, and can modify or compute per-vertex data. See Surface Shader Examples.finalcolor:ColorFunction
- Custom final color modification function. See Surface Shader Examples.finalgbuffer:ColorFunction
- Custom deferred path for altering gbuffer content.finalprepass:ColorFunction
- Custom prepass base path.
Shadows and Tessellation - additional directives can be given to control how shadows and tessellation is handled.
addshadow
- Generate a shadow caster pass. Commonly used with custom vertex modification, so that shadow casting also gets any procedural vertex animation. Often shaders don’t need any special shadows handling, as they can just use shadow caster pass from their fallback.fullforwardshadows
- Support all light shadow types in Forward rendering path
. By default shaders only support shadows from one directional light in forward rendering
(to save on internal shader variant count). If you need point or spot light shadows in forward rendering, use this directive.tessellate:TessFunction
- use DX11 GPU tessellation; the function computes tessellation factors. See Surface Shader Tessellation for details.
Code generation options - by default generated surface shader code tries to handle all possible lighting/shadowing/lightmap
scenarios. However in some cases you know you won’t need some of them, and it is possible to adjust generated code to skip them. This can result in smaller shaders that are faster to load.
exclude_path:deferred
,exclude_path:forward
,exclude_path:prepass
- Do not generate passes for given rendering path (Deferred Shading
, Forward and Legacy Deferred respectively).noshadow
- Disables all shadow receiving support in this shader.noambient
- Do not apply any ambient lighting or light probes
.novertexlights
- Do not apply any light probes or per-vertex lights in Forward rendering.nolightmap
- Disables all lightmapping support in this shader.nodynlightmap
- Disables runtime dynamic global illumination support in this shader.nodirlightmap
- Disables directional lightmaps support in this shader.nofog
- Disables all built-in Fog support.nometa
- Does not generate a “meta” pass (that’s used by lightmapping & dynamic global illumination to extract surface information).noforwardadd
- Disables Forward rendering additive pass. This makes the shader support one full directional light, with all other lights computed per-vertex/SH. Makes shaders smaller as well.nolppv
- Disables Light Probe Proxy Volume
support in this shader.noshadowmask
- Disables Shadowmask support for this shader (both Shadowmask
and Distance Shadowmask
).
Miscellaneous options
softvegetation
- Makes the surface shader only be rendered when Soft Vegetation is on.interpolateview
- Compute view direction in the vertex shader and interpolate it; instead of computing it in the pixel shader. This can make the pixel shader faster, but uses up one more texture interpolator.halfasview
- Pass half-direction vector into the lighting function instead of view-direction. Half-direction will be computed and normalized per vertex. This is faster, but not entirely correct.approxview
- Removed in Unity 5.0. Useinterpolateview
instead.dualforward
- Use dual lightmaps in forward rendering path.dithercrossfade
- Makes the surface shader support dithering effects. You can then apply this shader to GameObjects
that use an LOD Group
component configured for cross-fade transition mode.
To see what exactly is different from using different options above, it can be helpful to use “Show Generated Code” button in the Shader Inspector.
Surface Shader input structure
The input structure Input
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).
Additional values that can be put into Input structure:
float3 viewDir
- contains view direction, for computing Parallax effects, rim lighting etc.float4
withCOLOR
semantic - contains interpolated per-vertex color.float4 screenPos
- contains screen space position for reflection or screenspace effects. Note that this is not suitable for GrabPass; you need to compute custom UV yourself usingComputeGrabScreenPos
function.float3 worldPos
- contains world space position.float3 worldRefl
- contains world reflection vector if surface shader does not write to o.Normal. See Reflect-Diffuse shader for example.float3 worldNormal
- contains world normal vector if surface shader does not write to o.Normal.float3 worldRefl; INTERNAL_DATA
- contains world reflection vector if surface shader writes to o.Normal. To get the reflection vector based on per-pixel normal map
, useWorldReflectionVector (IN, o.Normal)
. See Reflect-Bumped shader for example.float3 worldNormal; INTERNAL_DATA
- contains world normal vector if surface shader writes to o.Normal. To get the normal vector based on per-pixel normal map, useWorldNormalVector (IN, o.Normal)
.
Surface Shaders and DirectX 11 HLSL syntax
Currently some parts of surface shader compilation pipeline do not understand DirectX 11-specific HLSL syntax, so if you’re using HLSL features like StructuredBuffers, RWTextures and other non-DX9 syntax, you have to wrap it into a DX11-only preprocessor macro.
See Platform Specific Differences and Shading Language pages for details.