万物皆可深度图
这个图如何得到的呢?和一般网上说的Unity方法,cg方法都有点不同
//VP矩阵(projectionMatrix),是将相机空间中的点从视锥体(frustum)变换到规则观察体(Canonical View Volume)中
//实际上也就是3d->2d,世界坐标,转视线贴图
Matrix4x4 projectionMatrix = GL.GetGPUProjectionMatrix(m_LightCamera.projectionMatrix, false) * m_LightCamera.worldToCameraMatrix;
Shader.SetGlobalMatrix("_gWorldToShadow", projectionMatrix);
有了这个矩阵之后,在Shader这么写
v2f vert(appdata v)
{
v2f o;
o.shadowCoord = mul(_gWorldToShadow, o.vertex);
}
传统的深度图方法
以下方法,和上面是分开滴
以下非完整代码,无法商用,只是侃侃
#include "UnityCG.cginc"
sampler2D _CameraDepthTexture;
/* struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};*/
struct v2f
{
float4 srcPos : TEXCOORD0;
//float2 uv :TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata_base v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
//o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.srcPos = ComputeScreenPos(o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
//fixed4 col = tex2D(_MainTex, i.uv);
//return col;
float depth = 1 - Linear01Depth(tex2Dproj(_CameraDepthTexture,UNITY_PROJ_COORD(i.srcPos)).r);
return float4(depth, depth, depth, 1.0f);
}
用了一减去(反转), 所以深度图也是翻转的
文字深度图
关键在于Text UI的材质和shader
深度图和原图同屏对比
Shader "UnLit/RGBDepth" {
Properties{
_MainTex("Base (RGB)", 2D) = "white" {}
}
SubShader{
Tags{ "RenderType" = "Opaque" }
Pass{
Cull off
ZTest Always Cull Off ZWrite Off
CGPROGRAM
//Physically based Standard lighting model, and enable shadows on all light types
//#pragma surface surf Standard fullforwardshadows
// Use shader model 3.0 target, to get nicer looking lighting
#pragma glsl
#pragma fragmentoption ARB_precision_hint_fastest
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#include "unityCG.cginc"
sampler2D _CameraDepthTexture;
uniform sampler2D _MainTex;
struct v2f {
float4 pos : SV_POSITION;
float4 scrPos:TEXCOORD0;
float2 uv : TEXCOORD1;
};
//Vertex Shader
v2f vert(appdata_base v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.scrPos = ComputeScreenPos(o.pos);
o.uv = v.texcoord.xy;
return o;
}
//Fragment Shader
float4 frag(v2f i) :COLOR{
int width = 2560;//画面宽度放大比率
int height = 1440;//画面高度放大比率
int frame = 128;//边框宽度
int RGBWidht = 1536;//RGB图宽度放大比率
int depthWidth = 768;//深度图宽度放大比率
int targetHeight = 1184;//输出图像部分高度
float x = i.uv.x*width;
float y = i.uv.y*height;
//生成四边框
if (x<frame)
return float4(1.0f, 1.0f, 1.0f, 1.0f);
if (x>width - frame)
return float4(1.0f, 1.0f, 1.0f, 1.0f);
if (y<frame)
return float4(1.0f, 1.0f, 1.0f, 1.0f);
if (y>height - frame)
return float4(1.0f, 1.0f, 1.0f, 1.0f);
y = (y-frame);
//分割画面
if (x < frame + RGBWidht) {
x = (x - frame) / RGBWidht;
y= y / targetHeight;
return tex2D(_MainTex, float2(x , y ));
}
else {
x= (x - frame - RGBWidht) ;
i.scrPos.x= x / depthWidth;
i.scrPos.y = y / targetHeight;
float4 uv = UNITY_PROJ_COORD(i.scrPos);
float depthValue = 1 - Linear01Depth(tex2Dproj(_CameraDepthTexture, uv).r);
return float4(depthValue, depthValue, depthValue, 1.0f);
}
return float4(0.0f, 0.0f, 0.0f, 1.0f);
}
ENDCG
}
}
FallBack "Diffuse"
}