Bramanta
Bramanta

Reputation: 451

How to load obj file to PyOpenGL

I'm trying to load .obj file to PyOpenGL and pygame referring to http://www.pygame.org/wiki/OBJFileLoader and https://github.com/yarolig/OBJFileLoader

I've tried to change the perspective and do translation but the object can't be seen

here is what i've come so far

import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from objloader import *


if __name__ == "__main__":
    pygame.init()
    display = (1000,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

    gluPerspective(90, (display[0]/display[1]), 1, 100)

    glTranslatef(0.0,0.0, -10)

    # import file
    model = OBJ('model.obj')

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        
        # draw model
        glPushMatrix()
        glTranslatef(10, 10, 10)
        model.render()
        glPopMatrix()
        
        pygame.display.flip()
        pygame.time.wait(10)

Upvotes: 1

Views: 5199

Answers (1)

Rabbid76
Rabbid76

Reputation: 210928

OpenGL has different current matrices, see glMatrixMode. Each vertex coordinate is transformed by the model view matrix and the projection matrix.
I recommend to set the projection matrix to the current GL_PROJECTION and the view matrix to the current GL_MODELVIEW:

if __name__ == "__main__":
    # [...]

    glMatrixMode(GL_PROJECTION) # <---- specify projection matrix
    gluPerspective(90, (display[0]/display[1]), 0.1, 100)

    glMatrixMode(GL_MODELVIEW)  # <---- specify model view matrix
    glTranslatef(0.0, 0.0, -5)

Anyway you have to remove the model transformation, because the model transformation moves the object out of the Viewing frustum and causes that the model is clipped:

if __name__ == "__main__":
    # [...]

    while True:
        # [...]

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        
        # draw model
        glPushMatrix()
        #glTranslatef(10, 10, 10) <--- DELETE
        model.render()
        glPopMatrix()

Note, the Wavefront OBJ loader requires a .obj and a .mtl file to load the model correctly.

Upvotes: 1

Related Questions