6 def make_edge_key(i1, i2):
7 return (min(i1, i2), max(i1, i2))
10 def __init__(self, edge):
11 if edge.__class__==Edge:
12 self._edge = edge._edge
13 self.smooth = edge.smooth
18 self.vertices = edge.vertices[:]
25 def __getattr__(self, attr):
26 return getattr(self._edge, attr)
28 def check_smooth(self, limit):
29 if len(self.faces)!=2:
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)
35 def other_face(self, f):
36 if f.index==self.faces[0].index:
37 if len(self.faces)>=2:
44 def other_vertex(self, v):
45 if v.index==self.vertices[0].index:
46 return self.vertices[1]
48 return self.vertices[0]
52 def __init__(self, vertex):
53 if vertex.__class__==Vertex:
54 self._vertex = vertex._vertex
55 self.uvs = vertex.uvs[:]
57 self.bino = vertex.bino
63 self.index = vertex.index
65 self.normal = vertex.normal
69 self.groups = vertex.groups[:]
71 def __getattr__(self, attr):
72 return getattr(self._vertex, attr)
74 def __cmp__(self, other):
77 return cmp(self.index, other.index)
81 def __init__(self, group):
83 self.group = group.group
84 self.weight = group.weight
86 def __getattr__(self, attr):
87 return getattr(self._group, attr)
91 def __init__(self, face):
93 self.index = face.index
95 self.vertices = face.vertices[:]
99 def __getattr__(self, attr):
100 return getattr(self._face, attr)
102 def __cmp__(self, other):
105 return cmp(self.index, other.index)
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))]
111 def pivot_vertices(self, *vt):
112 flags = [(v in vt) for v in self.vertices]
113 l = len(self.vertices)
115 if flags[i] and not flags[(i+l-1)%l]:
116 return self.vertices[i:]+self.vertices[:i]
118 def get_edge(self, v1, v2):
119 key = make_edge_key(v1.index, v2.index)
123 raise KeyError("No edge %s"%(key,))
125 def other_edge(self, e, v):
127 if d!=e and v in d.vertices:
130 def get_neighbors(self):
131 neighbors = [e.other_face(self) for e in self.edges]
132 return list(filter(bool, neighbors))
136 def __init__(self, e):
138 self.vertices = e.vertices[:]
143 def __init__(self, arg):
151 self.uvs = [d.uv for d in self.data]
156 dot = self.name.find('.')
158 ext = self.name[dot:]
159 if ext.startswith(".unit") and ext[5:].isdigit():
160 self.unit = int(ext[5:])
164 def __getattr__(self, attr):
165 return getattr(self._layer, attr)
169 def __init__(self, mesh):
171 self.name = mesh.name
173 self.winding_test = mesh.winding_test
174 self.tbn_vecs = mesh.tbn_vecs
175 self.vertex_groups = mesh.vertex_groups
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]
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[:]
187 # Clone only the desired UV layers
188 if self.use_uv=='NONE' or not mesh.uv_layers:
191 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
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]
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)):
201 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
203 if self.use_uv=='UNIT0':
204 self.uv_layers = [self.uv_layers[0]]
205 if self.uv_layers[0].unit!=0:
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}
212 if len(f.vertices)>4:
213 raise ValueError("Ngons are not supported")
215 f.vertices = [self.vertices[i] for i in f.vertices]
219 for k in f.edge_keys:
225 e.vertices = [self.vertices[i] for i in e.vertices]
229 # Store loose edges as lines
231 self.lines = [Line(e) for e in self.edges if not e.faces]
235 self.vertex_sequence = []
237 def __getattr__(self, attr):
238 return getattr(self._mesh, attr)
240 def transform(self, matrix):
241 for v in self.vertices:
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")
251 # Merge materials and form a lookup from source material indices to the
252 # merged material list
254 for m in other.materials:
255 if m in self.materials:
256 material_map.append(self.materials.index(m))
258 material_map.append(len(self.materials))
259 self.materials.append(m)
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
266 offset = len(self.vertices)
267 self.vertices += other.vertices
268 for v in self.vertices[offset:]:
271 loop_offset = len(self.loops)
272 self.loops += other.loops
274 offset = len(self.faces)
275 self.faces += other.faces
276 for f in self.faces[offset:]:
278 f.loop_start += loop_offset
279 f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total)
281 f.material_index = material_map[f.material_index]
283 offset = len(self.edges)
284 self.edges += other.edges
285 for e in self.edges[offset:]:
287 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
289 self.lines += other.lines
291 def prepare_triangles(self, progress):
292 face_count = len(self.faces)
293 for i in range(face_count):
295 nverts = len(f.vertices)
299 # Calculate normals at each vertex of the face
301 for j in range(nverts):
302 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
305 for j in range(nverts):
306 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
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
314 nf.index = len(self.faces)
315 self.faces.append(nf)
318 ne.index = len(self.edges)
319 self.edges.append(ne)
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:
326 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
327 for v in ne.vertices:
329 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
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]]
338 nf.edges = [ne, f.edges[2], f.edges[3]]
339 f.edges = [f.edges[0], f.edges[1], ne]
341 nf.edges = [f.edges[1], f.edges[2], ne]
342 f.edges = [f.edges[0], ne, f.edges[3]]
348 f.normal = normals[1-cut_index]
349 nf.normal = normals[3-cut_index]
351 progress.set_progress(i/face_count)
353 def prepare_smoothing(self, progress):
355 if self.smoothing=='NONE':
360 elif self.use_auto_smooth:
361 smooth_limit = math.cos(self.auto_smooth_angle)
364 e.check_smooth(smooth_limit)
366 progress.push_task("Sharp edges", 0.0, 0.7)
367 self.split_vertices(self.find_smooth_group, progress)
369 if self.smoothing!='BLENDER':
370 progress.set_task("Updating normals", 0.7, 1.0)
371 self.compute_normals(progress)
375 def prepare_vertex_groups(self, obj):
376 for v in self.vertices:
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)
382 g.weight *= weight_scale
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]
392 for v in self.vertices:
394 g.group = group_index_map[g.group]
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")
401 if self.use_uv=='NONE':
404 layer = UvLayer("material_map")
405 if self.use_uv=='UNIT0':
406 self.uv_layers = [layer]
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)
414 layer.uvs = [(0.0, 0.0)]*len(self.loops)
416 uv = material_map.get_material_uv(self.materials[f.material_index])
417 for i in f.loop_indices:
420 def prepare_uv(self, progress):
421 # Form a list of UV layers referenced by materials with the array atlas
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]
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
434 for l in array_uv_layers:
435 for i in f.loop_indices:
436 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
438 # Copy UVs from layers to faces
440 for u in self.uv_layers:
441 f.uvs.append([u.uvs[i] for i in f.loop_indices])
443 prog_count = len(self.uv_layers)
446 # Split by the UV layer used for TBN vectors first so connectivity
447 # remains intact for TBN vector computation
450 uv_names = [u.name for u in self.uv_layers]
451 if self.tbn_uvtex in uv_names:
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)
461 # Split by the remaining UV layers
462 for i, u in enumerate(self.uv_layers):
463 if i==tbn_layer_index:
466 progress.push_task_slice(u.name, prog_step, prog_count)
467 self.split_vertices(self.find_uv_group, progress, i)
471 # Copy UVs from faces to vertices
472 for v in self.vertices:
474 # All faces still connected to the vertex have the same UV value
476 i = f.vertices.index(v)
477 v.uvs = [u[i] for u in f.uvs]
479 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
481 def split_vertices(self, find_group_func, progress, *args):
482 vertex_count = len(self.vertices)
483 for i in range(vertex_count):
488 # Find all groups of faces on this vertex
492 groups.append(find_group_func(v, f, *args))
494 # Give groups after the first separate copies of the vertex
497 nv.index = len(self.vertices)
498 self.vertices.append(nv)
501 e_faces_in_g = [f for f in e.faces if f in g]
505 if len(e_faces_in_g)<len(e.faces):
506 # Create a copy of an edge at the boundary of the group
508 ne.index = len(self.edges)
509 self.edges.append(ne)
511 ne.other_vertex(v).edges.append(ne)
513 for f in e_faces_in_g:
515 f.edges[f.edges.index(e)] = ne
520 e.vertices[e.vertices.index(v)] = nv
523 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
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]
530 f.vertices[f.vertices.index(v)] = nv
533 progress.set_progress(i/vertex_count)
535 def find_smooth_group(self, vertex, face):
538 edges = [e for e in face.edges if vertex in e.vertices]
550 e = f.other_edge(e, vertex)
554 def find_uv_group(self, vertex, face, index):
555 uv = face.uvs[index][face.vertices.index(vertex)]
559 for f in vertex.faces:
560 if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
566 def compute_normals(self, progress):
567 for i, v in enumerate(self.vertices):
568 v.normal = mathutils.Vector()
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)
582 v.normal = mathutils.Vector((0, 0, 1))
584 progress.set_progress(i/len(self.vertices))
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
591 for i, v in enumerate(self.vertices):
592 v.tan = mathutils.Vector()
593 v.bino = mathutils.Vector()
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]]]
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)
607 mul = edge1.angle(edge2)/div
608 v.tan += (edge1*dv2-edge2*dv1)*mul
609 v.bino += (edge2*du1-edge1*du2)*mul
616 progress.set_progress(i/len(self.vertices))
618 def prepare_sequence(self, progress):
619 progress.push_task("Reordering faces", 0.0, 0.5)
620 self.reorder_faces(progress)
622 progress.set_task("Building sequence", 0.5, 1.0)
624 for i, f in enumerate(self.faces):
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])
631 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
632 sequence.insert(0, sequence[-1])
635 if sequence[-1] not in f.vertices:
638 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
640 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
642 sequence.append(sequence[-1])
646 sequence = f.vertices[:]
647 self.vertex_sequence.append(sequence)
649 progress.set_progress(i/len(self.faces))
653 self.reorder_vertices()
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
662 last_triangle_score = 0.75
663 cache_decay_power = 1.5
664 valence_boost_scale = 2.0
665 valence_boost_power = -0.5
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)
681 # Previous iteration gave no candidate for best face (or this is
682 # the first iteration). Scan all faces for the highest score.
688 score = sum(vertex_info[v.index][0] for v in f.vertices)
696 reordered_faces.append(face)
699 for v in face.vertices:
700 vertex_info[v.index][1] -= 1
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)
707 # Update scores for all vertices in the cache
708 for i, v in enumerate(cached_vertices):
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
720 for v in cached_vertices:
723 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
728 del cached_vertices[max_cache_size:]
731 progress.set_progress(n_processed/len(self.faces))
733 self.faces = reordered_faces
734 for i, f in enumerate(self.faces):
737 def reorder_vertices(self):
738 for v in self.vertices:
741 reordered_vertices = []
742 for s in self.vertex_sequence:
745 v.index = len(reordered_vertices)
746 reordered_vertices.append(v)
748 self.vertices = reordered_vertices
751 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
753 def drop_references(self):
754 for v in self.vertices:
762 for u in self.uv_layers:
767 def create_mesh_from_object(context, obj, progress, *, material_map=None):
769 raise Exception("Object is not a mesh")
771 progress.push_task("Preparing mesh", 0.0, 0.2)
773 objs = [(obj, mathutils.Matrix())]
779 if c.type=="MESH" and c.compound:
780 objs.append((c, m*c.matrix_local))
785 bmesh = o.to_mesh(context.scene, True, "PREVIEW")
786 bmeshes.append(bmesh)
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
806 mesh.name = obj.data.name
809 mesh.apply_material_map(material_map)
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)
822 # Discard the temporary Blender meshes after making sure there's no
823 # references to the data
824 mesh.drop_references()
826 bpy.data.meshes.remove(m)