2016-12-03 103 views
0

下面是我想要實現的,在下面的代碼中我有一個名爲switch_2D_3D的標誌,當它是真的時,我切換到2D模式,否則切換到3D。從2D切換到3D時的OpenGL

void reshape(GLsizei width, GLsizei height) 
{ 
    if (switch_2D_3D) 
    { 
     // GLsizei for non-negative integer 
     // Compute aspect ratio of the new window 
     if (height == 0) 
      height = 1;    // To prevent divide by 0 

     GLfloat aspect = (GLfloat)width/(GLfloat)height; 

     // Reset transformations 
     glLoadIdentity(); 

     // Set the aspect ratio of the clipping area to match the viewport 
     glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix 

     // Set the viewport to cover the new window 
     glViewport(0, 0, width, height); 

     if (width >= height) 
     { 
      // aspect >= 1, set the height from -1 to 1, with larger width 
      gluOrtho2D(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0); 
     } 
     else 
     { 
      // aspect < 1, set the width to -1 to 1, with larger height 
      gluOrtho2D(-1.0, 1.0, -1.0/aspect, 1.0/aspect); 
     } 

     winWidth = width; 
     winHeight = height; 
    } // 2D mode 
    else 
    { 
     // Prevent a divide by zero, when window is too short 
     // (you cant make a window of zero width). 
     if (height == 0) 
      height = 1; 

     float ratio = width * 1.0/height; 

     // Use the Projection Matrix 
     glMatrixMode(GL_PROJECTION); 

     // Reset Matrix 
     glLoadIdentity(); 

     // Set the viewport to be the entire window 
     glViewport(0, 0, width, height); 

     // Set the correct perspective. 
     gluPerspective(45.0f, ratio, 0.1f, 100.0f); 

     // Get Back to the Modelview 
     glMatrixMode(GL_MODELVIEW); 

     winWidth = width; 
     winHeight = height; 
    }// 3D mode 
} 

一切完美的作品只是在2D模式下繪圖時,但是當我換旗切換到3D模式,來這裏的問題

我每次調整窗口的大小,我畫的東西3D場景(例如立方體)會變得越來越小,最終消失,爲什麼會發生這種情況

如果我切換回2D模式,2D模式下的所有東西仍然可以正常工作,問題出在3D模式

另外,如果我sta rt將標誌設置爲false的程序,我會看到一個立方體,並且每次調整窗口大小時它都會變小。

爲什麼會發生這種情況?

+0

我想你應該停止思考「2D vs. 3D」。這種區分是毫無意義的,要講真相。你在那裏切換的是投影,當然你也可以在3D場景中使用正射投影。 – datenwolf

回答

0

你應該看看你的glLoadIdentity()/glMatrixMode()的相互作用。

現在,你有兩種不同的行爲:

在2D:你當你輸入的功能,想必GL_MODELVIEW,這將導致gluOrtho2D呼叫「堆起來」無論是主動重置矩陣。

在3D中:您總是重置投影矩陣,這似乎更加正確。

嘗試僅在第一個路徑(2D)中交換glLoadIdentityglMatrixMode調用的順序。

明智的做法是在實際修改之前始終明確設置要修改的矩陣。

+0

感謝您的回答。我嘗試過,但現在我再也看不到2D場景了,3D場景中的立方體仍然變小。 – RushSykes

+0

好吧,根據你如何處理旋轉,你可能想重新設置模型視圖矩陣,就像你之前做的那樣。這不是一個好主意,但是當你調用呼叫順序 – ltjax

+0

時,這就改變了哦,我知道了,我使用兩種場景的投影模式矩陣,所以我不應該再次設置矩陣模型視圖....再次感謝! – RushSykes