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