Question

I am using glm maths library for the following problem: converting a 2d screen position into 3d world space.

In an attempt to track down the problem, I have simplified the code to the following:

    float screenW = 800.0f;
    float screenH = 600.0f;
    glm::vec4 viewport = glm::vec4(0.0f, 0.0f, screenW, screenH);
    glm::mat4 tmpView(1.0f);
    glm::mat4 tmpProj = glm::perspective( 90.0f, screenW/screenH, 0.1f, 100000.0f);
    glm::vec3 screenPos = glm::vec3(0.0f, 0.0f, 1.0f);
    glm::vec3 worldPos = glm::unProject(screenPos, tmpView, tmpProj, viewport);

Now with the glm::unProject in this case I would expect worldPos to be (0, 0, 1). However it is coming through as (127100.12, -95325.094, -95325.094).

Am I misunderstanding what glm::unProject is supposed to do? I have traced through the function and it seems to be working OK.

Was it helpful?

Solution

The Z component in screenPos corresponds to the values in the depth buffer. So 0.0f is the near clip plane and 1.0f is the far clip plane.

If you want to find the world pos that is one unit away from the screen, you can rescale the vector:

worldPos = worldPos / (worldPos.z * -1.f);

Note also that the screenPos of 0,0 designates the bottom left corner of the screen, while in worldPos 0,0 is the center of the screen. So 0,0,1 should give you -1.3333,-1,-1, and 400,300,1 should give you 0,0,-1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top