Search code examples
shaderhlsl

HLSL getting world position of PIXEL


what I'm searching for is a simple way to get the world space coordinates for each pixel running throu the pixel shader.

I've found this topic: Pixel World Position

and it seems to work, but I'm yet not that used to shader language that I completly understand it.

Isn't there an easy way to solve this?

Kind regards, Marius


Solution

  • Easiest way is to pass it from the vertex shader as texture coordinate, like this (dx9 sample easy to convert to 10 if you use it):

    cbuffer cbmat : register( b0 )
    {
        float4x4 tW; //World transform
        float4x4 tWVP: //World * View * Projection
    };
    
    
    
    struct vs2ps
    {
        float4 Pos : POSITION;
        float4 TexCd : TEXCOORD0;
        float3 PosW : TEXCOORD1;
    };
    
    vs2ps VS(float4 Pos : POSITION,float4 TexCd : TEXCOORD0)
    {
        vs2ps Out;
        Out.Pos = mul(Pos, tWVP);
        Out.TexCd = TexCd;
        Out.PosW = mul(Pos, tW);
        return Out;
    }
    
    float4 PS(vs2ps In): COLOR
    {
        return float4(In.PosW,1.0f);
    }