5 def make_edge_key(i1, i2):
6 return (min(i1, i2), max(i1, i2))
9 def __init__(self, edge):
10 if edge.__class__==Edge:
11 self._edge = edge._edge
12 self.smooth = edge.smooth
17 self.vertices = edge.vertices[:]
24 def __getattr__(self, attr):
25 return getattr(self._edge, attr)
27 def check_smooth(self, limit):
28 if len(self.faces)!=2:
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)
34 def other_face(self, f):
35 if f.index==self.faces[0].index:
36 if len(self.faces)>=2:
43 def other_vertex(self, v):
44 if v.index==self.vertices[0].index:
45 return self.vertices[1]
47 return self.vertices[0]
51 def __init__(self, vertex):
52 if vertex.__class__==Vertex:
53 self._vertex = vertex._vertex
54 self.uvs = vertex.uvs[:]
56 self.bino = vertex.bino
62 self.index = vertex.index
64 self.normal = vertex.normal
68 self.groups = vertex.groups[:]
70 def __getattr__(self, attr):
71 return getattr(self._vertex, attr)
73 def __cmp__(self, other):
76 return cmp(self.index, other.index)
80 def __init__(self, group):
82 self.group = group.group
83 self.weight = group.weight
85 def __getattr__(self, attr):
86 return getattr(self._group, attr)
90 def __init__(self, face):
92 self.index = face.index
94 self.vertices = face.vertices[:]
98 def __getattr__(self, attr):
99 return getattr(self._face, attr)
101 def __cmp__(self, other):
104 return cmp(self.index, other.index)
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))]
110 def pivot_vertices(self, *vt):
111 flags = [(v in vt) for v in self.vertices]
112 l = len(self.vertices)
114 if flags[i] and not flags[(i+l-1)%l]:
115 return self.vertices[i:]+self.vertices[:i]
117 def get_edge(self, v1, v2):
118 key = make_edge_key(v1.index, v2.index)
122 raise KeyError("No edge %s"%(key,))
124 def other_edge(self, e, v):
126 if d!=e and v in d.vertices:
129 def get_neighbors(self):
130 neighbors = [e.other_face(self) for e in self.edges]
131 return list(filter(bool, neighbors))
135 def __init__(self, e):
137 self.vertices = e.vertices[:]
142 def __init__(self, arg):
149 self.uvs = [d.uv for d in self.data]
154 dot = self.name.find('.')
156 ext = self.name[dot:]
157 if ext.startswith(".unit") and ext[5:].isdigit():
158 self.unit = int(ext[5:])
162 def __getattr__(self, attr):
163 return getattr(self._layer, attr)
167 def __init__(self, mesh):
170 self.winding_test = mesh.winding_test
171 self.tbn_vecs = mesh.tbn_vecs
172 self.vertex_groups = mesh.vertex_groups
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]
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[:]
184 # Clone only the desired UV layers
185 if self.use_uv=='NONE' or not self.uv_layers:
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)))
191 if self.use_uv=='UNIT0':
192 self.uv_layers = [self.uv_layers[0]]
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:
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}
205 if len(f.vertices)>4:
206 raise ValueError("Ngons are not supported")
208 f.vertices = [self.vertices[i] for i in f.vertices]
212 for k in f.edge_keys:
218 e.vertices = [self.vertices[i] for i in e.vertices]
222 # Store loose edges as lines
224 self.lines = [Line(e) for e in self.edges if not e.faces]
228 def __getattr__(self, attr):
229 return getattr(self._mesh, attr)
231 def transform(self, matrix):
232 for v in self.vertices:
235 def splice(self, other):
236 if len(self.uv_layers)!=len(other.uv_layers):
237 raise ValueError("Meshes have incompatible UV layers")
238 for i, u in enumerate(self.uv_layers):
239 if u.name!=other.uv_layers[i].name:
240 raise ValueError("Meshes have incompatible UV layers")
242 # Merge materials and form a lookup from source material indices to the
243 # merged material list
245 for m in other.materials:
246 if m in self.materials:
247 material_map.append(self.materials.index(m))
249 material_map.append(len(self.materials))
250 self.materials.append(m)
252 # Append data and adjust indices where necessary. Since the data is
253 # spliced from the source mesh, rebuilding references is not necessary.
254 for i, u in enumerate(self.uv_layers):
255 u.uvs += other.uv_layers[i].uvs
257 offset = len(self.vertices)
258 self.vertices += other.vertices
259 for v in self.vertices[offset:]:
262 loop_offset = len(self.loops)
263 self.loops += other.loops
265 offset = len(self.faces)
266 self.faces += other.faces
267 for f in self.faces[offset:]:
269 f.loop_start += loop_offset
270 f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total)
272 f.material_index = material_map[f.material_index]
274 offset = len(self.edges)
275 self.edges += other.edges
276 for e in self.edges[offset:]:
278 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
280 self.lines += other.lines
282 def prepare_triangles(self, progress):
283 face_count = len(self.faces)
284 for i in range(face_count):
286 nverts = len(f.vertices)
290 # Calculate normals at each vertex of the face
292 for j in range(nverts):
293 edge_vecs.append(f.vertices[(j+1)%nverts].co-f.vertices[j].co)
296 for j in range(nverts):
297 normals.append(edge_vecs[j].cross(edge_vecs[j-1]).normalized())
299 # Check which diagonal results in a flatter triangulation
300 flatness1 = normals[0].dot(normals[2])
301 flatness2 = normals[1].dot(normals[3])
302 cut_index = 1 if flatness1>flatness2 else 0
305 nf.index = len(self.faces)
306 self.faces.append(nf)
309 ne.index = len(self.edges)
310 self.edges.append(ne)
312 nf.vertices = [f.vertices[cut_index], f.vertices[2], f.vertices[3]]
313 nf.loop_indices = [f.loop_indices[cut_index], f.loop_indices[2], f.loop_indices[3]]
314 for v in nf.vertices:
317 ne.vertices = [f.vertices[cut_index], f.vertices[2+cut_index]]
318 for v in ne.vertices:
320 ne.key = make_edge_key(ne.vertices[0].index, ne.vertices[1].index)
323 f.vertices[3-cut_index].faces.remove(f)
324 del f.vertices[3-cut_index]
325 f.loop_indices = [f.loop_indices[0], f.loop_indices[1], f.loop_indices[2+cut_index]]
329 nf.edges = [ne, f.edges[2], f.edges[3]]
330 f.edges = [f.edges[0], f.edges[1], ne]
332 nf.edges = [f.edges[1], f.edges[2], ne]
333 f.edges = [f.edges[0], ne, f.edges[3]]
335 f.normal = normals[1-cut_index]
336 nf.normal = normals[3-cut_index]
338 progress.set_progress(i/face_count)
340 def prepare_smoothing(self, progress):
342 if self.smoothing=='NONE':
347 elif self.use_auto_smooth:
348 smooth_limit = math.cos(self.auto_smooth_angle)
351 e.check_smooth(smooth_limit)
353 progress.push_task("Sharp edges", 0.0, 0.7)
354 self.split_vertices(self.find_smooth_group, progress)
356 if self.smoothing!='BLENDER':
357 progress.set_task("Updating normals", 0.7, 1.0)
358 self.compute_normals(progress)
362 def prepare_vertex_groups(self, obj):
363 for v in self.vertices:
365 weight_sum = sum(g.weight for g in v.groups)
366 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
367 weight_scale = weight_sum/sum(g.weight for g in v.groups)
369 g.weight *= weight_scale
371 if obj.parent and obj.parent.type=="ARMATURE":
372 armature = obj.parent.data
373 bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
374 group_index_map = {i: i for i in range(len(obj.vertex_groups))}
375 for g in first_obj.vertex_groups:
376 if g.name in bone_indices:
377 group_index_map[g.index] = bone_indices[g.name]
379 for v in self.vertices:
381 g.group = group_index_map[g.group]
383 def prepare_uv(self, obj, progress):
384 if obj.material_tex and self.use_uv!='NONE':
385 layer = UvLayer("material_tex")
387 if self.use_uv=='UNIT0':
388 self.uv_layers = [layer]
391 self.uv_layers.append(layer)
392 layer.unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
394 layer.uvs = [None]*len(self.loops)
396 uv = mathutils.Vector(((f.material_index+0.5)/len(self.materials), 0.5))
397 for i in f.loop_indices:
400 # Form a list of UV layers referenced by materials with the array atlas
402 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']
403 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
408 if f.material_index<len(self.materials):
409 mat = self.materials[f.material_index]
410 if mat and mat.array_atlas:
411 layer = mat.array_layer
413 for l in array_uv_layers:
414 for i in f.loop_indices:
415 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
417 # Copy UVs from layers to faces
419 for u in self.uv_layers:
420 f.uvs.append([u.uvs[i] for i in f.loop_indices])
422 prog_count = len(self.uv_layers)
425 # Split by the UV layer used for TBN vectors first so connectivity
426 # remains intact for TBN vector computation
429 uv_names = [u.name for u in self.uv_layers]
430 if self.tbn_uvtex in uv_names:
432 tbn_layer_index = uv_names.index(self.tbn_uvtex)
433 progress.push_task_slice("Computing TBN", 0, prog_count)
434 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
435 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
436 self.compute_tbn(tbn_layer_index, progress)
440 # Split by the remaining UV layers
441 for i, u in enumerate(self.uv_layers):
442 if i==tbn_layer_index:
445 progress.push_task_slice(u.name, prog_step, prog_count)
446 self.split_vertices(self.find_uv_group, progress, i)
450 # Copy UVs from faces to vertices
451 for v in self.vertices:
453 # All faces still connected to the vertex have the same UV value
455 i = f.vertices.index(v)
456 v.uvs = [u[i] for u in f.uvs]
458 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
460 def split_vertices(self, find_group_func, progress, *args):
461 vertex_count = len(self.vertices)
462 for i in range(vertex_count):
467 # Find all groups of faces on this vertex
471 groups.append(find_group_func(v, f, *args))
473 # Give groups after the first separate copies of the vertex
476 nv.index = len(self.vertices)
477 self.vertices.append(nv)
480 e_faces_in_g = [f for f in e.faces if f in g]
484 if len(e_faces_in_g)<len(e.faces):
485 # Create a copy of an edge at the boundary of the group
487 ne.index = len(self.edges)
488 self.edges.append(ne)
490 ne.other_vertex(v).edges.append(ne)
492 for f in e_faces_in_g:
494 f.edges[f.edges.index(e)] = ne
499 e.vertices[e.vertices.index(v)] = nv
502 e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
504 # Filter out any edges that were removed from the original vertex
505 v.edges = [e for e in v.edges if v in e.vertices]
509 f.vertices[f.vertices.index(v)] = nv
512 progress.set_progress(i/vertex_count)
514 def find_smooth_group(self, vertex, face):
517 edges = [e for e in face.edges if vertex in e.vertices]
529 e = f.other_edge(e, vertex)
533 def find_uv_group(self, vertex, face, index):
534 uv = face.uvs[index][face.vertices.index(vertex)]
538 for f in vertex.faces:
539 if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
545 def compute_normals(self, progress):
546 for i, v in enumerate(self.vertices):
547 v.normal = mathutils.Vector()
549 fv = f.pivot_vertices(v)
550 edge1 = fv[1].co-fv[0].co
551 edge2 = fv[-1].co-fv[0].co
552 if edge1.length and edge2.length:
553 # Use the angle between edges as a weighting factor. This gives
554 # more consistent normals on bends with an inequal number of
555 # faces on each side.
556 v.normal += f.normal*edge1.angle(edge2)
561 v.normal = mathutils.Vector((0, 0, 1))
563 progress.set_progress(i/len(self.vertices))
565 def compute_tbn(self, index, progress):
566 # This function is called at an early stage during UV preparation when
567 # face UVs are not available yet
568 layer_uvs = self.uv_layers[index].uvs
570 for i, v in enumerate(self.vertices):
571 v.tan = mathutils.Vector()
572 v.bino = mathutils.Vector()
574 vi = f.pivot_vertex(v)
575 uv0 = layer_uvs[f.loop_indices[vi[0]]]
576 uv1 = layer_uvs[f.loop_indices[vi[1]]]
577 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
582 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
583 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
584 div = (du1*dv2-du2*dv1)
586 mul = edge1.angle(edge2)/div
587 v.tan += (edge1*dv2-edge2*dv1)*mul
588 v.bino += (edge2*du1-edge1*du2)*mul
595 progress.set_progress(i/len(self.vertices))
597 def drop_references(self):
598 for v in self.vertices:
606 for u in self.uv_layers:
610 def create_strip(self, face, max_len):
611 # Find an edge with another unused face next to it
614 other = e.other_face(face)
615 if other and not other.flag:
622 # Add initial vertices so that we'll complete the edge on the first
624 vertices = face.pivot_vertices(*edge.vertices)
626 result = [vertices[-1], vertices[0]]
628 result = [vertices[-2], vertices[-1]]
633 vertices = face.pivot_vertices(*result[-2:])
636 # Quads need special handling because the winding of every other
637 # triangle in the strip is reversed
638 if len(vertices)==4 and not k:
639 result.append(vertices[3])
640 result.append(vertices[2])
641 if len(vertices)==4 and k:
642 result.append(vertices[3])
644 if len(result)>=max_len:
647 # Hop over the last edge
648 edge = face.get_edge(*result[-2:])
649 face = edge.other_face(face)
650 if not face or face.flag:
655 def create_mesh_from_object(context, obj, progress):
657 raise Exception("Object is not a mesh")
659 progress.push_task("Preparing mesh", 0.0, 0.2)
661 objs = [(obj, mathutils.Matrix())]
667 if c.type=="MESH" and c.compound:
668 objs.append((c, m*c.matrix_local))
673 bmesh = o.to_mesh(context.scene, True, "PREVIEW")
674 bmeshes.append(bmesh)
676 # Object.to_mesh does not copy custom properties
677 bmesh.winding_test = o.data.winding_test
678 bmesh.smoothing = o.data.smoothing
679 bmesh.use_lines = o.data.use_lines
680 bmesh.vertex_groups = o.data.vertex_groups
681 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
682 bmesh.use_uv = o.data.use_uv
683 bmesh.tbn_vecs = o.data.tbn_vecs
684 bmesh.tbn_uvtex = o.data.tbn_uvtex
694 progress.set_task("Triangulating", 0.2, 0.3)
695 mesh.prepare_triangles(progress)
696 progress.set_task("Smoothing", 0.3, 0.6)
697 mesh.prepare_smoothing(progress)
698 progress.set_task("Vertex groups", 0.6, 0.7)
699 mesh.prepare_vertex_groups(obj)
700 progress.set_task("Preparing UVs", 0.7, 1.0)
701 mesh.prepare_uv(obj, progress)
703 # Discard the temporary Blender meshes after making sure there's no
704 # references to the data
705 mesh.drop_references()
707 bpy.data.meshes.remove(m)