unity-shader-tutorial-depthMap

buildin效果图

urp效果图

DepthMap.shader

DepthMap.shader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
Shader "HHF/Tutorial/DepthMap"
{
SubShader
{
Tags { "Queue"="Transparent" "RenderType" = "Transparent" "IgnoreProjector" = "True" "RenderPipeline" = "UniversalPipeline" }
Cull Off

Pass
{
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

struct appdata
{
float4 vertex : POSITION;
};

struct v2f
{
float4 positionCS : SV_POSITION;
float4 positionSS : TEXCOORD0;
};

CBUFFER_START(UnityPerMaterial)

CBUFFER_END
TEXTURE2D(_CameraDepthTexture);SAMPLER(sampler_CameraDepthTexture);

v2f vert(appdata v)
{
v2f o = (v2f)0;

o.positionCS = TransformObjectToHClip(v.vertex.xyz);
o.positionSS = ComputeScreenPos(o.positionCS);
return o;
}

half4 frag(v2f i) : SV_Target
{
// 采样深度图
// float2 screenUV = i.positionSS.xy / i.positionSS.w;
float2 screenUV = i.positionCS.xy / _ScreenParams.xy;
half4 depthMap = SAMPLE_TEXTURE2D(_CameraDepthTexture, sampler_CameraDepthTexture, screenUV);

// 返回观察空间下的z值
// half depthZ = LinearEyeDepth(depthMap,_ZBufferParams);
// return frac(depthZ);

// 返回处理后的z值,0~1
half depthZ = Linear01Depth(depthMap.x, _ZBufferParams);
return depthZ;
}

ENDHLSL
}
}

SubShader
{
Tags { "Queue"="Transparent" "RenderType" = "Transparent" "IgnoreProjector" = "True" }
Cull Off

Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
};

struct v2f
{
float4 positionCS : SV_POSITION;
float4 positionSS : TEXCOORD0;
};

sampler2D _CameraDepthTexture;

v2f vert(appdata v)
{
v2f o = (v2f)0;

o.positionCS = UnityObjectToClipPos(v.vertex.xyz);
o.positionSS = ComputeScreenPos(o.positionCS);
return o;
}

half4 frag(v2f i) : SV_Target
{
// 采样深度图
// float2 screenUV = i.positionSS.xy / i.positionSS.w;
float2 screenUV = i.positionCS.xy / _ScreenParams.xy;
half4 depthMap = tex2D(_CameraDepthTexture, screenUV);

// 返回观察空间下的z值
// half depthZ = LinearEyeDepth(depthMap);
// return frac(depthZ);

// 返回处理后的z值,0~1
half depthZ = Linear01Depth(depthMap);
return depthZ;
}

ENDCG
}
}
}