2016-12-03 101 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