Sunday, May 7, 2017

Resizable Window for Pygame + OpenGL

Pygame + OpenGL provides a good platform for implementing OpenGL in Python language. It is straightforward to make the OpenGL window resizable. In the code below, we first detect the event of pygame video size change. When this event occurs, the display is reset with the width and height of the new window. The OpenGL perspective is also changed accordingly.

            if event.type == pygame.VIDEORESIZE:
                # For window size change
                surface = pygame.display.set_mode((event.w, event.h), DOUBLEBUF|OPENGL|RESIZABLE)
                gluPerspective(45, (1.0*event.w/event.h), 0.1, 50.0)
                glTranslatef(0.0,0.0, -5)

A sample Python program is listed below which shows a cube in OpenGL window which can be resized:


import pygame
from pygame.locals import *
import math

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

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )


def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()
    #print(repr(verticies[0][0])+','+repr(verticies[0][1]));
 
    glBegin( GL_POINTS );
    glColor3f(1,1,1); 
    for i in range(0,8):
         glVertex3f(verticies[i][0], verticies[i][1], verticies[i][2]);
    glEnd();


def main():
    pygame.init()
 
    display = (1000,750)
    surface = pygame.display.set_mode(display, DOUBLEBUF|OPENGL|RESIZABLE)
    gluPerspective(45, (1.0*display[0]/display[1]), 0.1, 50.0)
    glTranslatef(0.0,0.0, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.VIDEORESIZE:
                # For window size change
                surface = pygame.display.set_mode((event.w, event.h), DOUBLEBUF|OPENGL|RESIZABLE)
                gluPerspective(45, (1.0*event.w/event.h), 0.1, 50.0)
                glTranslatef(0.0,0.0, -5)

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube()

        pygame.display.flip()
        pygame.time.wait(10)


main()

No comments:

Post a Comment