Shader代码重复利用

发表于2018-10-24
评论0 1.9k浏览
有时候一段代码,我们可能在不同的地方调用,如果每个地方复制一份,一方面不美观,代码冗余,另一方面,如果这段代码出问题了就gg了,你得找到所有使用的地方,改吧。Shader中的代码也可以模块化的,方便大家去重复利用,主要使用define指令。例子如下:

创建.cginc文件

创建一个myinclude.cginc文件,在该文件中写入如下代码:
#ifndef MY_CG_INCLUDE
#define MY_CG_INCLUDE
fixed4 _MyColor;
//半兰伯特光照模型
inline fixed4 LightingHalfLambert (SurfaceOutput s, fixed3 lightDir, fixed atten)
{
    fixed diff = max (0, dot(s.Normal, lightDir));
    //如果定义了HalfLambert宏,则采用半兰伯特光照模型,否则采用普通的NdotL漫反射模型。
    #ifdef HalfLambert
    diff = (diff + 0.5)*0.5;
    #endif
    fixed4 c;
    c.rgb = s.Albedo*_LightColor0.rgb*((diff*_MyColor.rgb)*atten*2);
    c.a = s.Alpha;
    return c;
}
#endif

创建一个简单的surfaceshader

创建一个简单的surfaceshader着色器,代码如下:
Shader "Custom/HalfLambertShaderTest" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _DesatValue ("Desaturate", Range(0, 1)) = 0.5
        _MyColor ("My Color", Color) = (1,1,1,1)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200
        CGPROGRAM
        //定义HalfLambert宏,以便启用半兰伯特光照模型。
        #define HalfLambert
        #include "myinclude.cginc"  //类似C++的include,把自己写的.cginc文件加载进来
        #pragma surface surf HalfLambert  //启用.cginc文件中LightingHalfLambert 光照模型,名字是固定格式“Lighting”+“光照模型名称”
        sampler2D _MainTex;
        struct Input {
            float2 uv_MainTex;
        };
        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    } 
    FallBack "Diffuse"
}
以后就能把通用重复的代码整理出来,直接include就能使用,然后配合宏定义,很方便。
来自:https://blog.csdn.net/a958832776/article/details/70859936

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引