3

我对放大 OpenGL 中当前鼠标位置的任务感到绝望。我已经尝试了很多不同的事情并阅读了其他关于此的帖子,但我无法根据我的具体问题调整可能的解决方案。据我了解,您必须获取鼠标光标的当前窗口坐标,然后将它们取消投影以获取世界坐标,最后转换为这些世界坐标。

为了找到当前的鼠标位置,每次单击鼠标右键时,我都会在 GLUT 鼠标回调函数中使用以下代码。

if(button == 2)
{
    mouse_current_x = x;
    mouse_current_y = y;
...

接下来,在设置 ModelView 和 Projection 矩阵之前,我在显示函数中取消投影当前鼠标位置,这似乎也可以正常工作:

// Unproject Window Coordinates
float mouse_current_z;
glReadPixels(mouse_current_x, mouse_current_y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &mouse_current_z);
glm::vec3 windowCoordinates = glm::vec3(mouse_current_x, mouse_current_y, mouse_current_z);
glm::vec4 viewport = glm::vec4(0.0f, 0.0f, (float)width, (float)height);
glm::vec3 worldCoordinates = glm::unProject(windowCoordinates, modelViewMatrix, projectionMatrix, viewport);
printf("(%f, %f, %f)\n", worldCoordinates.x, worldCoordinates.y, worldCoordinates.z);

现在翻译是麻烦开始的地方。目前我正在绘制一个具有维度(dimensionX、dimensionY、dimensionZ)的立方体并转换到该立方体的中心,因此我的缩放也发生在中心点。我通过在 z 方向(小车)平移来实现缩放:

// Set ModelViewMatrix
modelViewMatrix = glm::mat4(1.0); // Start with the identity as the transformation matrix
modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3(0.0, 0.0, -translate_z)); // Zoom in or out by translating in z-direction based on user input 
modelViewMatrix = glm::rotate(modelViewMatrix, rotate_x, glm::vec3(1.0f, 0.0f, 0.0f)); // Rotate the whole szene in x-direction based on user input
modelViewMatrix = glm::rotate(modelViewMatrix,  rotate_y, glm::vec3(0.0f, 1.0f, 0.0f)); // Rotate the whole szene in y-direction based on user input
modelViewMatrix = glm::rotate(modelViewMatrix, -90.0f, glm::vec3(1.0f, 0.0f, 0.0f)); // Rotate the camera by 90 degrees in negative x-direction to get a frontal look on the szene
modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3(-dimensionX/2.0f, -dimensionY/2.0f, -dimensionZ/2.0f)); // Translate the origin to be the center of the cube
glBindBuffer(GL_UNIFORM_BUFFER, globalMatricesUBO);
glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(modelViewMatrix));
glBindBuffer(GL_UNIFORM_BUFFER, 0);

我试图通过转换到 worldCoordinates 向量来替换到立方体中心的转换,但这不起作用。我还尝试按宽度或高度缩放矢量。我在这里错过了一些重要的步骤吗?

4

1 回答 1

0

也许这不适用于您的情况。但对我来说,这似乎是处理这个问题的最好方法。使用 glulookat() 查看您已经找到的鼠标单击的 xyz 位置。然后把gluPerspective()改成更小的视角来实现实际的缩放。

于 2013-02-03T13:37:15.823 回答