]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
754e6ffc2d35460c0e474e7fc02e70b3e62c9568
[libs/gl.git] / blender / io_mspgl / mesh.py
1 import bpy
2 import math
3 import mathutils
4 import itertools
5
6 def make_edge_key(i1, i2):
7         return (min(i1, i2), max(i1, i2))
8
9 class Edge:
10         def __init__(self, edge):
11                 if edge.__class__==Edge:
12                         self.smooth = edge.smooth
13                 else:
14                         self.smooth = False
15                 if edge:
16                         self.vertices = edge.vertices[:]
17                         self.key = edge.key
18                 else:
19                         self.vertices = []
20                         self.key = None
21                 self.faces = []
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.uvs = vertex.uvs[:]
50                         self.tan = vertex.tan
51                         self.bino = vertex.bino
52                 else:
53                         self.uvs = []
54                         self.tan = None
55                         self.bino = None
56                 self.index = vertex.index
57                 self.co = mathutils.Vector(vertex.co)
58                 self.normal = mathutils.Vector(vertex.normal)
59                 self.color = None
60                 self.flag = False
61                 self.edges = []
62                 self.faces = []
63                 self.groups = vertex.groups[:]
64
65         def __cmp__(self, other):
66                 if other is None:
67                         return 1
68                 return cmp(self.index, other.index)
69
70
71 class VertexGroup:
72         def __init__(self, group):
73                 if group:
74                         self.group = group.group
75                         self.weight = group.weight
76                 else:
77                         self.group = 0
78                         self.weight = 0.0
79
80
81 class Face:
82         def __init__(self, face):
83                 self.index = face.index
84                 self.edges = []
85                 self.edge_keys = face.edge_keys
86                 self.vertices = face.vertices[:]
87                 self.loop_indices = face.loop_indices
88                 self.normal = face.normal
89                 self.use_smooth = face.use_smooth
90                 self.material_index = face.material_index
91                 self.flag = False
92
93         def __cmp__(self, other):
94                 if other is None:
95                         return 1
96                 return cmp(self.index, other.index)
97
98         def pivot_vertex(self, v):
99                 n = self.vertices.index(v)
100                 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
101
102         def get_loop_index(self, v):
103                 return self.loop_indices[self.vertices.index(v)]
104
105         def get_edge(self, v1, v2):
106                 key = make_edge_key(v1.index, v2.index)
107                 for e in self.edges:
108                         if e.key==key:
109                                 return e
110                 raise KeyError("No edge %s"%(key,))
111
112         def other_edge(self, e, v):
113                 for d in self.edges:
114                         if d!=e and v in d.vertices:
115                                 return d
116
117         def get_neighbors(self):
118                 neighbors = [e.other_face(self) for e in self.edges]
119                 return list(filter(bool, neighbors))
120
121
122 class Line:
123         def __init__(self, e):
124                 self.edge = e
125                 self.vertices = e.vertices[:]
126                 self.flag = False
127
128
129 class UvLayer:
130         def __init__(self, arg):
131                 if type(arg)==str:
132                         self.name = arg
133                         self.uvs = []
134                 else:
135                         self.name = arg.name
136                         self.uvs = [mathutils.Vector(d.uv) for d in arg.data]
137
138                 self.unit = None
139                 self.hidden = False
140
141                 dot = self.name.find('.')
142                 if dot>=0:
143                         ext = self.name[dot:]
144                         if ext.startswith(".unit") and ext[5:].isdigit():
145                                 self.unit = int(ext[5:])
146                         elif ext==".hidden":
147                                 self.hidden = True
148
149
150 class ColorLayer:
151         def __init__(self, l):
152                 self.name = l.name
153                 self.colors = [c.color[:] for c in l.data]
154
155
156 class Mesh:
157         def __init__(self, mesh):
158                 self.name = mesh.name
159
160                 self.winding_test = mesh.winding_test
161                 self.smoothing = mesh.smoothing
162                 self.use_uv = mesh.use_uv
163                 self.tbn_vecs = mesh.tbn_vecs
164                 self.tbn_uvtex = mesh.tbn_uvtex
165                 self.vertex_groups = mesh.vertex_groups
166
167                 # Clone basic data
168                 self.vertices = [Vertex(v) for v in mesh.vertices]
169                 if self.vertex_groups:
170                         for v in self.vertices:
171                                 v.groups = [VertexGroup(g) for g in v.groups]
172
173                 self.faces = [Face(f) for f in mesh.polygons]
174                 self.edges = [Edge(e) for e in mesh.edges]
175                 self.loops = mesh.loops[:]
176                 self.materials = mesh.materials[:]
177
178                 self.use_auto_smooth = mesh.use_auto_smooth
179                 self.auto_smooth_angle = mesh.auto_smooth_angle
180                 self.max_groups_per_vertex = mesh.max_groups_per_vertex
181
182                 # Clone only the desired UV layers
183                 if mesh.use_uv=='NONE' or not mesh.uv_layers:
184                         self.uv_layers = []
185                 else:
186                         self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
187
188                         # Assign texture unit numbers to UV layers that lack one
189                         missing_unit = [u for u in self.uv_layers if u.unit is None]
190                         if missing_unit:
191                                 missing_unit = sorted(missing_unit, key=(lambda u: u.name))
192                                 used_units = [u.unit for u in self.uv_layers if u.unit is not None]
193                                 for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)):
194                                         u.unit = n
195
196                         self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
197
198                         if mesh.use_uv=='UNIT0':
199                                 self.uv_layers = [self.uv_layers[0]]
200                                 if self.uv_layers[0].unit!=0:
201                                         self.uv_layers = []
202
203                 self.colors = None
204                 if mesh.vertex_colors:
205                         self.colors = ColorLayer(mesh.vertex_colors[0])
206
207                 # Rewrite links between elements to point to cloned data, or create links
208                 # where they don't exist
209                 edge_map = {e.key: e for e in self.edges}
210                 for f in self.faces:
211                         if len(f.vertices)>4:
212                                 raise ValueError("Ngons are not supported")
213
214                         f.vertices = [self.vertices[i] for i in f.vertices]
215                         for v in f.vertices:
216                                 v.faces.append(f)
217
218                         for k in f.edge_keys:
219                                 e = edge_map[k]
220                                 e.faces.append(f)
221                                 f.edges.append(e)
222
223                 for e in self.edges:
224                         e.vertices = [self.vertices[i] for i in e.vertices]
225                         for v in e.vertices:
226                                 v.edges.append(e)
227
228                 # Store loose edges as lines
229                 if mesh.use_lines:
230                         self.lines = [Line(e) for e in self.edges if not e.faces]
231                 else:
232                         self.lines = []
233
234                 self.vertex_sequence = []
235
236         def transform(self, matrix):
237                 for v in self.vertices:
238                         v.co = matrix@v.co
239
240         def splice(self, other):
241                 if len(self.uv_layers)!=len(other.uv_layers):
242                         raise ValueError("Meshes have incompatible UV layers")
243                 for i, u in enumerate(self.uv_layers):
244                         if u.name!=other.uv_layers[i].name:
245                                 raise ValueError("Meshes have incompatible UV layers")
246
247                 # Merge materials and form a lookup from source material indices to the
248                 # merged material list
249                 material_atlas = []
250                 for m in other.materials:
251                         if m in self.materials:
252                                 material_atlas.append(self.materials.index(m))
253                         else:
254                                 material_atlas.append(len(self.materials))
255                                 self.materials.append(m)
256
257                 # Append data and adjust indices where necessary.  Since the data is
258                 # spliced from the source mesh, rebuilding references is not necessary.
259                 for i, u in enumerate(self.uv_layers):
260                         u.uvs += other.uv_layers[i].uvs
261
262                 if self.colors:
263                         if other.colors:
264                                 self.colors.colors += other.colors.colors
265                         else:
266                                 self.colors.colors += [(1.0, 1.0, 1.0, 1.0)]*len(other.loops)
267                 elif other.colors:
268                         self.colors = ColorLayer(other.colors.name)
269                         self.colors.colors = [(1.0, 1.0, 1.0, 1.0)]*len(self.loops)+other.colors.colors
270
271                 offset = len(self.vertices)
272                 self.vertices += other.vertices
273                 for v in self.vertices[offset:]:
274                         v.index += offset
275
276                 loop_offset = len(self.loops)
277                 self.loops += other.loops
278
279                 offset = len(self.faces)
280                 self.faces += other.faces
281                 for f in self.faces[offset:]:
282                         f.index += offset
283                         f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
284                         if other.materials:
285                                 f.material_index = material_atlas[f.material_index]
286
287                 offset = len(self.edges)
288                 self.edges += other.edges
289                 for e in self.edges[offset:]:
290                         e.index += offset
291                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
292
293                 self.lines += other.lines
294
295         def prepare_triangles(self, progress):
296                 face_count = len(self.faces)
297                 for i in range(face_count):
298                         f = self.faces[i]
299                         nverts = len(f.vertices)
300                         if nverts==3:
301                                 continue
302
303                         # Calculate normals at each vertex of the face
304                         edge_vecs = []
305                         for j in range(nverts):
306                                 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
307
308                         normals = []
309                         for j in range(nverts):
310                                 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
311
312                         # Check which diagonal results in a flatter triangulation
313                         flatness1 = normals[0].dot(normals[2])
314                         flatness2 = normals[1].dot(normals[3])
315                         cut_index = 1 if flatness1>flatness2 else 0
316
317                         nf = Face(f)
318                         nf.index = len(self.faces)
319                         self.faces.append(nf)
320
321                         ne = Edge(None)
322                         ne.index = len(self.edges)
323                         self.edges.append(ne)
324
325                         nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
326                         nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
327                         for v in nf.vertices:
328                                 v.faces.append(nf)
329
330                         ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
331                         for v in ne.vertices:
332                                 v.edges.append(ne)
333                         ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
334                         ne.smooth = True
335
336                         f.vertices[3-cut_index].faces.remove(f)
337                         del f.vertices[3-cut_index]
338                         f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
339
340                         ne.faces = [f, nf]
341                         if cut_index==0:
342                                 nf.edges = [ne, f.edges[2], f.edges[3]]
343                                 f.edges = [f.edges[0], f.edges[1], ne]
344                         else:
345                                 nf.edges = [f.edges[1], f.edges[2], ne]
346                                 f.edges = [f.edges[0], ne, f.edges[3]]
347                         for e in nf.edges:
348                                 if e!=ne:
349                                         e.faces.remove(f)
350                                         e.faces.append(nf)
351
352                         f.normal = normals[1-cut_index]
353                         nf.normal = normals[3-cut_index]
354
355                         progress.set_progress(i/face_count)
356
357         def prepare_smoothing(self, progress):
358                 smooth_limit = -1
359                 if self.smoothing=='NONE':
360                         for f in self.faces:
361                                 f.use_smooth = False
362
363                         smooth_limit = 1
364                 elif self.use_auto_smooth:
365                         smooth_limit = math.cos(self.auto_smooth_angle)
366
367                 for e in self.edges:
368                         e.check_smooth(smooth_limit)
369
370                 progress.push_task("Sharp edges", 0.0, 0.7)
371                 self.split_vertices(self.find_smooth_group, progress)
372
373                 if self.smoothing!='BLENDER':
374                         progress.set_task("Updating normals", 0.7, 1.0)
375                         self.compute_normals(progress)
376
377                 progress.pop_task()
378
379         def prepare_vertex_groups(self, obj):
380                 if not self.vertex_groups:
381                         return
382
383                 for v in self.vertices:
384                         if v.groups:
385                                 weight_sum = sum(g.weight for g in v.groups)
386                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
387                                 weight_scale = weight_sum/sum(g.weight for g in v.groups)
388                                 for g in v.groups:
389                                         g.weight *= weight_scale
390                         while len(v.groups)<self.max_groups_per_vertex:
391                                 v.groups.append(VertexGroup(None))
392
393                 if obj.parent and obj.parent.type=="ARMATURE":
394                         armature = obj.parent.data
395                         bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
396                         group_index_map = {i: i for i in range(len(obj.vertex_groups))}
397                         for g in first_obj.vertex_groups:
398                                 if g.name in bone_indices:
399                                         group_index_map[g.index] = bone_indices[g.name]
400
401                         for v in self.vertices:
402                                 for g in v.groups:
403                                         g.group = group_index_map[g.group]
404
405         def apply_material_atlas(self, material_atlas):
406                 for m in self.materials:
407                         if m.name not in material_atlas.material_names:
408                                 raise Exception("Material atlas is not compatible with Mesh")
409
410                 if self.use_uv=='NONE':
411                         return
412
413                 layer = UvLayer("material_atlas")
414                 if self.use_uv=='UNIT0':
415                         self.uv_layers = [layer]
416                         layer.unit = 0
417                 else:
418                         self.uv_layers.append(layer)
419                         used_units = [u.unit for u in self.uv_layers]
420                         layer.unit = next(i for i in itertools.count() if i not in used_units)
421                         self.uv_layers.sort(key=lambda u: u.unit)
422
423                 layer.uvs = [(0.0, 0.0)]*len(self.loops)
424                 for f in self.faces:
425                         uv = material_atlas.get_material_uv(self.materials[f.material_index])
426                         for i in f.loop_indices:
427                                 layer.uvs[i] = uv
428
429         def prepare_uv(self, progress):
430                 # Form a list of UV layers referenced by materials with the array atlas
431                 # property set
432                 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']
433                 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
434
435                 if array_uv_layers:
436                         for f in self.faces:
437                                 layer = 0
438                                 if f.material_index<len(self.materials):
439                                         mat = self.materials[f.material_index]
440                                         if mat and mat.array_atlas:
441                                                 layer = mat.array_layer
442
443                                 for l in array_uv_layers:
444                                         for i in f.loop_indices:
445                                                 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
446
447                 prog_count = len(self.uv_layers)
448                 prog_step = 0
449
450                 # Split by the UV layer used for TBN vectors first so connectivity
451                 # remains intact for TBN vector computation
452                 tbn_layer_index = -1
453                 if self.tbn_vecs:
454                         if self.tbn_uvtex:
455                                 uv_names = [u.name for u in self.uv_layers]
456                                 if self.tbn_uvtex in uv_names:
457                                         tbn_layer_index = uv_names.index(self.tbn_uvtex)
458                         elif self.uv_layers[0].unit==0:
459                                 tbn_layer_index = 0
460
461                         if tbn_layer_index>=0:
462                                 prog_count += 1
463                                 progress.push_task_slice("Computing TBN", 0, prog_count)
464                                 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
465                                 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
466                                 self.compute_tbn(tbn_layer_index, progress)
467                                 progress.pop_task()
468                                 prog_step = 2
469                         else:
470                                 raise Exception("TBN UV layer not found")
471
472                 # Split by the remaining UV layers
473                 for i, u in enumerate(self.uv_layers):
474                         if i==tbn_layer_index:
475                                 continue
476
477                         progress.push_task_slice(u.name, prog_step, prog_count)
478                         self.split_vertices(self.find_uv_group, progress, i)
479                         progress.pop_task()
480                         prog_step += 1
481
482                 # Copy UVs from layers to vertices
483                 for v in self.vertices:
484                         if v.faces:
485                                 # All faces still connected to the vertex have the same UV value
486                                 f = v.faces[0]
487                                 i = f.get_loop_index(v)
488                                 v.uvs = [u.uvs[i] for u in self.uv_layers]
489                         else:
490                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
491
492         def prepare_colors(self, progress):
493                 if not self.colors:
494                         return
495
496                 self.split_vertices(self.find_color_group, progress)
497
498                 for v in self.vertices:
499                         if v.faces:
500                                 f = v.faces[0]
501                                 v.color = self.colors.colors[f.get_loop_index(v)]
502                         else:
503                                 v.color = (1.0, 1.0, 1.0, 1.0)
504
505         def split_vertices(self, find_group_func, progress, *args):
506                 vertex_count = len(self.vertices)
507                 for i in range(vertex_count):
508                         v = self.vertices[i]
509                         for f in v.faces:
510                                 f.flag = False
511
512                         # Find all groups of faces on this vertex
513                         groups = []
514                         for f in v.faces:
515                                 if not f.flag:
516                                         groups.append(find_group_func(v, f, *args))
517
518                         # Give groups after the first separate copies of the vertex
519                         for g in groups[1:]:
520                                 nv = Vertex(v)
521                                 nv.index = len(self.vertices)
522                                 self.vertices.append(nv)
523
524                                 for e in v.edges:
525                                         e_faces_in_g = [f for f in e.faces if f in g]
526                                         if not e_faces_in_g:
527                                                 continue
528
529                                         if len(e_faces_in_g)<len(e.faces):
530                                                 # Create a copy of an edge at the boundary of the group
531                                                 ne = Edge(e)
532                                                 ne.index = len(self.edges)
533                                                 self.edges.append(ne)
534
535                                                 ne.other_vertex(v).edges.append(ne)
536
537                                                 for f in e_faces_in_g:
538                                                         e.faces.remove(f)
539                                                         f.edges[f.edges.index(e)] = ne
540                                                         ne.faces.append(f)
541
542                                                 e = ne
543
544                                         e.vertices[e.vertices.index(v)] = nv
545                                         nv.edges.append(e)
546
547                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
548
549                                 # Filter out any edges that were removed from the original vertex
550                                 v.edges = [e for e in v.edges if v in e.vertices]
551
552                                 for f in g:
553                                         v.faces.remove(f)
554                                         f.vertices[f.vertices.index(v)] = nv
555                                         nv.faces.append(f)
556
557                         progress.set_progress(i/vertex_count)
558
559         def find_smooth_group(self, vertex, face):
560                 face.flag = True
561
562                 edges = [e for e in face.edges if vertex in e.vertices]
563
564                 group = [face]
565                 for e in edges:
566                         f = face
567                         while e.smooth:
568                                 f = e.other_face(f)
569                                 if not f or f.flag:
570                                         break
571
572                                 f.flag = True
573                                 group.append(f)
574                                 e = f.other_edge(e, vertex)
575
576                 return group
577
578         def find_uv_group(self, vertex, face, index):
579                 layer = self.uv_layers[index]
580                 uv = layer.uvs[face.get_loop_index(vertex)]
581                 face.flag = True
582
583                 group = [face]
584                 for f in vertex.faces:
585                         if not f.flag and layer.uvs[f.get_loop_index(vertex)]==uv:
586                                 f.flag = True
587                                 group.append(f)
588
589                 return group
590
591         def find_color_group(self, vertex, face):
592                 color = self.colors.colors[face.get_loop_index(vertex)]
593                 face.flag = True
594
595                 group = [face]
596                 for f in vertex.faces:
597                         if not f.flag and self.colors.colors[f.get_loop_index(vertex)]==color:
598                                 f.flag = True
599                                 group.append(f)
600
601                 return group
602
603         def compute_normals(self, progress):
604                 for i, v in enumerate(self.vertices):
605                         v.normal = mathutils.Vector()
606                         for f in v.faces:
607                                 vi = f.pivot_vertex(v)
608                                 edge1 = f.vertices[vi[1]].co-v.co
609                                 edge2 = f.vertices[vi[-1]].co-v.co
610                                 if edge1.length and edge2.length:
611                                         # Use the angle between edges as a weighting factor.  This gives
612                                         # more consistent normals on bends with an inequal number of
613                                         # faces on each side.
614                                         v.normal += f.normal*edge1.angle(edge2)
615
616                         if v.normal.length:
617                                 v.normal.normalize()
618                         else:
619                                 v.normal = mathutils.Vector((0, 0, 1))
620
621                         progress.set_progress(i/len(self.vertices))
622
623         def compute_tbn(self, index, progress):
624                 # This function is called at an early stage during UV preparation when
625                 # face UVs are not available yet
626                 layer_uvs = self.uv_layers[index].uvs
627
628                 for i, v in enumerate(self.vertices):
629                         v.tan = mathutils.Vector()
630                         v.bino = mathutils.Vector()
631                         for f in v.faces:
632                                 vi = f.pivot_vertex(v)
633                                 uv0 = layer_uvs[f.loop_indices[vi[0]]]
634                                 uv1 = layer_uvs[f.loop_indices[vi[1]]]
635                                 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
636                                 du1 = uv1[0]-uv0[0]
637                                 du2 = uv2[0]-uv0[0]
638                                 dv1 = uv1[1]-uv0[1]
639                                 dv2 = uv2[1]-uv0[1]
640                                 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
641                                 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
642                                 div = (du1*dv2-du2*dv1)
643                                 if div:
644                                         mul = edge1.angle(edge2)/div
645                                         v.tan += (edge1*dv2-edge2*dv1)*mul
646                                         v.bino += (edge2*du1-edge1*du2)*mul
647
648                         if v.tan.length:
649                                 v.tan.normalize()
650                         if v.bino.length:
651                                 v.bino.normalize()
652
653                         progress.set_progress(i/len(self.vertices))
654
655         def prepare_sequence(self, progress):
656                 progress.push_task("Reordering faces", 0.0, 0.5)
657                 self.reorder_faces(progress)
658
659                 progress.set_task("Building sequence", 0.5, 1.0)
660                 sequence = None
661                 for i, f in enumerate(self.faces):
662                         if sequence:
663                                 if len(sequence)==3:
664                                         # Rotate the first three vertices so that the new face can be added
665                                         if sequence[0] in f.vertices and sequence[1] not in f.vertices:
666                                                 sequence.append(sequence[0])
667                                                 del sequence[0]
668                                         elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
669                                                 sequence.insert(0, sequence[-1])
670                                                 del sequence[-1]
671
672                                 if sequence[-1] not in f.vertices:
673                                         sequence = None
674                                 else:
675                                         to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
676                                         if len(to_add)==2:
677                                                 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
678                                                         to_add.reverse()
679                                                 sequence.append(sequence[-1])
680                                         sequence += to_add
681
682                         if not sequence:
683                                 sequence = f.vertices[:]
684                                 self.vertex_sequence.append(sequence)
685
686                         progress.set_progress(i/len(self.faces))
687
688                 progress.pop_task()
689
690                 self.reorder_vertices()
691
692         def reorder_faces(self, progress):
693                 # Tom Forsyth's vertex cache optimization algorithm
694                 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
695
696                 for f in self.faces:
697                         f.flag = False
698
699                 last_triangle_score = 0.75
700                 cache_decay_power = 1.5
701                 valence_boost_scale = 2.0
702                 valence_boost_power = -0.5
703
704                 max_cache_size = 32
705                 cached_vertices = []
706
707                 # Keep track of the score and number of unused faces for each vertex
708                 vertex_info = [[0, len(v.faces)] for v in self.vertices]
709                 for vi in vertex_info:
710                         vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
711
712                 face = None
713                 reordered_faces = []
714
715                 n_processed = 0
716                 while 1:
717                         if not face:
718                                 # Previous iteration gave no candidate for best face (or this is
719                                 # the first iteration).  Scan all faces for the highest score.
720                                 best_score = 0
721                                 for f in self.faces:
722                                         if f.flag:
723                                                 continue
724
725                                         score = sum(vertex_info[v.index][0] for v in f.vertices)
726                                         if score>best_score:
727                                                 best_score = score
728                                                 face = f
729
730                         if not face:
731                                 break
732
733                         reordered_faces.append(face)
734                         face.flag = True
735
736                         for v in face.vertices:
737                                 vertex_info[v.index][1] -= 1
738
739                                 # Shuffle the vertex into the front of the cache
740                                 if v in cached_vertices:
741                                         cached_vertices.remove(v)
742                                 cached_vertices.insert(0, v)
743
744                         # Update scores for all vertices in the cache
745                         for i, v in enumerate(cached_vertices):
746                                 score = 0
747                                 if i<3:
748                                         score += last_triangle_score
749                                 elif i<max_cache_size:
750                                         score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
751                                 if vertex_info[v.index][1]:
752                                         score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
753                                 vertex_info[v.index][0] = score
754
755                         face = None
756                         best_score = 0
757                         for v in cached_vertices:
758                                 for f in v.faces:
759                                         if not f.flag:
760                                                 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
761                                                 if score>best_score:
762                                                         best_score = score
763                                                         face = f
764
765                         del cached_vertices[max_cache_size:]
766
767                         n_processed += 1
768                         progress.set_progress(n_processed/len(self.faces))
769
770                 self.faces = reordered_faces
771                 for i, f in enumerate(self.faces):
772                         f.index = i
773
774         def reorder_vertices(self):
775                 for v in self.vertices:
776                         v.index = -1
777
778                 reordered_vertices = []
779                 for s in self.vertex_sequence:
780                         for v in s:
781                                 if v.index<0:
782                                         v.index = len(reordered_vertices)
783                                         reordered_vertices.append(v)
784
785                 self.vertices = reordered_vertices
786
787                 for e in self.edges:
788                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
789
790
791 def create_mesh_from_object(context, obj, progress, *, material_atlas=None):
792         if obj.type!="MESH":
793                 raise Exception("Object is not a mesh")
794
795         progress.push_task("Preparing mesh", 0.0, 0.2)
796
797         objs = [(obj, mathutils.Matrix())]
798         i = 0
799         while i<len(objs):
800                 o, m = objs[i]
801                 i += 1
802                 for c in o.children:
803                         if c.type=="MESH" and c.compound:
804                                 objs.append((c, m*c.matrix_local))
805
806         dg = context.evaluated_depsgraph_get()
807
808         mesh = None
809         for o, m in objs:
810                 eval_obj = o.evaluated_get(dg)
811                 bmesh = eval_obj.to_mesh()
812
813                 # Object.to_mesh does not copy custom properties
814                 bmesh.winding_test = o.data.winding_test
815                 bmesh.smoothing = o.data.smoothing
816                 bmesh.use_lines = o.data.use_lines
817                 bmesh.vertex_groups = o.data.vertex_groups
818                 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
819                 bmesh.use_uv = o.data.use_uv
820                 bmesh.tbn_vecs = o.data.tbn_vecs
821                 bmesh.tbn_uvtex = o.data.tbn_uvtex
822
823                 me = Mesh(bmesh)
824                 me.transform(m)
825
826                 for i, s in enumerate(eval_obj.material_slots):
827                         if s.link=='OBJECT':
828                                 me.materials[i] = s.material
829
830                 if mesh:
831                         mesh.splice(me)
832                 else:
833                         mesh = me
834
835         mesh.name = obj.data.name
836
837         if material_atlas:
838                 mesh.apply_material_atlas(material_atlas)
839
840         progress.set_task("Triangulating", 0.2, 0.3)
841         mesh.prepare_triangles(progress)
842         progress.set_task("Smoothing", 0.3, 0.5)
843         mesh.prepare_smoothing(progress)
844         progress.set_task("Vertex groups", 0.5, 0.6)
845         mesh.prepare_vertex_groups(obj)
846         progress.set_task("Preparing UVs", 0.6, 0.75)
847         mesh.prepare_uv(progress)
848         progress.set_task("Preparing vertex colors", 0.75, 0.85)
849         mesh.prepare_colors(progress)
850         progress.set_task("Render sequence", 0.85, 1.0)
851         mesh.prepare_sequence(progress)
852
853         progress.pop_task()
854
855         return mesh