-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseModel2.py
More file actions
430 lines (305 loc) · 15 KB
/
BaseModel2.py
File metadata and controls
430 lines (305 loc) · 15 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# imports all openGL functions
from OpenGL.GL import *
from numpy.ctypeslib import as_ctypes
from numpy import ndarray
# and we import a bunch of helper functions
from matutils import *
from material import *
from shaders import *
from texture import Texture
class BaseModel:
'''
Base class for all models, implementing the basic draw function for triangular meshes.
Inherit from this to create new models.
'''
def __init__(self, scene, scene_pos=poseMatrix(), attributes=([],[],[],[],[],[]), color=[1,1,1], visible=True):
'''
Initialises the model data
'''
print('+ Initializing {}'.format(self.__class__.__name__))
# if this flag is set to False, the model is not rendered
self.visible = visible
# store the scene reference
self.scene = scene
# store the type of primitive to draw
self.primitive = GL_TRIANGLES
# store the shader program for rendering this model
self.shader = None
self.vertices = attributes[0]
self.normals = attributes[1]
self.tex_coords = attributes[2]
self.faces = attributes[3]
self.textures = attributes[4]
self.material = attributes[5]
# if self.material is not None:
# self.textures.append(Texture(x.texture))
# dict of VBOs
self.vbos = {}
# dict of attributes
self.attributes = {}
# store the position of the model in the scene, ...
self.scene_pos = scene_pos
# We use a Vertex Array Object to pack all buffers for rendering in the GPU (see lecture on OpenGL)
self.vao = glGenVertexArrays(1)
# this buffer will be used to store indices, if using shared vertex representation
self.index_buffer = None
def bind_shader(self, shader):
'''
If a new shader is bound, we need to re-link it to ensure attributes are correctly linked.
'''
if self.shader is None or self.shader.name is not shader:
if isinstance(shader, str):
self.shader = PhongShader(shader)
else:
self.shader = shader
# bind all attributes and compile the shader
self.shader.compile(self.attributes)
def initialise_vbo(self, name, data):
print('Initialising VBO for attribute {}'.format(name))
if data is None:
print('(W) Warning in {}.bind_attribute(): Data array for attribute {} is None!'.format(
self.__class__.__name__, name))
return
# bind the location of the attribute in the GLSL program to the next index
# the name of the location must correspond to a 'in' variable in the GLSL vertex shader code
self.attributes[name] = len(self.vbos)
# create a buffer object...
self.vbos[name] = glGenBuffers(1)
# and bind it
glBindBuffer(GL_ARRAY_BUFFER, self.vbos[name])
# enable the attribute
glEnableVertexAttribArray(self.attributes[name])
# Associate the bound buffer to the corresponding input location in the shader
# Each instance of the vertex shader will get one row of the array
# so this can be processed in parallel!
glVertexAttribPointer(index=self.attributes[name], size=data.shape[1], type=GL_FLOAT, normalized=False,
stride=0, pointer=None)
# ... and we set the data in the buffer as the vertex array
glBufferData(GL_ARRAY_BUFFER, data, GL_STATIC_DRAW)
def bind(self):
'''
This method stores the vertex data in a Vertex Buffer Object (VBO) that can be uploaded
to the GPU at render time.
'''
# bind the VAO to retrieve all buffers and rendering context
glBindVertexArray(self.vao)
if self.vertices is None:
print('(W) Warning in {}.bind(): No vertex array!'.format(self.__class__.__name__))
# initialise vertex position VBO and link to shader program attribute
self.initialise_vbo('position', self.vertices)
self.initialise_vbo('normal', self.normals)
self.initialise_vbo('tex_coords', self.tex_coords)
# if indices are provided, put them in a buffer too
if self.faces is not None:
self.index_buffer = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.index_buffer)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, self.faces, GL_STATIC_DRAW)
# finally we unbind the VAO and VBO when we're done to avoid side effects
glBindVertexArray(0)
glBindBuffer(GL_ARRAY_BUFFER, 0)
def draw(self, Mp=poseMatrix()):
'''
Draws the model using OpenGL functions.
:param Mp: The model matrix of the parent object, for composite objects.
:param shaders: the shader program to use for drawing
'''
if self.visible:
if len(self.vertices) == 0:
print('(W) Warning in {}.draw(): No vertex array!'.format(self.__class__.__name__))
# bind the Vertex Array Object so that all buffers are bound correctly and following operations affect them
glBindVertexArray(self.vao)
# setup the shader program and provide it the Model, View and Projection matrices to use
# for rendering this model
self.shader.bind(
model=self,
M=np.matmul(Mp, self.scene_pos)
)
# bind all textures. Note that your shader needs to handle each one with a sampler object.
for unit, tex in enumerate(self.textures):
glActiveTexture(GL_TEXTURE0 + unit)
tex.bind()
# # check whether the data is stored as vertex array or index array
if self.faces is not None:
# draw the data in the buffer using the index array
faces_to_draw = self.faces.flatten().shape[0]
glDrawElements(self.primitive, faces_to_draw, GL_UNSIGNED_INT, None )
else:
# draw the data in the buffer using the vertex array ordering only.
glDrawArrays(GL_TRIANGLES, 0, len(self.vertices))
# unbind the shader to avoid side effects
glBindVertexArray(0)
def __del__(self):
'''
Release all VBO objects when finished.
'''
glDeleteVertexArrays(1, self.vao)
for vbo in self.vbos.values():
glDeleteBuffers(1, as_ctypes(vbo))
class DrawModelFromMesh(BaseModel):
'''
Base class for all models, inherit from this to create new models
'''
def __init__(self, scene, scene_pos, file_name, shader=None, color=[1,1,1]):
'''
Initialises the model data
'''
print('Loading mesh(es) from file: {}'.format(file_name))
self.vertices = []
self.normals = []
self.tex_coords = []
self.faces = []
self.textures = []
with open(file_name) as objfile:
self.process_lines(objfile)
self.format_attributes()
print('File read. Found {} vertices.', len(self.vertices))
BaseModel.__init__(self, scene=scene, scene_pos=scene_pos, attributes=(self.vertices, self.normals, self.tex_coords, self.faces, self.textures,self.material))
self.bind()
if shader is not None:
self.bind_shader(shader)
def load_material_library(self, file_name):
library = MaterialLibrary()
material = None
print('-- Loading material library {}'.format(file_name))
mtlfile = open(file_name)
for line in mtlfile:
fields = line.split()
if len(fields) != 0:
if fields[0] == 'newmtl':
if material is not None:
library.add_material(material)
material = Material(fields[1])
print('Found material definition: {}'.format(material.name))
elif fields[0] == 'Ka':
material.Ka = np.array(fields[1:], 'f')
elif fields[0] == 'Kd':
material.Kd = np.array(fields[1:], 'f')
elif fields[0] == 'Ks':
material.Ks = np.array(fields[1:], 'f')
elif fields[0] == 'Ns':
material.Ns = float(fields[1])
elif fields[0] == 'd':
material.d = float(fields[1])
elif fields[0] == 'Tr':
material.d = 1.0 - float(fields[1])
elif fields[0] == 'illum':
material.illumination = int(fields[1])
elif fields[0] == 'map_Kd':
material.texture = fields[1]
library.add_material(material)
print('- Done, loaded {} materials'.format(len(library.materials)))
return library
def process_lines(self, objfile):
'''
Function for reading the Blender3D object file, line by line. Clearly
minimalistic and slow as it is, but it will do the job nicely for this course.
'''
for line in objfile:
feature = line.split()
match feature[0]:
case "v":
if len(feature) != 4:
print('FATAL ERROR: 3 entries expected for vertex!!')
return None
self.vertices.append([float(value) for value in feature[1:]])
case "vn":
if len(feature) != 4:
print('FATAL ERROR: 3 entries expected for normal!!')
return None
self.normals.append([float(value) for value in feature[1:]])
case "vt":
if len(feature) != 3:
print('FATAL ERROR: 2 entries expected for vertex texture!!')
return None
self.tex_coords.append([float(value) for value in feature[1:]])
case "mtllib":
if len(feature) != 2:
print('FATAL ERROR: material library file name missing!!')
return None
material_library = (self.load_material_library("models/" + feature[1]))
case "usemtl":
if len(feature) != 2:
print('FATAL ERROR: material name missing!!')
return None
material = material_library.materials[material_library.names[feature[1]]]
self.material = material
if material.texture is not None:
self.textures.append(Texture(material.texture))
case "f":
tri_count = len(feature) - 1
face_details=[]
face_info=[]
for i in range(3):
for j in range(tri_count):
face_info.append(np.uint32((feature[i+1]).split("/")[j]))
face_details.append(face_info)
face_info=[]
self.faces.append(face_details)
def calculate_normals(self):
'''
method to calculate normals from the mesh faces.
Use the approach discussed in class:
1. calculate normal for each face using cross product
2. set each vertex normal as the average of the normals over all faces it belongs to.
'''
self.normals = np.zeros((self.vertices.shape[0], 3), dtype='f')
if self.tex_coords is not None:
self.tangents = np.zeros((self.vertices.shape[0], 3), dtype='f')
self.binormals = np.zeros((self.vertices.shape[0], 3), dtype='f')
for f in range(self.faces.shape[0]):
# first calculate the face normal using the cross product of the triangle's sides
a = self.vertices[self.faces[f, 1]] - self.vertices[self.faces[f, 0]]
b = self.vertices[self.faces[f, 2]] - self.vertices[self.faces[f, 0]]
face_normal = np.cross(a, b)
# tangent
if self.tex_coords is not None:
txa = self.tex_coords[self.faces[f, 1], :] - self.tex_coords[self.faces[f, 0], :]
txb = self.tex_coords[self.faces[f, 2], :] - self.tex_coords[self.faces[f, 0], :]
face_tangent = txb[0]*a - txa[0]*b
face_binormal = -txb[1]*a + txa[1]*b
# blend normal on all 3 vertices
for j in range(3):
self.normals[self.faces[f, j], :] += face_normal
if self.tex_coords is not None:
self.tangents[self.faces[f, j], :] += face_tangent
self.binormals[self.faces[f, j], :] += face_binormal
# finally we need to normalise the vectors
self.normals /= np.linalg.norm(self.normals, axis=1, keepdims=True)
if self.tex_coords is not None:
self.tangents /= np.linalg.norm(self.tangents, axis=1, keepdims=True)
self.binormals /= np.linalg.norm(self.binormals, axis=1, keepdims=True)
def format_attributes(self):
# select faces for this mesh
self.faces = np.asarray(self.faces)
# and vertices
vmax = np.max(self.faces[:, :, 0].flatten())
vmin = np.min(self.faces[:, :, 0].flatten()) - 1
self.vertices = np.asarray(np.array(self.vertices)[vmin:vmax, :], dtype=np.float32)
if self.tex_coords is not None:
self.tex_coords = np.asarray(self.tex_coords, dtype=np.float32)
textures = self.fix_blender_textures()
if textures is not None:
self.tex_coords = np.array(textures[vmin:vmax, :])
self.normals = np.asarray(self.normals, dtype='f')
self.faces = self.faces[:, :, 0] - vmin - 1
# else:
# self.calculate_normals()
# fix blender texture indexing
def fix_blender_textures(self):
'''
Corrects the indexing of textures in Blender file for OpenGL.
Blender allows for multiple indexing of vertices and textures, which is not supported by OpenGL.
This function ensures that indexing is consistent.
:param textures: Original Blender texture UV values
:param faces: Blender faces multiple-index
:return: a new texture array indexed according to vertices.
'''
# (OpenGL, unlike Blender, does not allow for multiple indexing!)
if self.faces.shape[2] == 1:
print('(W) No texture indices provided, setting texture coordinate array as None!')
return None
new_textures = np.zeros((self.vertices.shape[0], 2), dtype='f')
for f in range(self.faces.shape[0]):
for j in range(self.faces.shape[1]):
new_textures[self.faces[f, j, 0] - 1, :] = self.tex_coords[self.faces[f, j, 1] - 1, :]
return new_textures