pythonmacospyopenglfreeglutglutcreatewindow

How to make resizable windows with glut?


I am following the sample programs in the OpenGL Superbible, and they make it sound like windows created with glutCreateWindow will be resizable. I am using my own python-version of their Listing 2.2 below, and my windows are never resizable. I am using: PyOpenGL 3.1.7 on macOS Ventura (and "freeglut" (I think it was also the same before I installed freeglut).

Here is the listing:

from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *

def change_size(w, h):
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    aspect_ratio = w/h
    if w <= h:
        glOrtho(-100, 100, -100/aspect_ratio, 100/aspect_ratio, 1, -1)
    else:
        glOrtho(-100*aspect_ratio, 100*aspect_ratio, -100, 100, 1, -1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    
    
def render_scene():
    glClear(GL_COLOR_BUFFER_BIT)
    glColor(1,0,0,0)
    glRectf(-25,25,25,-25)
    glFlush()
        
def setup_rc():
    glClearColor(0, 0, 1, 1)
    
def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGBA)
    glutCreateWindow("Simple")
    glutDisplayFunc(render_scene)
    glutReshapeFunc(change_size)
    setup_rc()
    glutMainLoop()
    
main()

is there an easy way to create the main window so it is resizable?


Solution

  • glut is an old library and there are some known issues on various systems, such as a resizing bug on Mac. If you have problems with glut on your system, I recommend you to use glfw which is more recent.

    install glfw

    pip3 install glfw
    

    There are just a few changes needed to rewrite your code using glfw instead of glut:

    from OpenGL.GL import *
    from glfw.GLFW import *
    
    def change_size(window, _w, _h):
        w, h = glfwGetFramebufferSize(window)
        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        aspect_ratio = w/h
        if w <= h:
            glOrtho(-100, 100, -100/aspect_ratio, 100/aspect_ratio, 1, -1)
        else:
            glOrtho(-100*aspect_ratio, 100*aspect_ratio, -100, 100, 1, -1)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        
    def render_scene():
        glClear(GL_COLOR_BUFFER_BIT)
        glColor(1,0,0,0)
        glRectf(-25,25,25,-25)
        glFlush()
            
    def setup_rc():
        glClearColor(0, 0, 1, 1)
        
    def main():
        if glfwInit() == GLFW_FALSE:
            raise Exception("error: init glfw")
    
        glfwWindowHint(GLFW_SAMPLES, 8)
        window = glfwCreateWindow(640, 480, "Simple", None, None)
        glfwMakeContextCurrent(window)
    
        setup_rc()
        glfwSetWindowSizeCallback(window, change_size)  
        change_size(window, 640, 480)
        while not glfwWindowShouldClose(window):
            glfwPollEvents()
            render_scene()
            glfwSwapBuffers(window)
        
    main()