1、开启深度和法线纹理
通过设置Camera中的depthTextureMode变量。
camera.depthTextureMode = DepthTextureMode.None; //不生成深度纹理
camera.depthTextureMode = DepthTextureMode.Depth; //生成深度纹理
camera.depthTextureMode = DepthTextureMode.DepthNormals; //生成深度法线纹理
camera.depthTextureMode = DepthTextureMode.MotionVectors; //指定是否应渲染运动矢量
//可通过或指令同时指定生成多个纹理
camera.depthTextureMode = DepthTextureMode.Depth | DepthTextureMode.DepthNormals;
2、访问深度和法线纹理
在shader中,使用变量名_CameraDepthTexture和_CameraDepthNormalsTexture访问对应纹理。
sampler2D _CameraDepthTexture; //深度纹理,深度值存储在r通道,范围[0,1]。通过MVP矩阵变化后的z值得到
sampler2D _CameraDepthNormalsTexture; //深度法线纹理
深度纹理的线性化
对于透视投影,存储的深度值是非线性的,要得到线性的深度值,需要进行转化,可通过LinearEyeDepth和Linear01Depth完成这个过程
float depth = tex2D(_CameraDepthTexture, uv).r; //获取到存储的深度值
float depth_view = LinearEyeDepth(depth); //获取视角空间下的深度值,范围在近平面和远平面之间,[z_near, z_far]
float depth_01 = Linear01Depth(depth); //获取[0,1]范围内线性分布的深度值, 0处于摄像机位置,1处于远平面位置
深度法线纹理的使用
深度法线纹理是32bit编码(每个通道8bit),法线信息存储在R和G通道,深度信息存储在B和A通道。深度值是16bit的数据,分别存储在两个8bit通道内。
因此,要使用深度法线纹理,在采样后需要对其解码才能使用。可使用UnityCG.cginc中的DecodeDepthNormal进行解码。
inline void DecodeDepthNormal( float4 enc, out float depth, out float3 normal )
{
depth = DecodeFloatRG (enc.zw);
normal = DecodeViewNormalStereo (enc);
}
float4 samplerValue = tex2D(_CameraDepthNormalsTexture, i.uv);
float depth; //depth的最终结果为[0,1]范围的线性分布
float3 normal; //normal为屏幕空间下的法线方向
DecodeDepthNormal(samplerValue, depth, normal);
3、显示深度值和法线值
深度纹理显示:
float4 samplerValue = tex2D(_CameraDepthNormalsTexture, i.uv);
float depth; //depth的最终结果为[0,1]范围的线性分布
float3 normal; //normal为屏幕空间下的法线方向
DecodeDepthNormal(samplerValue, depth, normal);
return fixed4(depth, depth, depth,1);
![[0,1]范围的深度值](https://i-blog.csdnimg.cn/blog_migrate/e9edd5ae3d1044441c4f622eca746180.png#pic_center)
法线纹理显示:
float4 samplerValue = tex2D(_CameraDepthNormalsTexture, i.uv);
float depth; //depth的最终结果为[0,1]范围的线性分布
float3 normal; //normal为屏幕空间下的法线方向
DecodeDepthNormal(samplerValue, depth, normal);
return fixed4(normal*0.5+0.5,1);
![映射到[0,1]范围内的视角空间下的法线纹理](https://i-blog.csdnimg.cn/blog_migrate/3fc0f2c5740341504a7da486cc5c1a17.png#pic_center)
4、参考资料
[1] 冯乐乐 《Unity Shader入门精要》页269-272
[2] Unity手册 https://docs.unity3d.com/2020.2/Documentation/Manual/SL-CameraDepthTexture.html
本文详细介绍了如何在Unity中开启和访问深度纹理与法线纹理,包括设置Camera的depthTextureMode属性,以及在Shader中如何使用sampler2D_CameraDepthTexture和sampler2D_CameraDepthNormalsTexture变量。还提供了深度纹理线性化和法线纹理解码的方法,并展示了如何在Shader中显示深度值和法线值。此外,提供了相关参考资料供深入学习。
1万+

被折叠的 条评论
为什么被折叠?



