Search Unity

Z-Fighting (2D Shader newbie question)

Discussion in 'Shaders' started by Pebbl3s, Mar 11, 2019.

  1. Pebbl3s

    Pebbl3s

    Joined:
    Apr 13, 2013
    Posts:
    6
    I started looking into writing my own shader to solve one specific issue with my game.

    I'm making a 2D game with a perspective camera/orthographic sorting, which works great for everything until I have 2+ sprite renderers on the same Z-plane, which is causing the Z fighting.

    The obvious solution to this would be via Sorting Layers/Order In Layer/Render Queue. The only reason these options don't seem to work is that they all trump the Z-plane. What I would like is a solution that respects the Z-plane sorting above all else, with some sort of option to sort only when on the same Z-plane.

    I'm curious if there's any concept of doing this on the shader-level. Having to slightly adjust Z position to compensate for Z-fighting seems more like a work-around than a solution.
     
    jrumps likes this.
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    Nope, this is the correct solution.

    When you have shaders with ZWrite On and ZTest LEqual (which are also the defaults if they're not defined), coplanar geometry is a no no. Unless coplanar geometry is exactly the same triangles & vertex positions with exactly the same vertex shader operations applied to those vertices, you'll get z fighting.
     
    jrumps likes this.
  3. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    Distortion will have zero impact on this.* Distortion effects only affect the color, and not the depth buffer.

    * Unless the distortion shader is writing to the depth buffer, but that is just writing the geometry to the depth buffer, and the issues would happen with out without distortion still. Or you're hitting the bug on iOS devices where grab passes clears the depth buffer
     
    jrumps likes this.
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    It all comes down to draw order. The distortion can only affect what was drawn before the grab pass, which gets run just before the particles to make a copy of the screen contents. If the draw order changes, so too does what the grab pass see. Try using the frame debugger to step through rendering.
     
    jrumps likes this.
  5. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    In terms of draw order.

    Render Queue (set on shader or overridden on material) > Sorting Group > Sorting Layer > Sorting Order > Bounds Distance or Z Depth (depending on project / camera setup).

    ZWrite & ZTest supersede all of that in terms of the apparent order, as the depth buffer exists explicitly to enforce depth sorting of opaque fragments regardless of actual draw order.
     
    Malzar likes this.