问题
I tried to read obj file with pyopengl but error come from glGenList(1) I just want to read the file and display in opengl Pls can you help me with full code;
Am tired of stack and error it took me 3hrd to post this from OpenGL.GL import * from tkinter import messagebox import sys
filename = input('pls input file path: ')
class OBJ:
def __init__(self, filename, swapyz=False):
"""Loads a Wavefront OBJ file. """
self.vertices = []
self.normals = []
self.texcoords = []
self.faces = []
material = None
for line in open(filename, "r"):
if line.startswith('#'): continue
values = line.split()
#print(values)
if not values: continue
if values[0] == 'v':
v = list(map(float, values[1:4]))
if swapyz:
v = (v[0], v[2], v[1])
self.vertices.append(v)
elif values[0] == 'vn':
v = list(map(float, values[1:4]))
if swapyz:
v = (v[0], v[2], v[1])
self.normals.append(v)
elif values[0] == 'vt':
self.texcoords.append(map(float, values[1:3]))
elif values[0] == 'mtllib':
continue
elif values[0] == 'f':
face = []
texcoords = []
norms = []
for v in values[1:]:
w = v.split('/')
face.append(int(w[0]))
if len(w) >= 2 and len(w[1]) > 0:
texcoords.append(int(w[1]))
else:
texcoords.append(0)
if len(w) >= 3 and len(w[2]) > 0:
norms.append(int(w[2]))
else:
norms.append(0)
self.faces.append((face, norms, texcoords))
#print(self.faces)
self.gl_list = glGenLists(0)
glNewList(self.gl_list, GL_COMPILE)
#glEnable(GL_TEXTURE_2D)
#glFrontFace(GL_CCW)
for face in self.faces:
vertices, normals, texture_coords = face
glBegin(GL_POLYGON)
for i in range(len(vertices)):
if normals[i] > 0:
glNormal3fv(self.normals[normals[i] - 1])
if texture_coords[i] > 0:
glTexCoord2fv(self.texcoords[texture_coords[i] - 1])
glVertex3fv(self.vertices[vertices[i] - 1])
glEnd()
glEndList()
OBJ(filename,swapyz=True)
回答1:
For any OpenGL instruction a valid and current OpenGL Context is required. Make sure that you have created the OpenGL window before creating the display list.
There is a 2nd issue, that will cause an error when glNewList
is called, after the 1st issue has been solved. You want to create more than 1 display lists objects, hence the argument to glGenLists has to be at least 1:
self.gl_list = glGenLists(0)
self.gl_list = glGenLists(1)
来源:https://stackoverflow.com/questions/62625561/pyopengl-reading-obj-file