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