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.smooth = edge.smooth
16 self.vertices = edge.vertices[:]
23 def check_smooth(self, limit):
24 if len(self.faces)!=2:
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)
30 def other_face(self, f):
31 if f.index==self.faces[0].index:
32 if len(self.faces)>=2:
39 def other_vertex(self, v):
40 if v.index==self.vertices[0].index:
41 return self.vertices[1]
43 return self.vertices[0]
47 def __init__(self, vertex):
48 if vertex.__class__==Vertex:
49 self.uvs = vertex.uvs[:]
54 self.index = vertex.index
55 self.co = mathutils.Vector(vertex.co)
56 self.normal = mathutils.Vector(vertex.normal)
61 self.groups = vertex.groups[:]
63 def __cmp__(self, other):
66 return cmp(self.index, other.index)
70 def __init__(self, group):
72 self.group = group.group
73 self.weight = group.weight
80 def __init__(self, face):
81 self.index = face.index
83 self.edge_keys = face.edge_keys
84 self.vertices = face.vertices[:]
85 self.loop_indices = face.loop_indices
86 self.normal = face.normal
87 self.use_smooth = face.use_smooth
88 self.material_index = face.material_index
91 def __cmp__(self, other):
94 return cmp(self.index, other.index)
96 def pivot_vertex(self, v):
97 n = self.vertices.index(v)
98 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
100 def get_loop_index(self, v):
101 return self.loop_indices[self.vertices.index(v)]
103 def get_edge(self, v1, v2):
104 key = make_edge_key(v1.index, v2.index)
108 raise KeyError("No edge %s"%(key,))
110 def other_edge(self, e, v):
112 if d!=e and v in d.vertices:
115 def get_neighbors(self):
116 neighbors = [e.other_face(self) for e in self.edges]
117 return list(filter(bool, neighbors))
121 def __init__(self, e):
123 self.vertices = e.vertices[:]
128 def __init__(self, arg):
134 self.uvs = [mathutils.Vector(d.uv) for d in arg.data]
139 dot = self.name.find('.')
141 ext = self.name[dot:]
142 if ext.startswith(".unit") and ext[5:].isdigit():
143 self.unit = int(ext[5:])
149 def __init__(self, l):
151 self.colors = [c.color[:] for c in l.data]
155 def __init__(self, mesh):
156 self.name = mesh.name
158 self.winding_test = mesh.winding_test
159 self.smoothing = mesh.smoothing
160 self.use_uv = mesh.use_uv
161 self.tangent_uvtex = mesh.tangent_uvtex
162 self.vertex_groups = mesh.vertex_groups
165 self.vertices = [Vertex(v) for v in mesh.vertices]
166 if self.vertex_groups:
167 for v in self.vertices:
168 v.groups = [VertexGroup(g) for g in v.groups]
170 self.faces = [Face(f) for f in mesh.polygons]
171 self.edges = [Edge(e) for e in mesh.edges]
172 self.loops = mesh.loops[:]
173 self.materials = mesh.materials[:]
175 self.use_auto_smooth = mesh.use_auto_smooth
176 self.auto_smooth_angle = mesh.auto_smooth_angle
177 self.max_groups_per_vertex = mesh.max_groups_per_vertex
179 # Clone only the desired UV layers
180 if mesh.use_uv=='NONE' or not mesh.uv_layers:
183 self.uv_layers = [UvLayer(u) for u in mesh.uv_layers]
185 # Assign texture unit numbers to UV layers that lack one
186 missing_unit = [u for u in self.uv_layers if u.unit is None]
188 missing_unit = sorted(missing_unit, key=(lambda u: u.name))
189 used_units = [u.unit for u in self.uv_layers if u.unit is not None]
190 for u, n in zip(missing_unit, (i for i in itertools.count() if i not in used_units)):
193 self.uv_layers = sorted(self.uv_layers, key=(lambda u: u.unit))
195 if mesh.use_uv=='UNIT0':
196 self.uv_layers = [self.uv_layers[0]]
197 if self.uv_layers[0].unit!=0:
201 if mesh.vertex_colors:
202 self.colors = ColorLayer(mesh.vertex_colors[0])
204 # Rewrite links between elements to point to cloned data, or create links
205 # where they don't exist
206 edge_map = {e.key: e for e in self.edges}
208 if len(f.vertices)>4:
209 raise ValueError("Ngons are not supported")
211 f.vertices = [self.vertices[i] for i in f.vertices]
215 for k in f.edge_keys:
221 e.vertices = [self.vertices[i] for i in e.vertices]
225 # Store loose edges as lines
227 self.lines = [Line(e) for e in self.edges if not e.faces]
231 # Check if tangent vectors are needed
232 if mesh.tangent_vecs=='NO':
233 self.tangent_vecs = False
234 elif mesh.tangent_vecs=='YES':
235 self.tangent_vecs = True
236 elif mesh.tangent_vecs=='AUTO':
237 from .material import Material
238 self.tangent_vecs = False
239 for m in self.materials:
242 normal_prop = next((p for p in mat.properties if p.tex_keyword=="normal_map"), None)
243 if normal_prop and normal_prop.texture:
244 self.tangent_vecs = True
246 self.vertex_sequence = []
248 def transform(self, matrix):
249 for v in self.vertices:
252 def splice(self, other):
253 if len(self.uv_layers)!=len(other.uv_layers):
254 raise ValueError("Meshes have incompatible UV layers")
255 for i, u in enumerate(self.uv_layers):
256 if u.name!=other.uv_layers[i].name:
257 raise ValueError("Meshes have incompatible UV layers")
259 # Merge materials and form a lookup from source material indices to the
260 # merged material list
262 for m in other.materials:
263 if m in self.materials:
264 material_atlas.append(self.materials.index(m))
266 material_atlas.append(len(self.materials))
267 self.materials.append(m)
269 # Append data and adjust indices where necessary. Since the data is
270 # spliced from the source mesh, rebuilding references is not necessary.
271 for i, u in enumerate(self.uv_layers):
272 u.uvs += other.uv_layers[i].uvs
276 self.colors.colors += other.colors.colors
278 self.colors.colors += [(1.0, 1.0, 1.0, 1.0)]*len(other.loops)
280 self.colors = ColorLayer(other.colors.name)
281 self.colors.colors = [(1.0, 1.0, 1.0, 1.0)]*len(self.loops)+other.colors.colors
283 offset = len(self.vertices)
284 self.vertices += other.vertices
285 for v in self.vertices[offset:]:
288 loop_offset = len(self.loops)
289 self.loops += other.loops
291 offset = len(self.faces)
292 self.faces += other.faces
293 for f in self.faces[offset:]:
295 f.loop_indices = range(f.loop_indices.start+offset, f.loop_indices.stop+offset)
297 f.material_index = material_atlas[f.material_index]
299 offset = len(self.edges)
300 self.edges += other.edges
301 for e in self.edges[offset:]:
303 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
305 self.lines += other.lines
307 def prepare_triangles(self, progress):
308 face_count = len(self.faces)
309 for i in range(face_count):
311 nverts = len(f.vertices)
315 # Calculate normals at each vertex of the face
317 for j in range(nverts):
318 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
321 for j in range(nverts):
322 normals.append(edge_vecs[j-1].cross(edge_vecs[j]).normalized())
324 # Check which diagonal results in a flatter triangulation
325 flatness1 = normals[0].dot(normals[2])
326 flatness2 = normals[1].dot(normals[3])
327 cut_index = 1 if flatness1>flatness2 else 0
330 nf.index = len(self.faces)
331 self.faces.append(nf)
334 ne.index = len(self.edges)
335 self.edges.append(ne)
337 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
338 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
339 for v in nf.vertices:
342 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
343 for v in ne.vertices:
345 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
348 f.vertices[3-cut_index].faces.remove(f)
349 del f.vertices[3-cut_index]
350 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
354 nf.edges = [ne, f.edges[2], f.edges[3]]
355 f.edges = [f.edges[0], f.edges[1], ne]
357 nf.edges = [f.edges[1], f.edges[2], ne]
358 f.edges = [f.edges[0], ne, f.edges[3]]
364 f.normal = normals[1-cut_index]
365 nf.normal = normals[3-cut_index]
367 progress.set_progress(i/face_count)
369 def prepare_smoothing(self, progress):
371 if self.smoothing=='NONE':
376 elif self.use_auto_smooth:
377 smooth_limit = math.cos(self.auto_smooth_angle)
380 e.check_smooth(smooth_limit)
382 progress.push_task("Sharp edges", 0.0, 0.7)
383 self.split_vertices(self.find_smooth_group, progress)
385 if self.smoothing!='BLENDER':
386 progress.set_task("Updating normals", 0.7, 1.0)
387 self.compute_normals(progress)
391 def prepare_vertex_groups(self, obj):
392 if not self.vertex_groups:
395 for v in self.vertices:
397 weight_sum = sum(g.weight for g in v.groups)
398 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
399 weight_scale = weight_sum/sum(g.weight for g in v.groups)
401 g.weight *= weight_scale
402 while len(v.groups)<self.max_groups_per_vertex:
403 v.groups.append(VertexGroup(None))
405 if obj.parent and obj.parent.type=="ARMATURE":
406 armature = obj.parent.data
407 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
408 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
409 for g in first_obj.vertex_groups:
410 if g.name in bone_indices:
411 group_index_map[g.index] = bone_indices[g.name]
413 for v in self.vertices:
415 g.group = group_index_map[g.group]
417 def apply_material_atlas(self, material_atlas):
418 for m in self.materials:
419 if m.name not in material_atlas.material_names:
420 raise Exception("Material atlas is not compatible with Mesh")
422 if self.use_uv=='NONE':
425 layer = UvLayer("material_atlas")
426 if self.use_uv=='UNIT0':
427 self.uv_layers = [layer]
430 self.uv_layers.append(layer)
431 used_units = [u.unit for u in self.uv_layers]
432 layer.unit = next(i for i in itertools.count() if i not in used_units)
433 self.uv_layers.sort(key=lambda u: u.unit)
435 layer.uvs = [(0.0, 0.0)]*len(self.loops)
437 uv = material_atlas.get_material_uv(self.materials[f.material_index])
438 for i in f.loop_indices:
441 def prepare_uv(self, progress):
442 # Form a list of UV layers referenced by materials with the array atlas
444 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']
445 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
450 if f.material_index<len(self.materials):
451 mat = self.materials[f.material_index]
452 if mat and mat.array_atlas:
453 layer = mat.array_layer
455 for l in array_uv_layers:
456 for i in f.loop_indices:
457 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
459 prog_count = len(self.uv_layers)
462 # Split by the UV layer used for tangent vectors first so connectivity
463 # remains intact for tangent vector computation
464 tangent_layer_index = -1
465 if self.tangent_vecs:
466 if self.tangent_uvtex:
467 uv_names = [u.name for u in self.uv_layers]
468 if self.tangent_uvtex in uv_names:
469 tangent_layer_index = uv_names.index(self.tangent_uvtex)
470 elif self.uv_layers[0].unit==0:
471 tangent_layer_index = 0
473 if tangent_layer_index>=0:
475 progress.push_task_slice("Computing tangents", 0, prog_count)
476 self.split_vertices(self.find_uv_group, progress, tangent_layer_index)
477 progress.set_task_slice(self.tangent_uvtex, 1, prog_count)
478 self.compute_tangents(tangent_layer_index, progress)
482 raise Exception("Tangent UV layer not found")
484 # Split by the remaining UV layers
485 for i, u in enumerate(self.uv_layers):
486 if i==tangent_layer_index:
489 progress.push_task_slice(u.name, prog_step, prog_count)
490 self.split_vertices(self.find_uv_group, progress, i)
494 # Copy UVs from layers to vertices
495 for v in self.vertices:
497 # All faces still connected to the vertex have the same UV value
499 i = f.get_loop_index(v)
500 v.uvs = [u.uvs[i] for u in self.uv_layers]
502 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
504 def prepare_colors(self, progress):
508 self.split_vertices(self.find_color_group, progress)
510 for v in self.vertices:
513 v.color = self.colors.colors[f.get_loop_index(v)]
515 v.color = (1.0, 1.0, 1.0, 1.0)
517 def split_vertices(self, find_group_func, progress, *args):
518 vertex_count = len(self.vertices)
519 for i in range(vertex_count):
524 # Find all groups of faces on this vertex
528 groups.append(find_group_func(v, f, *args))
530 # Give groups after the first separate copies of the vertex
533 nv.index = len(self.vertices)
534 self.vertices.append(nv)
537 e_faces_in_g = [f for f in e.faces if f in g]
541 if len(e_faces_in_g)<len(e.faces):
542 # Create a copy of an edge at the boundary of the group
544 ne.index = len(self.edges)
545 self.edges.append(ne)
547 ne.other_vertex(v).edges.append(ne)
549 for f in e_faces_in_g:
551 f.edges[f.edges.index(e)] = ne
556 e.vertices[e.vertices.index(v)] = nv
559 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
561 # Filter out any edges that were removed from the original vertex
562 v.edges = [e for e in v.edges if v in e.vertices]
566 f.vertices[f.vertices.index(v)] = nv
569 progress.set_progress(i/vertex_count)
571 def find_smooth_group(self, vertex, face):
574 edges = [e for e in face.edges if vertex in e.vertices]
586 e = f.other_edge(e, vertex)
590 def find_uv_group(self, vertex, face, index):
591 layer = self.uv_layers[index]
592 uv = layer.uvs[face.get_loop_index(vertex)]
596 for f in vertex.faces:
597 if not f.flag and layer.uvs[f.get_loop_index(vertex)]==uv:
603 def find_color_group(self, vertex, face):
604 color = self.colors.colors[face.get_loop_index(vertex)]
608 for f in vertex.faces:
609 if not f.flag and self.colors.colors[f.get_loop_index(vertex)]==color:
615 def compute_normals(self, progress):
616 for i, v in enumerate(self.vertices):
617 v.normal = mathutils.Vector()
619 vi = f.pivot_vertex(v)
620 edge1 = f.vertices[vi[1]].co-v.co
621 edge2 = f.vertices[vi[-1]].co-v.co
622 if edge1.length and edge2.length:
623 # Use the angle between edges as a weighting factor. This gives
624 # more consistent normals on bends with an inequal number of
625 # faces on each side.
626 v.normal += f.normal*edge1.angle(edge2)
631 v.normal = mathutils.Vector((0, 0, 1))
633 progress.set_progress(i/len(self.vertices))
635 def compute_tangents(self, index, progress):
636 layer_uvs = self.uv_layers[index].uvs
638 for i, v in enumerate(self.vertices):
639 v.tan = mathutils.Vector()
641 vi = f.pivot_vertex(v)
642 uv0 = layer_uvs[f.loop_indices[vi[0]]]
643 uv1 = layer_uvs[f.loop_indices[vi[1]]]
644 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
649 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
650 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
651 div = (du1*dv2-du2*dv1)
653 mul = edge1.angle(edge2)/div
654 v.tan += (edge1*dv2-edge2*dv1)*mul
659 progress.set_progress(i/len(self.vertices))
661 def prepare_sequence(self, progress):
662 progress.push_task("Reordering faces", 0.0, 0.5)
663 self.reorder_faces(progress)
665 progress.set_task("Building sequence", 0.5, 1.0)
667 for i, f in enumerate(self.faces):
670 # Rotate the first three vertices so that the new face can be added
671 if sequence[0] in f.vertices and sequence[1] not in f.vertices:
672 sequence.append(sequence[0])
674 elif sequence[2] not in f.vertices and sequence[1] in f.vertices:
675 sequence.insert(0, sequence[-1])
678 if sequence[-1] not in f.vertices:
681 to_add = [v for v in f.vertices if v!=sequence[-1] and v!=sequence[-2]]
683 if (f.vertices[1]==sequence[-1]) != (len(sequence)%2==1):
685 sequence.append(sequence[-1])
689 sequence = f.vertices[:]
690 self.vertex_sequence.append(sequence)
692 progress.set_progress(i/len(self.faces))
696 self.reorder_vertices()
698 def reorder_faces(self, progress):
699 # Tom Forsyth's vertex cache optimization algorithm
700 # http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
705 last_triangle_score = 0.75
706 cache_decay_power = 1.5
707 valence_boost_scale = 2.0
708 valence_boost_power = -0.5
713 # Keep track of the score and number of unused faces for each vertex
714 vertex_info = [[0, len(v.faces)] for v in self.vertices]
715 for vi in vertex_info:
716 vi[0] = valence_boost_scale*(vi[1]**valence_boost_power)
724 # Previous iteration gave no candidate for best face (or this is
725 # the first iteration). Scan all faces for the highest score.
731 score = sum(vertex_info[v.index][0] for v in f.vertices)
739 reordered_faces.append(face)
742 for v in face.vertices:
743 vertex_info[v.index][1] -= 1
745 # Shuffle the vertex into the front of the cache
746 if v in cached_vertices:
747 cached_vertices.remove(v)
748 cached_vertices.insert(0, v)
750 # Update scores for all vertices in the cache
751 for i, v in enumerate(cached_vertices):
754 score += last_triangle_score
755 elif i<max_cache_size:
756 score += (1-(i-3)/(max_cache_size-3))**cache_decay_power
757 if vertex_info[v.index][1]:
758 score += valence_boost_scale*(vertex_info[v.index][1]**valence_boost_power)
759 vertex_info[v.index][0] = score
763 for v in cached_vertices:
766 score = sum(vertex_info[fv.index][0] for fv in f.vertices)
771 del cached_vertices[max_cache_size:]
774 progress.set_progress(n_processed/len(self.faces))
776 self.faces = reordered_faces
777 for i, f in enumerate(self.faces):
780 def reorder_vertices(self):
781 for v in self.vertices:
784 reordered_vertices = []
785 for s in self.vertex_sequence:
788 v.index = len(reordered_vertices)
789 reordered_vertices.append(v)
791 self.vertices = reordered_vertices
794 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
797 def create_mesh_from_object(context, obj, progress, *, material_atlas=None):
799 raise Exception("Object is not a mesh")
801 progress.push_task("Preparing mesh", 0.0, 0.2)
803 objs = [(obj, mathutils.Matrix())]
809 if c.type=="MESH" and c.compound:
810 objs.append((c, m*c.matrix_local))
812 dg = context.evaluated_depsgraph_get()
816 eval_obj = o.evaluated_get(dg)
817 bmesh = eval_obj.to_mesh()
819 # Object.to_mesh does not copy custom properties
820 bmesh.winding_test = o.data.winding_test
821 bmesh.smoothing = o.data.smoothing
822 bmesh.use_lines = o.data.use_lines
823 bmesh.vertex_groups = o.data.vertex_groups
824 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
825 bmesh.use_uv = o.data.use_uv
826 bmesh.tangent_vecs = o.data.tangent_vecs
827 bmesh.tangent_uvtex = o.data.tangent_uvtex
832 for i, s in enumerate(eval_obj.material_slots):
834 me.materials[i] = s.material
841 mesh.name = obj.data.name
844 mesh.apply_material_atlas(material_atlas)
846 progress.set_task("Triangulating", 0.2, 0.3)
847 mesh.prepare_triangles(progress)
848 progress.set_task("Smoothing", 0.3, 0.5)
849 mesh.prepare_smoothing(progress)
850 progress.set_task("Vertex groups", 0.5, 0.6)
851 mesh.prepare_vertex_groups(obj)
852 progress.set_task("Preparing UVs", 0.6, 0.75)
853 mesh.prepare_uv(progress)
854 progress.set_task("Preparing vertex colors", 0.75, 0.85)
855 mesh.prepare_colors(progress)
856 progress.set_task("Render sequence", 0.85, 1.0)
857 mesh.prepare_sequence(progress)