]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
Add a bunch of comments to the Mesh class in the Blender exporter
[libs/gl.git] / blender / io_mspgl / mesh.py
1 import bpy
2 import math
3 import mathutils
4
5 def make_edge_key(i1, i2):
6         return (min(i1, i2), max(i1, i2))
7
8 class Edge:
9         def __init__(self, edge):
10                 if edge.__class__==Edge:
11                         self._edge = edge._edge
12                         self.vertices = edge.vertices[:]
13                         self.smooth = edge.smooth
14                 else:
15                         self._edge = edge
16                         self.smooth = False
17                 self.key = edge.key
18                 self.faces = []
19
20         def __getattr__(self, attr):
21                 return getattr(self._edge, attr)
22
23         def check_smooth(self, limit):
24                 if len(self.faces)!=2:
25                         return
26
27                 d = self.faces[0].normal.dot(self.faces[1].normal)
28                 self.smooth = ((d>limit and self.faces[0].use_smooth and self.faces[1].use_smooth) or d>0.99995)
29
30         def other_face(self, f):
31                 if f.index==self.faces[0].index:
32                         if len(self.faces)>=2:
33                                 return self.faces[1]
34                         else:
35                                 return None
36                 else:
37                         return self.faces[0]
38
39         def other_vertex(self, v):
40                 if v.index==self.vertices[0].index:
41                         return self.vertices[1]
42                 else:
43                         return self.vertices[0]
44
45
46 class Vertex:
47         def __init__(self, vertex):
48                 if vertex.__class__==Vertex:
49                         self._vertex = vertex._vertex
50                         self.uvs = vertex.uvs[:]
51                         self.tan = vertex.tan
52                         self.bino = vertex.bino
53                 else:
54                         self._vertex = vertex
55                         self.uvs = []
56                         self.tan = None
57                         self.bino = None
58                 self.index = vertex.index
59                 self.co = vertex.co
60                 self.normal = vertex.normal
61                 self.flag = False
62                 self.edges = []
63                 self.faces = []
64                 self.groups = vertex.groups[:]
65
66         def __getattr__(self, attr):
67                 return getattr(self._vertex, attr)
68
69         def __cmp__(self, other):
70                 if other is None:
71                         return 1
72                 return cmp(self.index, other.index)
73
74
75 class VertexGroup:
76         def __init__(self, group):
77                 self._group = group
78                 self.group = group.group
79                 self.weight = group.weight
80
81         def __getattr__(self, attr):
82                 return getattr(self._group, attr)
83
84
85 class Face:
86         def __init__(self, face):
87                 self._face = face
88                 self.index = face.index
89                 self.edges = []
90                 self.vertices = face.vertices[:]
91                 self.uvs = []
92                 self.flag = False
93
94         def __getattr__(self, attr):
95                 return getattr(self._face, attr)
96
97         def __cmp__(self, other):
98                 if other is None:
99                         return 1
100                 return cmp(self.index, other.index)
101
102         def pivot_vertex(self, v):
103                 n = self.vertices.index(v)
104                 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
105
106         def pivot_vertices(self, *vt):
107                 flags = [(v in vt) for v in self.vertices]
108                 l = len(self.vertices)
109                 for i in range(l):
110                         if flags[i] and not flags[(i+l-1)%l]:
111                                 return self.vertices[i:]+self.vertices[:i]
112
113         def get_edge(self, v1, v2):     
114                 key = make_edge_key(v1.index, v2.index)
115                 for e in self.edges:
116                         if e.key==key:
117                                 return e
118                 raise KeyError("No edge %s"%(key,))
119
120         def other_edge(self, e, v):
121                 for d in self.edges:
122                         if d!=e and v in d.vertices:
123                                 return d
124
125         def get_neighbors(self):
126                 neighbors = [e.other_face(self) for e in self.edges]
127                 return list(filter(bool, neighbors))
128
129
130 class Line:
131         def __init__(self, e):
132                 self.edge = e
133                 self.vertices = e.vertices[:]
134                 self.flag = False
135
136
137 class UvLayer:
138         def __init__(self, arg):
139                 if type(arg)==str:
140                         self._layer = None
141                         self.name = arg
142                 else:
143                         self._layer = arg
144                         self.name = arg.name
145                         self.uvs = [d.uv for d in self.data]
146
147                 self.unit = None
148                 self.hidden = False
149
150                 dot = self.name.find('.')
151                 if dot>=0:
152                         ext = self.name[dot:]
153                         if ext.startswith(".unit") and ext[5:].isdigit():
154                                 self.unit = int(ext[5:])
155                         elif ext==".hidden":
156                                 self.hidden = True
157
158         def __getattr__(self, attr):
159                 return getattr(self._layer, attr)
160
161
162 class Mesh:
163         def __init__(self, mesh):
164                 self._mesh = mesh
165
166                 self.winding_test = mesh.winding_test
167                 self.tbn_vecs = mesh.tbn_vecs
168                 self.vertex_groups = mesh.vertex_groups
169
170                 # Clone basic data
171                 self.vertices = [Vertex(v) for v in self.vertices]
172                 for v in self.vertices:
173                         v.groups = [VertexGroup(g) for g in v.groups]
174
175                 self.faces = [Face(f) for f in self.polygons]
176                 self.edges = [Edge(e) for e in self.edges]
177                 self.loops = self.loops[:]
178                 self.materials = self.materials[:]
179
180                 # Clone only the desired UV layers
181                 if self.use_uv=='NONE' or not self.uv_layers:
182                         self.uv_layers = []
183                 else:
184                         self.uv_layers = [UvLayer(u) for u in self.uv_layers]
185                         self.uv_layers = sorted([u for u in self.uv_layers if not u.hidden], key=(lambda u: (u.unit or 1000, u.name)))
186
187                         if self.use_uv=='UNIT0':
188                                 self.uv_layers = [self.uv_layers[0]]
189
190                         # Assign texture unit numbers to UV layers that lack one
191                         next_unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
192                         for u in self.uv_layers:
193                                 if not u.unit:
194                                         u.unit = next_unit
195                                         next_unit += 1
196
197                 # Rewrite links between elements to point to cloned data, or create links
198                 # where they don't exist
199                 edge_map = {e.key: e for e in self.edges}
200                 for f in self.faces:
201                         if len(f.vertices)>4:
202                                 raise ValueError("Ngons are not supported")
203
204                         f.vertices = [self.vertices[i] for i in f.vertices]
205                         for v in f.vertices:
206                                 v.faces.append(f)
207
208                         for k in f.edge_keys:
209                                 e = edge_map[k]
210                                 e.faces.append(f)
211                                 f.edges.append(e)
212
213                 for e in self.edges:
214                         e.vertices = [self.vertices[i] for i in e.vertices]
215                         for v in e.vertices:
216                                 v.edges.append(e)
217
218                 # Store loose edges as lines
219                 if self.use_lines:
220                         self.lines = [Line(e) for e in self.edges if not e.faces]
221                 else:
222                         self.lines = []
223
224         def __getattr__(self, attr):
225                 return getattr(self._mesh, attr)
226
227         def transform(self, matrix):
228                 for v in self.vertices:
229                         v.co = matrix*v.co
230
231         def splice(self, other):
232                 if len(self.uv_layers)!=len(other.uv_layers):
233                         raise ValueError("Meshes have incompatible UV layers")
234                 for i, u in enumerate(self.uv_layers):
235                         if u.name!=other.uv_layers[i].name:
236                                 raise ValueError("Meshes have incompatible UV layers")
237
238                 # Merge materials and form a lookup from source material indices to the
239                 # merged material list
240                 material_map = []
241                 for m in other.materials:
242                         if m in self.materials:
243                                 material_map.append(self.materials.index(m))
244                         else:
245                                 material_map.append(len(self.materials))
246                                 self.materials.append(m)
247
248                 # Append data and adjust indices where necessary.  Since the data is
249                 # spliced from the source mesh, rebuilding references is not necessary.
250                 for i, u in enumerate(self.uv_layers):
251                         u.uvs += other.uv_layers[i].uvs
252
253                 offset = len(self.vertices)
254                 self.vertices += other.vertices
255                 for v in self.vertices[offset:]:
256                         v.index += offset
257
258                 loop_offset = len(self.loops)
259                 self.loops += other.loops
260
261                 offset = len(self.faces)
262                 self.faces += other.faces
263                 for f in self.faces[offset:]:
264                         f.index += offset
265                         f.loop_start += loop_offset
266                         f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total)
267                         if other.materials:
268                                 f.material_index = material_map[f.material_index]
269
270                 offset = len(self.edges)
271                 self.edges += other.edges
272                 for e in self.edges[offset:]:
273                         e.index += offset
274                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
275
276                 self.lines += other.lines
277
278         def prepare_smoothing(self, progress):
279                 smooth_limit = -1
280                 if self.smoothing=='NONE':
281                         for f in self.faces:
282                                 f.use_smooth = False
283
284                         smooth_limit = 1
285                 elif self.use_auto_smooth:
286                         smooth_limit = math.cos(self.auto_smooth_angle)
287
288                 for e in self.edges:
289                         e.check_smooth(smooth_limit)
290
291                 progress.push_task("Sharp edges", 0.0, 0.7)
292                 self.split_vertices(self.find_smooth_group, progress)
293
294                 if self.smoothing!='BLENDER':
295                         progress.set_task("Updating normals", 0.7, 1.0)
296                         self.compute_normals(progress)
297
298                 progress.pop_task()
299
300         def prepare_vertex_groups(self, obj):
301                 for v in self.vertices:
302                         if v.groups:
303                                 weight_sum = sum(g.weight for g in v.groups)
304                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
305                                 weight_scale = weight_sum/sum(g.weight for g in v.groups)
306                                 for g in v.groups:
307                                         g.weight *= weight_scale
308
309                 if obj.parent and obj.parent.type=="ARMATURE":
310                         armature = obj.parent.data
311                         bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
312                         group_index_map = {i: i for i in range(len(obj.vertex_groups))}
313                         for g in first_obj.vertex_groups:
314                                 if g.name in bone_indices:
315                                         group_index_map[g.index] = bone_indices[g.name]
316
317                         for v in self.vertices:
318                                 for g in v.groups:
319                                         g.group = group_index_map[g.group]
320
321         def prepare_uv(self, obj, progress):
322                 if obj.material_tex and self.use_uv!='NONE':
323                         layer = UvLayer("material_tex")
324
325                         if self.use_uv=='UNIT0':
326                                 self.uv_layers = [layer]
327                                 layer.unit = 0
328                         else:
329                                 self.uv_layers.append(layer)
330                                 layer.unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
331
332                         layer.uvs = [None]*len(self.loops)
333                         for f in self.faces:
334                                 uv = mathutils.Vector(((f.material_index+0.5)/len(self.materials), 0.5))
335                                 for i in f.loop_indices:
336                                         layer.uvs[i] = uv
337
338                 # Form a list of UV layers referenced by materials with the array atlas
339                 # property set
340                 array_uv_layers = [t.uv_layer for m in self.materials if m.array_atlas for t in m.texture_slots if t and t.texture_coords=='UV']
341                 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
342
343                 if array_uv_layers:
344                         for f in self.faces:
345                                 layer = 0
346                                 if f.material_index<len(self.materials):
347                                         mat = self.materials[f.material_index]
348                                         if mat and mat.array_atlas:
349                                                 layer = mat.array_layer
350
351                                 for l in array_uv_layers:
352                                         for i in f.loop_indices:
353                                                 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
354
355                 # Copy UVs from layers to faces
356                 for f in self.faces:
357                         for u in self.uv_layers:
358                                 f.uvs.append([u.uvs[i] for i in f.loop_indices])
359
360                 prog_count = len(self.uv_layers)
361                 prog_step = 0
362
363                 # Split by the UV layer used for TBN vectors first so connectivity
364                 # remains intact for TBN vector computation
365                 tbn_layer_index = -1
366                 if self.tbn_vecs:
367                         uv_names = [u.name for u in self.uv_layers]
368                         if self.tbn_uvtex in uv_names:
369                                 prog_count += 1
370                                 tbn_layer_index = uv_names.index(self.tbn_uvtex)
371                                 progress.push_task_slice("Computing TBN", 0, prog_count)
372                                 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
373                                 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
374                                 self.compute_tbn(tbn_layer_index, progress)
375                                 progress.pop_task()
376                                 prog_step = 2
377
378                 # Split by the remaining UV layers
379                 for i, u in enumerate(self.uv_layers):
380                         if i==tbn_layer_index:
381                                 continue
382
383                         progress.push_task_slice(u.name, prog_step, prog_count)
384                         self.split_vertices(self.find_uv_group, progress, i)
385                         progress.pop_task()
386                         prog_step += 1
387
388                 # Copy UVs from faces to vertices
389                 for v in self.vertices:
390                         if v.faces:
391                                 # All faces still connected to the vertex have the same UV value
392                                 f = v.faces[0]
393                                 i = f.vertices.index(v)
394                                 v.uvs = [u[i] for u in f.uvs]
395                         else:
396                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
397
398         def split_vertices(self, find_group_func, progress, *args):
399                 vertex_count = len(self.vertices)
400                 for i in range(vertex_count):
401                         v = self.vertices[i]
402                         for f in v.faces:
403                                 f.flag = False
404
405                         # Find all groups of faces on this vertex
406                         groups = []
407                         for f in v.faces:
408                                 if not f.flag:
409                                         groups.append(find_group_func(v, f, *args))
410
411                         # Give groups after the first separate copies of the vertex
412                         for g in groups[1:]:
413                                 nv = Vertex(v)
414                                 nv.index = len(self.vertices)
415                                 self.vertices.append(nv)
416
417                                 for e in v.edges:
418                                         e_faces_in_g = [f for f in e.faces if f in g]
419                                         if not e_faces_in_g:
420                                                 continue
421
422                                         if len(e_faces_in_g)<len(e.faces):
423                                                 # Create a copy of an edge at the boundary of the group
424                                                 ne = Edge(e)
425                                                 ne.index = len(self.edges)
426                                                 self.edges.append(ne)
427
428                                                 ne.other_vertex(v).edges.append(ne)
429
430                                                 for f in e_faces_in_g:
431                                                         e.faces.remove(f)
432                                                         f.edges[f.edges.index(e)] = ne
433                                                         ne.faces.append(f)
434
435                                                 e = ne
436
437                                         e.vertices[e.vertices.index(v)] = nv
438                                         nv.edges.append(e)
439
440                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
441
442                                 # Filter out any edges that were removed from the original vertex
443                                 v.edges = [e for e in v.edges if v in e.vertices]
444
445                                 for f in g:
446                                         v.faces.remove(f)
447                                         f.vertices[f.vertices.index(v)] = nv
448                                         nv.faces.append(f)
449
450                         progress.set_progress(i/vertex_count)
451
452         def find_smooth_group(self, vertex, face):
453                 face.flag = True
454
455                 edges = [e for e in face.edges if vertex in e.vertices]
456
457                 group = [face]
458                 for e in edges:
459                         f = face
460                         while e.smooth:
461                                 f = e.other_face(f)
462                                 if not f or f.flag:
463                                         break
464
465                                 f.flag = True
466                                 group.append(f)
467                                 e = f.other_edge(e, vertex)
468
469                 return group
470
471         def find_uv_group(self, vertex, face, index):
472                 uv = face.uvs[index][face.vertices.index(vertex)]
473                 face.flag = True
474
475                 group = [face]
476                 for f in vertex.faces:
477                         if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
478                                 f.flag = True
479                                 group.append(f)
480
481                 return group
482
483         def compute_normals(self, progress):
484                 for i, v in enumerate(self.vertices):
485                         v.normal = mathutils.Vector()
486                         for f in v.faces:
487                                 fv = f.pivot_vertices(v)
488                                 edge1 = fv[1].co-fv[0].co
489                                 edge2 = fv[-1].co-fv[0].co
490                                 if edge1.length and edge2.length:
491                                         # Use the angle between edges as a weighting factor.  This gives
492                                         # more consistent normals on bends with an inequal number of
493                                         # faces on each side.
494                                         v.normal += f.normal*edge1.angle(edge2)
495
496                         if v.normal.length:
497                                 v.normal.normalize()
498                         else:
499                                 v.normal = mathutils.Vector((0, 0, 1))
500
501                         progress.set_progress(i/len(self.vertices))
502
503         def compute_tbn(self, index, progress):
504                 # This function is called at an early stage during UV preparation when
505                 # face UVs are not available yet
506                 layer_uvs = self.uv_layers[index].uvs
507
508                 for i, v in enumerate(self.vertices):
509                         v.tan = mathutils.Vector()
510                         v.bino = mathutils.Vector()
511                         for f in v.faces:
512                                 vi = f.pivot_vertex(v)
513                                 uv0 = layer_uvs[f.loop_indices[vi[0]]]
514                                 uv1 = layer_uvs[f.loop_indices[vi[1]]]
515                                 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
516                                 du1 = uv1[0]-uv0[0]
517                                 du2 = uv2[0]-uv0[0]
518                                 dv1 = uv1[1]-uv0[1]
519                                 dv2 = uv2[1]-uv0[1]
520                                 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
521                                 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
522                                 div = (du1*dv2-du2*dv1)
523                                 if div:
524                                         mul = edge1.angle(edge2)/div
525                                         v.tan += (edge1*dv2-edge2*dv1)*mul
526                                         v.bino += (edge2*du1-edge1*du2)*mul
527
528                         if v.tan.length:
529                                 v.tan.normalize()
530                         if v.bino.length:
531                                 v.bino.normalize()
532
533                         progress.set_progress(i/len(self.vertices))
534
535         def drop_references(self):
536                 for v in self.vertices:
537                         v._vertex = None
538                         for g in v.groups:
539                                 g._group = None
540                 for e in self.edges:
541                         e._edge = None
542                 for f in self.faces:
543                         f._face = None
544                 for u in self.uv_layers:
545                         u._layer = None
546                 self._mesh = None
547
548         def create_strip(self, face, max_len):
549                 # Find an edge with another unused face next to it
550                 edge = None
551                 for e in face.edges:
552                         other = e.other_face(face)
553                         if other and not other.flag:
554                                 edge = e
555                                 break
556
557                 if not edge:
558                         return None
559
560                 # Add initial vertices so that we'll complete the edge on the first
561                 # iteration
562                 vertices = face.pivot_vertices(*edge.vertices)
563                 if len(vertices)==3:
564                         result = [vertices[-1], vertices[0]]
565                 else:
566                         result = [vertices[-2], vertices[-1]]
567
568                 while 1:
569                         face.flag = True
570
571                         vertices = face.pivot_vertices(*result[-2:])
572                         k = len(result)%2
573
574                         # Quads need special handling because the winding of every other
575                         # triangle in the strip is reversed
576                         if len(vertices)==4 and not k:
577                                 result.append(vertices[3])
578                         result.append(vertices[2])
579                         if len(vertices)==4 and k:
580                                 result.append(vertices[3])
581
582                         if len(result)>=max_len:
583                                 break
584
585                         # Hop over the last edge
586                         edge = face.get_edge(*result[-2:])
587                         face = edge.other_face(face)
588                         if not face or face.flag:
589                                 break
590
591                 return result
592
593 def create_mesh_from_object(context, obj, progress):
594         if obj.type!="MESH":
595                 raise Exception("Object is not a mesh")
596
597         progress.push_task("Preparing mesh", 0.0, 0.3)
598
599         objs = [(obj, mathutils.Matrix())]
600         i = 0
601         while i<len(objs):
602                 o, m = objs[i]
603                 i += 1
604                 for c in o.children:
605                         if c.type=="MESH" and c.compound:
606                                 objs.append((c, m*c.matrix_local))
607
608         mesh = None
609         bmeshes = []
610         for o, m in objs:
611                 bmesh = o.to_mesh(context.scene, True, "PREVIEW")
612                 bmeshes.append(bmesh)
613
614                 # Object.to_mesh does not copy custom properties
615                 bmesh.winding_test = o.data.winding_test
616                 bmesh.smoothing = o.data.smoothing
617                 bmesh.use_lines = o.data.use_lines
618                 bmesh.vertex_groups = o.data.vertex_groups
619                 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
620                 bmesh.use_uv = o.data.use_uv
621                 bmesh.tbn_vecs = o.data.tbn_vecs
622                 bmesh.tbn_uvtex = o.data.tbn_uvtex
623
624                 me = Mesh(bmesh)
625                 me.transform(m)
626
627                 if mesh:
628                         mesh.splice(me)
629                 else:
630                         mesh = me
631
632         progress.set_task("Smoothing", 0.3, 0.6)
633         mesh.prepare_smoothing(progress)
634         progress.set_task("Vertex groups", 0.6, 0.7)
635         mesh.prepare_vertex_groups(obj)
636         progress.set_task("Preparing UVs", 0.7, 1.0)
637         mesh.prepare_uv(obj, progress)
638
639         # Discard the temporary Blender meshes after making sure there's no
640         # references to the data
641         mesh.drop_references()
642         for m in bmeshes:
643                 bpy.data.meshes.remove(m)
644
645         progress.pop_task()
646
647         return mesh