使用Depth Textures:
可以將depth信息渲染到一張texture,有些效果的制作會需要scene depth信息,此時depth texture就可以派上用場了。
Depth Texture在不同平台上有不同的實現,並且原生的支持也不一樣。
UnityCG.cginc里面定義了一些使用depth texture的幫助宏定義:
UNITY_TRANSFER_DEPTH(o) 計算eye space的深度值,並寫入變量o(float2)。當需要渲染到一張深度貼圖時,在vertex shader中使用該函數。在原生就支持depth texture的平台上,該函數啥也不做,因為Z buffer的值會被渲染。
UNITY_OUTPUT_DEPTH(i) 根據i(float2)返回eye space深度值。當需要渲染到一張深度貼圖時,在fragment shader中使用該函數。在原生就支持depth texture的平台上,該函數總是返回0。
COMPUTE_EYEDEPTH(i) 計算eye space的深度值。在vertex shader中使用,當不渲染到depth texture,而只是獲取該值時使用。
DECODE_EYEDEPTH(i) 從depth texture i中得到高精度的eye space depth。
Shader "Render Depth" { SubShader { Tags { "RenderType"="Opaque" } Pass { Fog { Mode Off } CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float4 pos : SV_POSITION; float2 depth : TEXCOORD0; }; v2f vert (appdata_base v) { v2f o; o.pos = mul (UNITY_MATRIX_MVP, v.vertex); UNITY_TRANSFER_DEPTH(o.depth); return o; } half4 frag(v2f i) : COLOR { UNITY_OUTPUT_DEPTH(i.depth); } ENDCG } } }
Camera's Depth Texture:
Camera能夠生成一張depth texture或者depth+normals texture。可以用來實現一些后處理效果或自定義的光照模式等。
Depth Texture可以直接來自於depth buffer,或者是基於Shader Replacement特性的一個獨立的pass來實現,所以也可以自己來做這件事。
變量:Camera.depthTextureMode
取值:
DepthTextureMode.Depth:一張screen-sized的depth貼圖。
DepthTextureMode.DepthNormals:
screen-sized 32 bit(8 bit/channel)texture,包含depth和view space normals信息。
noramls存放在R和G通道,depth使用B和A通道。
[UnityCG.cginc]DecodeDepthNormal(float4 enc, out float depth, out float3 normal)函數可以用來從pixel value中解碼出depth和normal值,返回的depth為0..1的范圍。
