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