2017-01-02 1910 views
1

在這裏,我有兩個循環。第一個循環處理圖形幾秒鐘,然後代碼進入第二個循環。我在第一個循環中通過glutMainLoopEvent處理圖形事件。在第二個循環開始之前,我想關閉圖形窗口。看起來命令glutLeaveMainLoop無法關閉窗口。在第一次循環之後,我應該用什麼其他函數強制關閉窗口?如何關閉一個openGL窗口

#include <stdio.h> 
#include <GL/freeglut.h> 
#include <boost/thread/thread.hpp> // for sleep 

void cback_render() 
{ 
    if(!glutGetWindow()) 
     return ; 
    static float rotations = 0; 

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

    glLoadIdentity(); 
    glRotatef(rotations, 0, 0, 1); 

    glBegin(GL_TRIANGLES); 
     glVertex3f(0,0,0); 
     glVertex3f(1,0,0); 
     glVertex3f(0,1,0); 
    glEnd(); 

    glutSwapBuffers(); 

    if (++rotations > 360) rotations -= 360; 
} 

void timer(int) 
{ 
    if(!glutGetWindow()) 
     return ; 
    glutPostRedisplay(); 
    glutMainLoopEvent(); 
    glutTimerFunc(30, timer, 1); 
} 

int main(int argc, char **argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH); 
    glutInitWindowPosition(100, 100); 
    glutInitWindowSize(512, 512); 
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); 

    glutCreateWindow("freegluttest"); 
    glutDisplayFunc (cback_render); 
    glutTimerFunc(30, timer, 1); 

    long i=0; 
    while(glutGetWindow() && i< 30) 
    { 
     printf("[%ld]\n",i); 
     i++; 
     glutMainLoopEvent(); 
     boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 
    } 
    glutMainLoopEvent(); 

    glutLeaveMainLoop(); // does not work 
    glutMainLoopEvent(); 

    // do something else .... 
    while(1) 
    { 
     // other calculations 
     boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 
    } 

    return 0; 
} 
+0

這是過剩還是freeglut?我對glut標籤感到困惑。 – CroCo

+0

@CroCo,謝謝你的提及。 – ar2015

+0

我對freeglut不熟悉,但是你確定在終止「glutLeaveMainLoop()」之後可以調用這個「glutMainLoopEvent()」嗎?另外,您是否嘗試通過單擊x標記按鈕來終止窗口? – CroCo

回答

0

從freeglut文檔確定在http://freeglut.sourceforge.net/docs/api.php#EventProcessing

功能使用的是glutLeaveMainLoop()是簡單地阻止過剩的主循環,如果它是由glutMainLoop()glutMainLoopEvent()啓動。

既然你在你的例子中自己控制循環,glutLeaveMainLoop()將不會做任何事情。

它的目的是爲了留下過剩的主循環如果過剩,你不是在控制它。

由於你有一個while(1)在100ms睡眠結束時,應用程序將不會做任何事情,當它到達那裏後,所有的框架已被渲染。如果你想破壞窗口使用一些窗口功能,如glutDestroyWindow()

+0

我認爲'glutDestroyWindow()'用於添加回調。我不認爲它會破壞窗戶。第二個循環代表我的程序將執行另一個計算。我無法刪除第二個循環。我嚴格需要關閉窗口而不終止程序。 – ar2015

+0

你確定你使用的是哪種版本的GLUT?檢查這個鏈接它說,函數'glutDestroyWindow()'完全符合我的想法。 https://www.opengl.org/resources/libraries/glut/spec3/node19.html – Harish

+0

對不起,我犯了一個錯誤。代碼使用: 'if(glutGetWindow()) \t \t \t glutDestroyWindow(glutGetWindow()); \t glutMainLoopEvent(); \t glutMainLoopEvent();' – ar2015