Skip to content Skip to sidebar Skip to footer

Trying To Graph A Simple Square In Pyopengl

I'm trying to teach myself OpenGL using pyopengl and I'm struck on trying to render a simple 2D square centered at the origin. Whenever I set an array value greater than or equal t

Solution 1:

You need to set the projection matrix and the viewport. Python allows us to use a little bit functional programming to do it the sane way:

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

defdisplay(w, h):
    aspect = float(w)/float(h)
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-aspect * 5, aspect * 5, -5, 5, -1, 1)

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity()

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glBegin(GL_QUADS)
    glVertex3f(2,-2,0)
    glVertex3f(2,2,0)
    glVertex3f(-2,2,0)
    glVertex3f(-2,-2,0)
    glEnd()

    glutSwapBuffers()

defreshape(w, h):
    glutDisplayFunc(lambda: display(w, h))
    glutPostRedisplay();

if __name__ == '__main__':
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
    glutInitWindowSize(640,480)
    glutCreateWindow("Hello World :'D")

    glutReshapeFunc(reshape)
    glutIdleFunc(glutPostRedisplay)
    glutMainLoop()

Solution 2:

Try setting a non-default projection matrix:

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho( 0, 640, 0, 480, -10, 10)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    ...

Post a Comment for "Trying To Graph A Simple Square In Pyopengl"