Version: Unity 6.0 (6000.0)
语言 : 中文
从 URP 着色器库导入文件
在自定义 URP 着色器中使用摄像机

在自定义 URP 着色器中变换位置

要在自定义通用渲染管线 (URP) 着色器中变换位置,请执行以下步骤:

  1. 在着色器文件中的 HLSLPROGRAM 中添加 #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"Core.hlsl 文件将导入 ShaderVariablesFunction.hlsl 文件。
  2. 使用 ShaderVariablesFunction.hlsl 文件的以下方法之一。
方法 语法 描述
GetNormalizedScreenSpaceUV float2 GetNormalizedScreenSpaceUV(float2 positionInClipSpace) 将裁剪空间中的位置转换为屏幕空间。
GetObjectSpaceNormalizeViewDir half3 GetObjectSpaceNormalizeViewDir(float3 positionInObjectSpace) 将对象空间中的位置转换为朝向查看器的标准化方向。
GetVertexNormalInputs VertexNormalInputs GetVertexNormalInputs(float3 normalInObjectSpace) 将对象空间中顶点的法线转换为世界空间中的切线、双切线和法线。您还可以输入对象空间中的法线切线和 float4 切线。
GetVertexPositionInputs VertexPositionInputs GetVertexPositionInputs(float3 positionInObjectSpace) 将对象空间中的顶点位置转换为世界空间、视图空间、裁剪空间和标准化设备坐标中的位置。
GetWorldSpaceNormalizeViewDir half3 GetWorldSpaceNormalizeViewDir(float3 positionInWorldSpace) 将世界空间中某个位置的方向返回到查看器,并将方向标准化。
GetWorldSpaceViewDir float3 GetWorldSpaceViewDir(float3 positionInWorldSpace) 将世界空间中某个位置的方向返回到查看器。

结构

VertexPositionInputs

使用 GetVertexNormalInputs 方法获取此结构。

字段 描述
float3 positionWS 在世界空间中的位置。
float3 positionVS 在视图空间中的位置。
float4 positionCS 在裁剪空间中的位置。
float4 positionNDC 位置作为标准化设备坐标 (NDC)。

VertexNormalInputs

使用 GetVertexNormalInputs 方法获取此结构。

字段 描述
real3 tangentWS 世界空间中的切线。
real3 bitangentWS 世界空间中的双切线。
float3 normalWS 世界空间中的法线。

示例

以下 URP 着色器使用代表对象在屏幕空间中位置的颜色绘制对象表面。

Shader "Custom/ScreenSpacePosition"
{
    SubShader
    {
        Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }

        Pass
        {
            HLSLPROGRAM

            #pragma vertex vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes
            {
                float4 positionOS : POSITION;
                float2 uv: TEXCOORD0;
            };

            struct Varyings
            {
                float4 positionCS  : SV_POSITION;
                float2 uv: TEXCOORD0;
                float3 positionWS : TEXCOORD2;
            };

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                OUT.positionCS = TransformObjectToHClip(IN.positionOS.xyz);

                // Get the position of the vertex in different spaces
                VertexPositionInputs positions = GetVertexPositionInputs(IN.positionOS);

                // Set positionWS to the screen space position of the vertex
                OUT.positionWS = positions.positionWS.xyz;

                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                // Set the fragment color to the screen space position vector
                return float4(IN.positionWS.xy, 0, 1);
            }
            ENDHLSL
        }
    }
}

其他资源

从 URP 着色器库导入文件
在自定义 URP 着色器中使用摄像机