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