Search Unity

Writing to depth buffer. How to convert from DX to OpenGL?

Discussion in 'Shaders' started by DylanF, Nov 7, 2014.

  1. DylanF

    DylanF

    Joined:
    Jun 25, 2013
    Posts:
    55
    I'm writing to the depth buffer in a fragment shader (ray marcher) that works great on DX9 and DX11. The shader mostly works on OpenGL, the depth writing does have an effect, but the depths aren't correct.

    Here's the bottom of the fragment code, where the z buffer value is calculated from a world position. Can anyone tell me how to make this work correctly with OpenGL/GLSL?
    Code (csharp):
    1.  
    2. C2E2f_Output o;
    3.  o.col = float4(color,1.0);
    4. float4 projPos = mul(UNITY_MATRIX_VP, float4(impactWorldPosition, 1.0));
    5. o.dep = projPos.z / projPos.w;
    6. return o;
    7.  
    Behavior is the same on a mac with an intel gpu and a windows machine with a recent nvidia card (with the editor forced to run in opengl). I've tried doubling the depth before subtracting 1 from it (to convert to a -1 to 1 range), but that didn't do the trick.

    Pragmas used in the shader:
    Code (csharp):
    1.  
    2.     SubShader {
    3.         Tags { "Queue" = "Geometry+1" }
    4.    
    5.         Pass{
    6.             ZTest LEqual
    7.             Blend SrcAlpha OneMinusSrcAlpha
    8.        
    9.             Fog { Mode Off }
    10.             CGPROGRAM
    11.             #pragma target 3.0
    12.             #pragma glsl
    13.             #pragma exclude_renderers gles flash
    14.             #pragma vertex vert
    15.             #pragma fragment frag
    16. //          #pragma profileoption NumInstructionSlots=8192
    17.             #pragma profileoption NumMathInstructionSlots=2048
    18.            
    19.             #include "UnityCG.cginc"
    20.  
     
  2. DylanF

    DylanF

    Joined:
    Jun 25, 2013
    Posts:
    55
    This seems to be working. Not sure if it is reducing my depth buffer precision under opengl though:
    Code (csharp):
    1.  
    2. #if SHADER_API_OPENGL
    3.                 o.dep = depth*.5 + .5;
    4. #else
    5.                 o.dep = depth;
    6. #endif
    7.