- Home /
Depth maps and reconstructing the MVP matrix from a light
In order to try and simulate translucency I'm attempting to read values from a depth map created from the perspective of a light.
In my script I'm collecting the view and projection matrices from a temporary camera attached to the light and passing them into my shader to calculate the MVP from light space.
Shader.SetGlobalMatrix( "_LightViewMatrix", tempCamera.worldToCameraMatrix );
Shader.SetGlobalMatrix( "_LightProjectionMatrix", lightProjectionMatrix );
(lightProjectionMatrix is the camera projection matrix corrected as per http://answers.unity3d.com/questions/12713/how-do-i-reproduce-the-mvp-matrix.html)
I then multiply these together with the _Object2World matrix in the vertex shader to create my custom MVP. I then multiply the vertex model space position by this matrix and use these coordinates to gather depth values from my depth texture.
float4x4 MVP_MATRIX = _LightProjectionMatrix * _LightViewMatrix * modelMatrix;
output.lightTexCoord = mul( MVP_MATRIX, float4( v.vertex.xyz, 1.0 ) );
output.lightTexCoord = COMPUTE_POS( output.lightTexCoord );
// doing this in the fragment shader
// unconvinced this is right but I can't check it properly
float depth = tex2Dproj( _CameraDepthBuffer, UNITY_PROJ_COORD(output.lightTexCoord) );
However, I can't tell if this is working because my depth texture seems to be off. I'm testing this by overlaying a GUITexture over the screen with the contents of the render texture, so that it's the same size to check against distortion. However, as I move the light close to the target the depth buffer image arrives from the right (see image below), rather than directly in front as I'd expect. It moves across the screen from right to left as I get closer to the model.
Render texture code:
m_depthRenderTexture = RenderTexture.GetTemporary( Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32 );
tempCamera.targetTexture = m_depthRenderTexture;
tempCamera.RenderWithShader( m_shader, null );
m_shader simply uses a depth example from the docs
v2f vert( appdata_base v )
{
v2f o;
o.pos = mul( UNITY_MATRIX_MVP, v.vertex );
o.depth = ComputeScreenPos( o.pos );
return o;
}
half4 frag(v2f i) : COLOR
{
// UNITY_OUTPUT_DEPTH(i.depth);
//Grab the depth value from the depth texture
//Linear01Depth restricts this value to [0, 1]
float depth = Linear01Depth( tex2Dproj( _CameraDepthTexture, UNITY_PROJ_COORD(i.depth)).r);
half4 c;
c.r = depth;
c.g = depth;
c.b = depth;
c.a = 1;
return c;
}
Any ideas? This has been frustrating me for a long time.
Your answer
Follow this Question
Related Questions
Replacing and stacking shaders for some objects 1 Answer
Weird Material clashing in LWRP with the CustomForwardRenderData 0 Answers
Depth of field with multiple cameras 0 Answers
Question about Lists [C#] 0 Answers
Get RenderTexture 1 Answer