Search Unity

Sampling depth buffer in vertex shader results in flickering

Discussion in 'Shaders' started by kulesz, Mar 19, 2020.

  1. kulesz

    kulesz

    Joined:
    Jul 1, 2012
    Posts:
    140
    Hi,

    I'm trying to sample a depth buffer inside a vertex shader to see if a particular vertex is hidden behind already drawn geometry. Than I'm planning to modify vertices according to the result.

    I've already got a working code sample from my other project - but it samples depth buffer in fragment shader, which is more common case. When I moved sampling part to the vertex shader, a strange flickering started to occur when object is drawn before other objects. When object is beind, everything seems fine.

    In the example below, if calculated depth is larger than one in buffer (so it's occluded by some other geometry) - quad is drawn in green. Otherwise it is red. Center of quad is the vertex that is sampled.

    Do I need to do something else to make it work?



    Code (CSharp):
    1. v2g vert(appdata_base v)
    2. {
    3.     v2g o;
    4.     o.pos = UnityObjectToClipPos(v.vertex);
    5.  
    6.     float4 screenPos = ComputeScreenPos(o.pos);
    7.     o.sceneZ = LinearEyeDepth(tex2Dlod(_CameraDepthTexture, float4(screenPos.xy / screenPos.w, 0, 0)));
    8.     COMPUTE_EYEDEPTH(o.pointZ);
    9.  
    10.     return o;
    11. }
    12.  
    13. float4 frag(g2f i) : SV_Target
    14. {
    15.     if (i.sceneZ > i.pointZ)
    16.         return float4(1, 0, 0, 1);
    17.     else
    18.         return float4(0, 1, 0, 1);
    19. }
    20.  
     
  2. kulesz

    kulesz

    Joined:
    Jul 1, 2012
    Posts:
    140
    OK, I've got it as soon as I have posted the question :)

    There was a Fallback "Diffuse" part at the end of entire shader, which caused it (I guess) to write to depth buffer itself. Thus the flickering.
     
    neoshaman and mgear like this.
  3. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,493
  4. iamvideep

    iamvideep

    Joined:
    Oct 27, 2017
    Posts:
    118
    What is the o.Point.z in the vertex shader? Where is the value of it being generated?