Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

查看深度纹理

1.如何查看深度纹理


我们可以在屏幕后处理中使用我们学习过的获取深度纹理信息的知识点
将深度值作为颜色的RGB值显示在屏幕上
感受深度纹理中存储的内容
理论上来说,如果深度值使用0~1范围内的线性值
越接近近裁剪面越接近黑色
越接近远裁剪面越接近白色

2.实现效果

1.shader部分

1.)实现思路

  1. 声明变量 _CameraDepthTexture 获取深度纹理
  2. 顶点着色器 只需要修改传入结构体类型
  3. 片元着色器
    1. 使用深度纹理采样宏 得到非线性的深度值
    2. 经非线性的深度值 转化到观察空间下 并将像素点到摄像机的距离转换到[0,1]区间内 (非线性深度值)
    3. 将深度值作为RGB颜色返回
  4. Fallback off

2.)实现示例

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
Shader "Unlit/DepthTexture"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
//按规则命名的深度纹理变量
sampler2D _CameraDepthTexture;

v2f vert (appdata_base v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
return o;
}

fixed4 frag (v2f i) : SV_Target
{
//非线性的 裁剪空间下的深度值
float depth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture,i.uv);
//得到线性的 [0,1]之间的深度值
fixed linearDepth = Linear01Depth(depth);
//把深度值 作为RGB颜色输出
return fixed4(linearDepth,linearDepth,linearDepth,1);
}
ENDCG
}
}
Fallback Off
}

2.C#部分

1.)实现思路

  1. 继承PostEffetBase
  2. 在Start函数中设置深度纹理模式

2.)实现示例

1
2
3
4
5
6
7
8
public class DepthTexture : PostEffectBase
{
private void Start()
{
//可以在Shader中得到对应的深度纹理信息了
Camera.main.depthTextureMode = DepthTextureMode.Depth;
}
}

评论