-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwavefront.py
96 lines (74 loc) · 2.62 KB
/
wavefront.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import glm
import scene
def readVec2(data):
v = [float(val) for val in data[0:2]]
return glm.vec2(*v)
def readVec3(data):
v = [float(val) for val in data[0:3]]
return glm.vec3(*v)
class Parser(object):
def __init__(self, group):
self.vertices = [glm.vec3(0.0)]
self.normals = [glm.vec3(0.0)]
self.texcoords = [glm.vec2(0.0)]
self.mesh = None
self.group = group
def read_file(self, file):
for line in file:
self.parse(line)
def parse(self, line):
if line.startswith('#'):
return
values = line.split()
if len(values) < 2:
return
attrib = 'parse_%s' % values[0]
args = values[1:]
if hasattr(self, attrib):
parse_function = getattr(self, attrib)
parse_function(args)
# else:
# print("unable to read line:", line)
def parse_v(self, args):
self.vertices.append(readVec3(args))
def parse_vn(self, args):
self.normals.append(readVec3(args))
def parse_vt(self, args):
self.texcoords.append(readVec2(args))
def parse_o(self, args):
self.mesh = scene.Mesh(args[0])
self.group.add(self.mesh)
def parse_f(self, args):
if self.mesh is None:
self.parse_o(['unnamed mesh'])
prim0 = scene.Triangle(*[glm.vec3(0.0), glm.vec3(0.0), glm.vec3(0.0)])
self.mesh.add(prim0)
for i, v in enumerate(args):
vidx, tidx, nidx = (list(map(int, [j or 0
for j in v.split('/')])) +
[0, 0])[:3]
# wrap index around
if vidx < 0:
vidx = len(self.vertices) - vidx
if tidx < 0:
tidx = len(self.texcoords) - tidx
if nidx < 0:
nidx = len(self.normals) - nidx
if i < 3:
prim0.vertex(i, self.vertices[vidx], self.texcoords[tidx],
self.normals[nidx])
elif i == 3:
# second triangle for quad face
prim1 = scene.Triangle(prim0.vertices[0], prim0.vertices[2],
self.vertices[vidx])
prim1.texcoords = [
prim0.texcoords[0], prim0.texcoords[2],
self.texcoords[tidx]
]
prim1.normals = [
prim0.normals[0], prim0.normals[2], self.normals[nidx]
]
self.mesh.add(prim1)
def read(group, file):
parser = Parser(group)
parser.read_file(file)