Convert mouse cursor into 3 dimensional coordinates

Hello,

I would like to convert mouse cursor coordinates (x, y) into 3 dimensional coordinates (x, y, z).
Note that my question is not about object picking technique but having sort of adjustable depth buffer for object drawing.

For example, I would like to create an object in x, y, z when I click the left mouse button.
So it should be x depth away from camera but object should be drawn in a position where exactly I click from the screen + depth buffer inside.

glm::mat4 viewMatrix = glm::lookAt(position, target, up);
glm::mat4 projectionMatrix = glm::perspective(glm::radians(cameraFrustum.fov), cameraFrustum.AR, cameraFrustum.nearPlane, cameraFrustum.farPlane);

void InputManager::mouse_cursor_callback(GLFWwindow* window, double xpos, double ypos) {
    GLfloat x = xpos;
    GLfloat y = glWindow.height - 1 - ypos;
    GLfloat z = 0.0f;
    glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);
    glWindow.glMouse = glm::unProject(glm::vec3(x, y, z),
				glWindow.camera->viewMatrix,
				glWindow.camera->projectionMatrix,
				glm::vec4(glWindow.x, glWindow.y, glWindow.width, glWindow.height));
}

I am trying to make it done with above but it returns z as 1 always.
Is there a way I can achieve my goal?

Thanks,

You are retrieving the depth value from a depth map, which will give you a value from 0 to 1, and what you want is a distance, so these are 2 different things.

You need to convert tour depth value in a range that is usable, in order to use it. so you will need to make 0 the camera near plane, and 1 the camera far plane, and everything in between should be the mid interval. But you cannont just perform a normal linear interpolation as these values are non linear, therefore you will need to convert it to a linear range as follows:

float linear_depth(float value){
	return (2.0 * near * far) / (far + near - value * (far-near));
}

but this result wont be what you need, you will need to to calculate a direction vector from your camera center, and the point you calculated with the code above, and the intersect sai direction ray with a plane in order to obtain the poin you want, the name is ray-plane intersection.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.