Unity Shader 入门精要 | 第六章 Unity 中的基础光照

欢迎前往个人博客 驽马点滴 和视频空间 哔哩哔哩-《挨踢日志》

6.1 我们是如何看到这个世界的

  1. 需要有光源;
  2. 光源发出的光有几种情况:
    a) 被别的物体吸收
    b) 散射出去(反射和折射)
  3. 摄像机接收的光,产生了图片;

一些名词:
散射(scattering)
吸收(absorption)
折射(reflection)或者透射(transmission)
漫反射(diffuse)
高光反射(specular)
着色(shading)

6.2 什么是标准光照模型

标准光照模型是由著名学者裴祥风在1973年提出的。标准光照模型只关心直接光照(direct light),就是那些直接从光源发射出来照射到物体表面后,经过物体表面到一次反射直接进入摄像机的光线。

它的基本方法是,将进入摄像机的光线分为 4 个部分,每个部分使用一种方法来计算其贡献度。这 4 个部分分别是:

  1. 自发光(emissive)
    直接使用材质的自发光颜色;c(emissive) = m(emissive)

  2. 漫反射(diffuse)
    漫反射光照符合兰伯特定律(Lambert‘s Law):反射光线的强度与表面法线和光源方向之间夹角的余弦值成正比,因此计算公式如下:
    c(diffuse) = ( c(light) * m(diffuse) ) * max(0, n·l)

  3. 高光反射(specular)
    反射光 r = 2(l·n)n-l
    c(specular) = c(light)m(specular)(max(0, v·r))^m(gloss)
    上述模型为 Phong 模型,Blinn 模型引入一个新的矢量: h = (v+l)/|v+l|
    光照模型为 c(specular) = c(light)m(specular)(max(0, v·h))^m(gloss)
    Blinn 模型在 v 和 l 都是定值的时候,会比较快,否者还是 Phong 比较快一些。

  4. 环境光(ambient),通常是一个全局变量 c(ambient) = g(ambient)

最后几点:

  1. 光照模型可以用在顶点着色阶段或者片元着色阶段进行计算,亦是逐顶点光照或者逐像素光照;
  2. 上述的模型都是经验模型,图形学第一定律:如果它看起来是对的,那么它就是对的;
  3. 标准光照模型又称为 Phong 光照模型;
  4. 更改标准光照模型中的高光反射计算模型为 Blinn 算法的光照模型,称为 Blinn-Phong 光照模型;

6.3 Unity 中的环境光和自发光

暂时忽略,未看到有环境光和自发光相关的设置;

6.4 如何在 Unity 中实现漫反射光照模型

Shader "Unity Shaders Book/Chapter 6/Diffuse Vertex-Level" {
    Properties {
        _Diffuse ("Diffuse", Color) = (1.0, 1.0, 1.0, 1.0)
    }

    SubShader {
        Pass {
            Tags {"LightMode"="ForwardBase"}

            CGPROGRAM
            #include "Lighting.cginc"

            #pragma vertex vert 
            #pragma fragment frag 

            fixed4 _Diffuse;

            struct a2v {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f {
                float4 pos : SV_POSITION;
                fixed3 color : COLOR0; 
            };

            v2f vert(a2v v) {
                v2f o;
                // o.pos = mul(UNITY_MATRIX_MVP, v.vertex)
                o.pos = UnityObjectToClipPos(v.vertex);
                // Lighting 
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
                // fixed3 worldNormal = normalize(mul(v.normal, (float3x3)unity_WorldToObject));
                fixed3 worldNormal = UnityObjectToWorldNormal(v.normal);
                fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
                fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLight));
                o.color = ambient + diffuse;
                return o;
            }

            fixed4 frag(v2f i): SV_Target {
                fixed3 c = i.color;
                return fixed4(c, 1.0);
            }
            ENDCG
        }
    }
    Fallback "Diffuse"
}

语法上的变动:

// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
  1. _World2Object 被替换为 unity_WorldToObject
  2. mul(UNITY_MATRIX_MVP,) 被替换为 UnityObjectToClipPos()
  3. Object Space 中的法线变换到 World Space 中时,Unity 提供了 UnityObjectToWorldNormal( in float3 norm ) 函数;

逐顶点计算更改为逐像素计算

将上述逐顶点的计算更改为逐像素计算:

// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Unity Shaders Book/Chapter 6/Diffuse Pixel-Level" {
    Properties {
        _Diffuse ("Diffuse", Color) = (1.0, 1.0, 1.0, 1.0)
    }

    SubShader {
        Pass {
            Tags {"LightMode"="ForwardBase"}

            CGPROGRAM
            #include "Lighting.cginc"

            #pragma vertex vert 
            #pragma fragment frag 

            fixed4 _Diffuse;

            struct a2v {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f {
                float4 pos : SV_POSITION;
                fixed3 worldNormal : TEXCOORD0; 
            };

            v2f vert(a2v v) {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject);
                return o;
            }

            fixed4 frag(v2f i): SV_Target {
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;

                fixed3 worldNormal = normalize(i.worldNormal);
                fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
                fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLight));

                fixed3 c = ambient + diffuse;
                return fixed4(c, 1.0);
            }
            ENDCG
        }
    }

    Fallback "Diffuse"
}

上述使用的兰伯特光照模型,在光照无法到达的地方,会失去模型表现细节,出现全黑的情况。有一种改善技术被提出来:半兰伯特光照模型。其公式为:

c(diffuse) = c(light)*m(diffuse)*(alpha*n·l + beta)  

通常 alpha 和 beta 均取 0.5 。

// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Unity Shaders Book/Chapter 6/Diffuse Pixel-Level Half Lambert" {
    Properties {
        _Diffuse ("Diffuse", Color) = (1.0, 1.0, 1.0, 1.0)
    }

    SubShader {
        Pass {
            Tags {"LightMode"="ForwardBase"}

            CGPROGRAM
            #include "Lighting.cginc"

            #pragma vertex vert 
            #pragma fragment frag 

            fixed4 _Diffuse;

            struct a2v {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f {
                float4 pos : SV_POSITION;
                fixed3 worldNormal : TEXCOORD0; 
            };

            v2f vert(a2v v) {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject);
                return o;
            }

            fixed4 frag(v2f i): SV_Target {
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;

                fixed3 worldNormal = normalize(i.worldNormal);
                fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
                fixed halfLambert = dot(worldNormal, worldLight)*0.5 + 0.5;
                fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * halfLambert;

                fixed3 c = ambient + diffuse;
                return fixed4(c, 1.0);
            }
            ENDCG
        }
    }

    Fallback "Diffuse"
}

6.5 如何在 Unity 中实现高光反射模型

高光反射模型的计算公式为:

c(specular) = c(light)*m(specular)*(max(0, r·v))^m(gloss)

其中:

  • c(light) 由 _LightColor0.rgb 获得
  • m(specular) 通过材质面板获取
  • r 反射光线可以由 2·(l·n) - l 计算出来,其中 l 是光源方向(-l 是光照方向,注意二者的区别:光源方向是指向光源,光照方向是从光源发出的方向),Unity 的 Cg 提供了计算反射光的函数 reflect(i, n) 其中, i 是入射方向,n 是法线方向;
  • v 是视角方向;

对应的 Shader:

// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Unity Shaders Book/Chapter 6/Specular Vertex-Level" {
    Properties {
        _Diffuse ("Diffuse", Color) = (1.0, 1.0, 1.0, 1.0)
        _Specular ("Specular", Color) = (1.0, 1.0, 1.0, 1.0)
        _Gloss ("Gloss", Range(8.0, 256)) = 20
    }

    SubShader {
        Pass {
            Tags {"LightMode"="ForwardBase"}

            CGPROGRAM
            #include "Lighting.cginc"

            #pragma vertex vert 
            #pragma fragment frag 

            fixed4 _Diffuse;
            fixed4 _Specular;
            fixed _Gloss;

            struct a2v {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f {
                float4 pos : SV_POSITION;
                fixed3 color : COLOR0; 
            };

            v2f vert(a2v v) {
                v2f o;
                // o.pos = mul(UNITY_MATRIX_MVP, v.vertex)
                o.pos = UnityObjectToClipPos(v.vertex);

                // Common Variables
                fixed3 worldNormal = UnityObjectToWorldNormal(v.normal);
                fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);

                // Ambient Lighting
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;

                // Diffuse Lighting 
                fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLightDir));

                // Specular Lighting 
                fixed3 reflectDir = normalize(reflect(-worldLightDir, worldNormal));
                fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - mul(unity_ObjectToWorld, v.vertex));
                fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(reflectDir, viewDir)), _Gloss);
                
                // Summery of Lightings
                o.color = ambient + diffuse + specular;

                return o;
            }

            fixed4 frag(v2f i): SV_Target {
                fixed3 c = i.color;
                return fixed4(c, 1.0);
            }
            ENDCG
        }
    }

    Fallback "Specular"
}

逐像素高光反射

// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'


// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Unity Shaders Book/Chapter 6/Specular Pixel-Level" {
    Properties {
        _Diffuse ("Diffuse", Color) = (1.0, 1.0, 1.0, 1.0)
        _Specular ("Specular", Color) = (1.0, 1.0, 1.0, 1.0)
        _Gloss ("Gloss", Range(8.0, 256)) = 20
    }

    SubShader {
        Pass {
            Tags {"LightMode"="ForwardBase"}

            CGPROGRAM
            #include "Lighting.cginc"

            #pragma vertex vert 
            #pragma fragment frag 

            fixed4 _Diffuse;
            fixed4 _Specular;
            fixed _Gloss;

            struct a2v {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f {
                float4 pos : SV_POSITION;
                float3 worldNormal: TEXCOORD0; 
                float3 worldPos: TEXCOORD1;
            };

            v2f vert(a2v v) {
                v2f o;
                // o.pos = mul(UNITY_MATRIX_MVP, v.vertex)
                o.pos = UnityObjectToClipPos(v.vertex);
                o.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject);
                // o.worldNormal = mul((float3x3)unity_ObjectToWorld, v.normal);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex);
                return o;
            }

            fixed4 frag(v2f i): SV_Target {
                // Common Variables
                fixed3 worldNormal = normalize(i.worldNormal);
                fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);

                // Ambient Lighting
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;

                // Diffuse Lighting 
                fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLightDir));

                // Specular Lighting 
                fixed3 reflectDir = normalize(reflect(-worldLightDir, worldNormal));
                fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);
                fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(reflectDir, viewDir)), _Gloss);
                
                // Summery of Lightings
                fixed3 c = ambient + diffuse + specular;
                return fixed4(c, 1.0);
            }
            ENDCG
        }
    }

    Fallback "Specular"
}

Blinn-Phong 高光反射模型

// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'


// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Unity Shaders Book/Chapter 6/Specular Pixel-Level Blinn-Phong" {
    Properties {
        _Diffuse ("Diffuse", Color) = (1.0, 1.0, 1.0, 1.0)
        _Specular ("Specular", Color) = (1.0, 1.0, 1.0, 1.0)
        _Gloss ("Gloss", Range(8.0, 256)) = 20
    }

    SubShader {
        Pass {
            Tags {"LightMode"="ForwardBase"}

            CGPROGRAM
            #include "Lighting.cginc"

            #pragma vertex vert 
            #pragma fragment frag 

            fixed4 _Diffuse;
            fixed4 _Specular;
            fixed _Gloss;

            struct a2v {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f {
                float4 pos : SV_POSITION;
                float3 worldNormal: TEXCOORD0; 
                float3 worldPos: TEXCOORD1;
            };

            v2f vert(a2v v) {
                v2f o;
                // o.pos = mul(UNITY_MATRIX_MVP, v.vertex)
                o.pos = UnityObjectToClipPos(v.vertex);
                o.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject);
                // o.worldNormal = mul((float3x3)unity_ObjectToWorld, v.normal);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex);
                return o;
            }

            fixed4 frag(v2f i): SV_Target {
                // Common Variables
                fixed3 worldNormal = normalize(i.worldNormal);
                fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);

                // Ambient Lighting
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;

                // Diffuse Lighting 
                fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLightDir));

                // Specular Lighting 
                // fixed3 reflectDir = normalize(reflect(-worldLightDir, worldNormal));
                fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);
                fixed3 halfDir = normalize(worldLightDir + viewDir);
                fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(worldNormal, halfDir)), _Gloss);
                
                // Summery of Lightings
                fixed3 c = ambient + diffuse + specular;
                return fixed4(c, 1.0);
            }
            ENDCG
        }
    }

    Fallback "Specular"
}

6.6 使用 Unity 内置函数

UnityCG.cginc 中一些常用的帮助函数

输入:模型空间中的顶点
输出:世界空间中从该点到摄像机的方向
inline float3 WorldSpaceViewDir( in float4 localPos )
{
    float3 worldPos = mul(unity_ObjectToWorld, localPos).xyz;
    return UnityWorldSpaceViewDir(worldPos);
}
输入: 世界空间中的顶点
输出:世界空间中从该点到摄像机的方向
inline float3 UnityWorldSpaceViewDir( in float3 worldPos )
{
    return _WorldSpaceCameraPos.xyz - worldPos;
}
输入:模型空间中到顶点
输出:模型空间中从该点到摄像机的方向
inline float3 ObjSpaceViewDir( in float4 v )
{
    float3 objSpaceCameraPos = mul(unity_WorldToObject, float4(_WorldSpaceCameraPos.xyz, 1)).xyz;
    return objSpaceCameraPos - v.xyz;
}
输入:模型空间中的顶点坐标
输出:世界空间中,从该点到光源的方向
inline float3 WorldSpaceLightDir( in float4 localPos )
{
    float3 worldPos = mul(unity_ObjectToWorld, localPos).xyz;
    return UnityWorldSpaceLightDir(worldPos);
}
备注:仅可用于向前渲染中,没有归一化。
输入:世界空间中的顶点坐标
输出:世界空间中从该点到光源到方向
inline float3 UnityWorldSpaceLightDir( in float3 worldPos )
{
    #ifndef USING_LIGHT_MULTI_COMPILE
        return _WorldSpaceLightPos0.xyz - worldPos * _WorldSpaceLightPos0.w;
    #else
        #ifndef USING_DIRECTIONAL_LIGHT
        return _WorldSpaceLightPos0.xyz - worldPos;
        #else
        return _WorldSpaceLightPos0.xyz;
        #endif
    #endif
}
备注:仅可用于向前渲染中,没有归一化。
输入:模型空间中的顶点坐标
输出:模型空间中从该点到光源的方向
inline float3 ObjSpaceLightDir( in float4 v )
{
    float3 objSpaceLightPos = mul(unity_WorldToObject, _WorldSpaceLightPos0).xyz;
    #ifndef USING_LIGHT_MULTI_COMPILE
        return objSpaceLightPos.xyz - v.xyz * _WorldSpaceLightPos0.w;
    #else
        #ifndef USING_DIRECTIONAL_LIGHT
        return objSpaceLightPos.xyz - v.xyz;
        #else
        return objSpaceLightPos.xyz;
        #endif
    #endif
}
备注:仅可用于向前渲染中,没有归一化。

欢迎前往个人博客 驽马点滴 和视频空间 哔哩哔哩-《挨踢日志》

你可能感兴趣的:(Unity Shader 入门精要 | 第六章 Unity 中的基础光照)