Search code examples
shaderdirectx-11semanticsdepth

z component of SV_POSITION in pixel shader


Hi i am newbie in directx and struggling with SV_POSITION in pixel shader.

So my pixel shader get input from SV_POSITION input(float4) as normal and i just guess that the z component of this input will give me the depth value of the pixel that this shader is dealing with. So i just did some simple test.

Pixel Shader

float4 main(PS_INPUT input) : SV_Target
{
    float Z = input.pos.z / input.pos.w;
    if (Z<0.1f)
        return RED;

    ...//draw texture
}

enter image description here enter image description here And it turns out that all obj appears RED except when i get camera really close to them. just opposite result that i expected.

So i just guess the output value of SV_POSITION in vertex shader will be differnt to input value of same semantic in pixel shader???

any advice would be appreciated.


Solution

  • You're guess is correct - the input to the pixel shader is not the same as the output from the vertex shader. The SV_Position value has some special semantics associated with it that prevents this from occuring.

    When doing rendering in Direct3D 11, there are several pipeline stages that take place before your data appears on the screen. These stages are a mostly programmable, but some are fixed by the system or the hardware. Those five fixed stages (in order of appearance) are the Input Assembler, the Tesselator, the Stream Output, the Rasterizer, and the Output Merger. These five stages make various changes to the input data according to specific information provided to Direct3D.

    Your problem involves the fourth stage, the Rasterizer. This stage takes the coordinates of the 3D geometry you're attempting to render and generates the pixel coordinates that will be affected by the rendering operation. It's these pixel coordinates that are passed to the pixel shader, with the shader being run once per generated pixel. The original coordinates created by the vertex shader have been consumed by the rasterizer.

    If you need to pass the depth value to the pixel shader, you can provide that information through a custom semantic, or try and access it from the value SV_Depth.

    You can find more information about the pipeline stages here.