Search Unity

Modify depth in surface shader?

Discussion in 'Shaders' started by SunnySunshine, Jun 29, 2015.

  1. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    976
    Is there a way to modify depth in a surface shader, so you can draw one object in front of another, even though it's behind?

    I've come across some methods, but none seem applicable for what I wish to do. I can't use render queues, because I only want the object farther away to be drawn in front if the distance between the objects' surfaces is less than 5 cm. I don't want to offset vertices and draw an invisible material on top (into z buffer), because that can cause a noticeable edge where nothing is rendered at all.

    I simply want to draw one object in front of another, if the distance in depth between their respective pixels is less than 5 cm.

    I found this, which seems to work:
    http://forum.unity3d.com/threads/writing-depth-value-in-fragment-program.66153/#post-2141579

    But hacking the output of a compiled shader doesn't seem to be the best way to go bout things. Is there really no other way?
     
    Last edited: Jun 29, 2015
  2. SunnySunshine

    SunnySunshine

    Joined:
    May 18, 2009
    Posts:
    976
  3. Zicandar

    Zicandar

    Joined:
    Feb 10, 2014
    Posts:
    388
    You could use the stencil buffer for this, not "easy" but probably easier then doing it with depth modification!
    My idea:
    1: Let the object in front be drawn, (and let it tag up the stencil buffer if only some objects are allowed to have other in front of them).
    2: Let the object that is behind be drawn with a stencil only pass, and offset it 5cm,. Now if you only want it to be drawn in front of THIS object, and nothing else, you can check the stencil buffer. Make sure to write to the stencil buffer if depth passes, so you know what pixels are less then 5cm behind.
    3: Draw the object, without a ZTest, and rely on the stencil to have checked it for you. If you only want the object to be "moved" forward when behind some objects, you will need a second pass that checks that the stencil buffer is NOT set, and does a normal z-test.

    I hope this makes sense, as I'm not very good at explaining it.