返回
Featured image of post URP基础光照

URP基础光照

在该节我将使用HLSL语法,复刻CG语法下的**逐像素高光反射光照(Blinn-Phong光照模型)**Shader。

本系列URP不再阐述具体的效果实现逻辑与公式推导,侧重于URP下对**《Shader入门精要》**中Demo的复刻。如果对该Shader实现原理层面不太了解,建议移步我之前对**《Shader入门精要》**一书的学习笔记博客。在此感谢该书作者冯乐乐女神为我们这些新手铺垫了求学之路。

效果图

使用到的语法

  • 指定渲染通道采用URP渲染管道,这是必须的

    Tags { "RenderPipeline" = "UniversalRenderPipeline" }

  • 引用hlsl函数库

                #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
                #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
                #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl"
    
  • 将材质属性声明在一个名为UnityPerMaterialCBUFFER块中,这样才能保证该Shader能够兼容SRP的批处理

                CBUFFER_START(UnityPerMaterial)
                ……
                CBUFFER_END
    
  • 初始化结构体

          ZERO_INITIALIZE(v2f, o);
    
  • 一些坐标转换函数

                    // 使用HLSL的函数将坐标从模型空间转换到裁剪空间
                    o.pos = TransformObjectToHClip(v.vertex.xyz);                
                    // 使用HLSL的函数将法线从物体空间转换到世界空间
                    o.worldNormal = TransformObjectToWorldDir(v.normal);                
                    // 使用HLSL的函数将顶点从对象空间转换到世界空间
                    o.worldPos = TransformObjectToWorldDir(v.vertex.xyz);
    
  • 获取URP下主光源数据

    Light light = GetMainLight();

    该方法源码如下:

    Light GetMainLight()
    {
    	Light light;
    	light.direction = _MainLightPosition.xyz;
    	// unity_LightData.z is 1 when not culled by the culling mask, otherwise 0.
    	light.distanceAttenuation = unity_LightData.z;
    #if defined(LIGHTMAP_ON) || defined(_MIXED_LIGHTING_SUBTRACTIVE)
    	// unity_ProbesOcclusion.x is the mixed light probe occlusion data
    	light.distanceAttenuation *= unity_ProbesOcclusion.x;
    #endif
    	light.shadowAttenuation = 1.0;
    	light.color = _MainLightColor.rgb;
    
    	return light;
    }
    
  • URP内部兰伯特漫反射计算函数

    	half3 diffuse = LightingLambert(light.color.rgb, worldLightDir, worldNormal) 
    
  • 相机位置

    _WorldSpaceCameraPos

  • 环境光

    _GlossyEnvironmentColor

  • FallBack

    FallBack "Packages/com.unity.render-pipelines.universal/FallbackError"

完整代码

笔者其实比较纠结这里的环境光写法,在URP下有多种方式去计算环境光,比如带入球谐函数计算环境光、从光照贴图中获取环境光等。不在使用UNITY_LIGHTMODEL_AMBIENT.xyz的原因是该函数已经被2018版Unity标注为过期函数。

通过反复实验,得到效果与Built-in下环境光效果最相近的是half3 ambient =unity_AmbientEquator;方法,但逻辑上URP定义的环境光应该是half3 ambient = _GlossyEnvironmentColor;,这是由URP管线在管线脚本中计算天空盒的光照系数后传入的,但效果上比Built-in会亮两个灰度。

在Unity2019版本后使用Unity不再自动进行光照烘焙,我们新建场景后需要手动去开启自动烘焙,否则在Shader无法获取到环境光。(Window->rendering->Lighting Settings->Scene,最下方的AutoGenerate勾选上)

