[Unity]URP HLSL Shader自用模板

Shader "URP/falushan"
{
    Properties //着色器的输入 
    {
        _BaseMap ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags {
            "RenderType"="Opaque"
            "RenderPipeLine"="UniversalRenderPipeline" //用于指明使用URP来渲染
        }

        HLSLINCLUDE 
        #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/UnityInstancing.hlsl" 
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"

        CBUFFER_START(UnityPerMaterial) //声明变量
            float4 _BaseMap_ST;
        CBUFFER_END

        TEXTURE2D(_BaseMap); //贴图采样  
        SAMPLER(sampler_BaseMap);

        struct a2v //顶点着色器
        {
            float4 positionOS: POSITION;
            float3 normalOS: TANGENT;
            half4 vertexColor: COLOR;
            float2 uv : TEXCOORD0;
        };

        struct v2f //片元着色器
        {
            float4 positionCS: SV_POSITION;
            float2 uv: TEXCOORD0;
            half4 vertexColor: COLOR;
        }; 

        ENDHLSL

        Pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag


            v2f vert (a2v v)
            {
                v2f o;
                o.positionCS = TransformObjectToHClip(v.positionOS);
                o.uv = TRANSFORM_TEX(v.uv, _BaseMap);
                o.vertexColor = v.vertexColor;
                return o;
            }

            half4 frag (v2f i) : SV_Target  /* 注意在HLSL中,fixed4类型变成了half4类型*/
            {
                half4 col = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, i.uv);
                half res=lerp(i.vertexColor,col, i.vertexColor.g);
                return half4(res,res,res,1.0);
            }
            ENDHLSL
        }
    }
}

1)CBUFFER_START和CBUFFER_END:变量是单个材质独有的时候建议放在这里面,以提高性能。CBUFFER(常量缓冲区)的空间较小,不适合存放纹理贴图这种大量数据的数据类型,适合存放float,half之类的不占空间的数据

2)TEXTURE2D (_BaseMap)和SAMPLER(sampler_BaseMap) :贴图采样,放在CBUFFER下面

3)SAMPLE_TEXTURE2D(textureName, samplerName, xxx.uv) :具有三个变量,分别是TEXTURE2D (_MainTex)的变量和SAMPLER(sampler_MainTex)的变量和uv

4)渲染管线的标签为"RenderPipeline"="UniversalRenderPipeline" 

参考:

雪风carel https://www.bilibili.com/read/cv6383390 出处:bilibili

posted @ 2023-08-06 20:47  LOFU  阅读(458)  评论(0编辑  收藏  举报