Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Using CameraDepthTexture to calculate frag mask operation

Discussion in 'Shaders' started by WildStyle69, Feb 12, 2020.

  1. WildStyle69

    WildStyle69

    Joined:
    Jul 20, 2016
    Posts:
    318
    Hi folks,

    So I (naively) thought I can use the depth information from the _CameraDepthTexture in my frag shader, to calculate if vertices are visible or behind (masked) by another object in the scene. Goal is discard any pixels in the frag shader operation that are occluded by another object (with a higher depth value).

    I've read a load on the subject today, but am still struggling to get any result.

    In my vert method, am setting up the data to use in the frag operation:

    Code (CSharp):
    1. v2f vert(appdata v)
    2. {
    3.     v2f o;
    4.     o.color = float4(0, 0, 0, 1);
    5.     o.pos = UnityObjectToClipPos(v.vertex);
    6.     o.uv = v.texcoord.xy;
    7.  
    8.     float4 worldPos = mul(UNITY_MATRIX_M, v.vertex);
    9.     o.screenPos  = ComputeScreenPos(o.pos);
    10.     o.screenPos.z = -mul(UNITY_MATRIX_V, worldPos).z;
    11.  
    12.     o.depth = -mul(UNITY_MATRIX_V, mul(unity_ObjectToWorld, v.vertex)).z;
    13.  
    14.     return o;
    15. }
    Then in the frag method am looking to calcuate and discard the pixels:

    Code (CSharp):
    1. float4 frag(v2f input) : COLOR
    2. {
    3.     float sceneDepth = LinearEyeDepth(SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, UNITY_PROJ_COORD(input.screenPos)));
    4.     clip(sceneDepth - input.depth);
    5.  
    6.    .... rest of frag shader code continues.
    7. }
    Might be worth mentioning - I'm working in VR, and have confirmed that the _CameraDepthTexture is sending depth information.

    Am I going about this the right way, or completely in the wrong direction?

    // Wildstyle
     
  2. WildStyle69

    WildStyle69

    Joined:
    Jul 20, 2016
    Posts:
    318
    I've found another solution to achieve my objectives - create a dynamic texture mask from the depth buffer, then use that as an alpha mask in the frag shader.

    // Wildstyle