Shader "URP/Blinn-Phong"
{
    Properties
    {
        _Diffuse ("Diffuse", Color) = (1, 1, 1, 1)
        _Specular ("Specular", Color) = (1, 1, 1, 1)
        _Gloss ("Gloss", Range(1.0, 500)) = 20
    }
    SubShader
    {
        //      指定渲染通道使用URP渲染管线
        Tags { "RenderPipeline" = "UniversalRenderPipeline" "RenderType" = "Opaqua" }
        Pass
        {
            Tags { "LightMode" = "UniversalForward" }
            
            HLSLPROGRAM
            
            #pragma vertex vert
            #pragma fragment frag
            
            // 引用URP函数库
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
            #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl"
            
            // 为了确保UnityShader可以兼容SRP批处理
            // 需要把所有的材质属性声明在一个名为UnityPerMaterial的CBUFFER块中
            CBUFFER_START(UnityPerMaterial)
            half4 _Diffuse;
            half4 _Specular;
            float _Gloss;
            CBUFFER_END
            
            struct a2v
            {
                float4 vertex: POSITION;
                float3 normal: NORMAL;
                
                float2 lightmapUV: TEXCOORD1;
            };
            
            struct v2f
            {
                float4 pos: SV_POSITION;
                float3 worldNormal: TEXCOORD0;
                float3 worldPos: TEXCOORD1;
                
                //DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 2);
            };
            
            v2f vert(a2v v)
            {
                v2f o;
                // 初始化变量
                ZERO_INITIALIZE(v2f, o);
                
                // 使用HLSL的函数将坐标从模型空间转换到裁剪空间
                o.pos = TransformObjectToHClip(v.vertex.xyz);
                
                // 使用HLSL的函数将法线从物体空间转换到世界空间
                o.worldNormal = TransformObjectToWorldDir(v.normal);
                
                // 使用HLSL的函数将顶点从对象空间转换到世界空间
                o.worldPos = TransformObjectToWorldDir(v.vertex.xyz);
                
                //OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUV);
                
                return o;
            }
            
            half4 frag(v2f i): SV_Target
            {
                // 使用HLSL的函数获取主光源数据
                Light light = GetMainLight();
                
                half3 worldNormal = normalize(i.worldNormal);
                // 使用HLSL的函数计算世界空间下的光方向
                half3 worldLightDir = normalize(TransformObjectToWorldDir(light.direction));
                // 漫反射光=入射光线强度*材质的漫反射系数*取值为正数(表面法线方向 · 光源方向)
                // half3 diffuse = light.color.rgb * _Diffuse.rgb * max(0, dot(worldNormal, worldLightDir));
                half3 diffuse = LightingLambert(light.color.rgb, worldLightDir, worldNormal) * _Diffuse.rgb;
                
                // 使用HLSL的函数_WorldSpaceCameraPos获取相机位置
                // 视角方向 = 标准化(世界空间下相机位置-坐标位置)
                half3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos);
                // 半角方向 = 标准化(世界空间下光线方向 + 视角方向)
                half3 halfDir = normalize(worldLightDir + viewDir);
                // BlinnPhong高光反射=入射光线颜色强度*材质的高光反射系数*n次平方(取值为正数(法线方向 · 半角方向));		pow:次平方
                half3 specular = light.color.rgb * _Specular.rgb * pow(max(0, dot(worldNormal, halfDir)), _Gloss);
                
                
                // 获取环境光方式多种,且得到效果不一
                //half3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
                //half3 ambient = (glstate_lightmodel_ambient).xyz;
                //half3 ambient = i.vertexSH.xyz;
                //half3 ambient = SampleSH(worldNormal);
                half3 ambient = _GlossyEnvironmentColor;
                //half3 ambient = half3(unity_SHAr.w, unity_SHAg.w, unity_SHAb.w) ;
                //half3 ambient = SAMPLE_GI(i.lightmapUV, i.vertexSH, worldNormal);
                //half3 ambient =unity_AmbientEquator; ;
                
                
                // 最终结果=环境光+漫反射+高光反射,1.0代表透明度
                return half4(ambient + diffuse + specular, 1.0);
            }
            ENDHLSL
            
        }
    }
    FallBack "Packages/com.unity.render-pipelines.universal/FallbackError"
}
Licensed under CC BY-NC-SA 4.0
0