2013-02-03 44 views
3

在OpenGL當前鼠標的位置,我絕望到放大在OpenGL當前鼠標位置的任務。我已經嘗試了很多不同的東西,並閱讀了其他文章,但我無法將可能的解決方案適應於我的具體問題。所以據我瞭解,你必須獲得鼠標光標的當前窗口座標,然後取消對它們進行投影以獲取世界座標,最後轉換爲這些世界座標。放大使用GLM功能

要查找當前鼠標的位置,我每次鼠標右鍵單擊時使用下面的代碼在我的GLUT鼠標回調函數。

// 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); 

現在的翻譯,其中:

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

接下來,我建立模型視圖和投影矩陣,這也似乎完全正常工作之前unproject在我的顯示功能當前鼠標位置麻煩開始了。目前,我正在繪製一個具有尺寸(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矢量替換翻譯立方體的中心,但這並沒有工作。我也嘗試通過寬度或高度來縮放矢量。 我錯過了一些關鍵的步驟嗎?

+0

我認爲,翻譯成立方體的中心後,你應該再回到原點,然後翻譯沿z – Deepak

+0

縮放到中心與上面貼的代碼好嗎工作。現在我想放大一些任意位置,問題是如何實現這一點。 – Schnigges

+0

您想在不旋轉相機的情況下放大不同於0,0,0的方向?那麼你將不得不將相機跳到新的位置,以便它仍然看着相同的「z」方向。更自然的變焦將是相機保持其世界位置,但改變它正在看的點。這需要輪換。你可以閱讀有關偏航,俯仰,旋轉。 – 2013-02-03 16:14:12

回答

0

也許這不會工作你的情況。但對我來說,這似乎是解決這個問題的最好方法。使用glulookat()查看已經找到的鼠標點擊的xyz位置。然後將gluPerspective()更改爲更小的視角以實現實際縮放。

+0

其實,我並不想達到改變變焦透視,所以這並不能真正回答我的問題。 – Schnigges

+0

@Schnigges:然後你的問題被錯誤地命名。 「縮放」的意思是「改變FOV」。如果您想通過移動相機來「縮放」,那不再是「放大」;這是*移動相機*。 –

+0

感謝您的更正,但我認爲您可以將此攝像機運動解釋爲任何縮放。這就是爲什麼我說「我通過在z方向翻譯(小車)來實現縮放」。 – Schnigges