使用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。app
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的范围。
函数