🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Convert coordinate to screen with projection matrix

Started by
2 comments, last by Josh Klint 1 year, 8 months ago

I have this code I use to convert a point relative to the camera into a screen coordinate (each axes between 0 and 1, like a texture coordinate):

vec3 CameraPositionToScreenCoord(in vec3 position)
{
    float aspect = BufferSize.x / BufferSize.y;
    position.x /= position.z / CameraZoom;
    position.y /= -position.z / CameraZoom;
    position.x /= 2.0f * aspect;
    position.y /= 2.0f;
    position.xy += 0.5f;
    return position;
}

This only works with an orthographic matrix, and as I understand it some VR headsets use funny sheared projection matrices. However, if I do a matrix multiplication of the position times the projection matrix, the results don't seem to be mapped to the screen correctly.

Here is the coordinate visualized using my code above:

Here is the result if I multiply the position by the projection matrix, just like in the vertex shader:

What am I missing here?

10x Faster Performance for VR: www.ultraengine.com

Advertisement

Getting closer, but it looks like the Z-position makes no difference in the equation:

        //Convert vertex position to gl_Position
        vec4 glposition = projectionmatrix * vec4(position, 1.0f);
        glposition.z = (glposition.z + glposition.w) * 0.5f;

        //Convert gl_Position to gl_FragCoord
        vec4 glfragcoord = glposition;
        glfragcoord.xy = vec2(0) + BufferSize * (1.0f + glposition.xy / glposition.w) * 0.5f;

        //Convert to visible texcoords;
        glfragcoord.xy /= BufferSize;

10x Faster Performance for VR: www.ultraengine.com

Actually, the last shot above is the correct result. >_<

10x Faster Performance for VR: www.ultraengine.com

This topic is closed to new replies.

Advertisement