]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
42b1b1bd054417a4156fbd247cfad37592f23785
[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, me):
10                 if me.__class__==Edge:
11                         self._medge = me._medge
12                         self.vertices = me.vertices[:]
13                         self.smooth = me.smooth
14                 else:
15                         self._medge = me
16                         self.smooth = False
17                 self.key = me.key
18                 self.faces = []
19
20         def __getattr__(self, attr):
21                 return getattr(self._medge, attr)
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, mv):
48                 if mv.__class__==Vertex:
49                         self._mvert = mv._mvert
50                         self.uvs = mv.uvs[:]
51                         self.tan = mv.tan
52                         self.bino = mv.bino
53                 else:
54                         self._mvert = mv
55                         self.uvs = []
56                         self.tan = None
57                         self.bino = None
58                 self.index = mv.index
59                 self.co = mv.co
60                 self.normal = mv.normal
61                 self.flag = False
62                 self.edges = []
63                 self.faces = []
64                 self.groups = mv.groups[:]
65
66         def __getattr__(self, attr):
67                 return getattr(self._mvert, attr)
68
69         def __cmp__(self, other):
70                 if other is None:
71                         return 1
72                 return cmp(self.index, other.index)
73
74
75 class VertexGroup:
76         def __init__(self, base):
77                 self._base = base
78                 self.group = base.group
79                 self.weight = base.weight
80
81         def __getattr__(self, attr):
82                 return getattr(self._mvert, attr)
83
84
85 class Face:
86         def __init__(self, mf):
87                 self._mface = mf
88                 self.index = mf.index
89                 self.edges = []
90                 self.vertices = mf.vertices[:]
91                 self.uvs = []
92                 self.flag = False
93
94         def __getattr__(self, attr):
95                 return getattr(self._mface, attr)
96
97         def __cmp__(self, other):
98                 if other is None:
99                         return 1
100                 return cmp(self.index, other.index)
101
102         def pivot_vertex(self, v):
103                 n = self.vertices.index(v)
104                 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
105
106         def pivot_vertices(self, *vt):
107                 flags = [(v in vt) for v in self.vertices]
108                 l = len(self.vertices)
109                 for i in range(l):
110                         if flags[i] and not flags[(i+l-1)%l]:
111                                 return self.vertices[i:]+self.vertices[:i]
112
113         def get_edge(self, v1, v2):     
114                 key = make_edge_key(v1.index, v2.index)
115                 for e in self.edges:
116                         if e.key==key:
117                                 return e
118                 raise KeyError("No edge %s"%(key,))
119
120         def other_edge(self, e, v):
121                 for d in self.edges:
122                         if d!=e and v in d.vertices:
123                                 return d
124
125         def get_neighbors(self):
126                 neighbors = [e.other_face(self) for e in self.edges]
127                 return list(filter(bool, neighbors))
128
129
130 class Line:
131         def __init__(self, e):
132                 self.edge = e
133                 self.vertices = e.vertices[:]
134                 self.flag = False
135
136
137 class UvLayer:
138         def __init__(self, arg):
139                 if type(arg)==str:
140                         self._layer = None
141                         self.name = arg
142                 else:
143                         self._layer = arg
144                         self.name = arg.name
145                         self.uvs = [d.uv for d in self.data]
146
147                 self.unit = None
148                 self.hidden = False
149
150                 dot = self.name.find('.')
151                 if dot>=0:
152                         ext = self.name[dot:]
153                         if ext.startswith(".unit") and ext[5:].isdigit():
154                                 self.unit = int(ext[5:])
155                         elif ext==".hidden":
156                                 self.hidden = True
157
158         def __getattr__(self, attr):
159                 return getattr(self._layer, attr)
160
161
162 class Mesh:
163         def __init__(self, m):
164                 self._mesh = m
165
166                 self.winding_test = m.winding_test
167                 self.tbn_vecs = m.tbn_vecs
168                 self.vertex_groups = m.vertex_groups
169
170                 self.vertices = [Vertex(v) for v in self.vertices]
171                 self.faces = [Face(f) for f in self.polygons]
172                 self.edges = [Edge(e) for e in self.edges]
173                 self.edge_map = {e.key: e for e in self.edges}
174                 self.loops = self.loops[:]
175
176                 self.materials = self.materials[:]
177                 if self.use_uv=='NONE' or not self.uv_layers:
178                         self.uv_layers = []
179                 else:
180                         self.uv_layers = [UvLayer(u) for u in self.uv_layers]
181                         self.uv_layers = sorted([u for u in self.uv_layers if not u.hidden], key=(lambda u: (u.unit or 1000, u.name)))
182
183                         if self.use_uv=='UNIT0':
184                                 self.uv_layers = [self.uv_layers[0]]
185
186                         next_unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
187                         for u in self.uv_layers:
188                                 if not u.unit:
189                                         u.unit = next_unit
190                                         next_unit += 1
191
192                 for v in self.vertices:
193                         v.groups = [VertexGroup(g) for g in v.groups]
194
195                 for f in self.faces:
196                         if len(f.vertices)>4:
197                                 raise ValueError("Ngons are not supported")
198
199                         f.vertices = [self.vertices[i] for i in f.vertices]
200                         for v in f.vertices:
201                                 v.faces.append(f)
202
203                         for k in f.edge_keys:
204                                 e = self.edge_map[k]
205                                 e.faces.append(f)
206                                 f.edges.append(e)
207
208                 for e in self.edges:
209                         e.vertices = [self.vertices[i] for i in e.vertices]
210                         for v in e.vertices:
211                                 v.edges.append(e)
212
213                 if self.use_lines:
214                         self.lines = [Line(e) for e in self.edges if not e.faces]
215                 else:
216                         self.lines = []
217
218         def __getattr__(self, attr):
219                 return getattr(self._mesh, attr)
220
221         def transform(self, matrix):
222                 for v in self.vertices:
223                         v.co = matrix*v.co
224
225         def splice(self, other):
226                 if len(self.uv_layers)!=len(other.uv_layers):
227                         raise ValueError("Meshes have incompatible UV layers")
228                 for i, u in enumerate(self.uv_layers):
229                         if u.name!=other.uv_layers[i].name:
230                                 raise ValueError("Meshes have incompatible UV layers")
231
232                 material_map = []
233                 for m in other.materials:
234                         if m in self.materials:
235                                 material_map.append(self.materials.index(m))
236                         else:
237                                 material_map.append(len(self.materials))
238                                 self.materials.append(m)
239
240                 for i, u in enumerate(self.uv_layers):
241                         u.uvs += other.uv_layers[i].uvs
242
243                 offset = len(self.vertices)
244                 self.vertices += other.vertices
245                 for v in self.vertices[offset:]:
246                         v.index += offset
247
248                 loop_offset = len(self.loops)
249                 self.loops += other.loops
250
251                 offset = len(self.faces)
252                 self.faces += other.faces
253                 for f in self.faces[offset:]:
254                         f.index += offset
255                         f.loop_start += loop_offset
256                         f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total)
257                         if other.materials:
258                                 f.material_index = material_map[f.material_index]
259
260                 offset = len(self.edges)
261                 self.edges += other.edges
262                 for e in self.edges[offset:]:
263                         e.index += offset
264                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
265                         self.edge_map[e.key] = e
266
267                 self.lines += other.lines
268
269         def prepare_smoothing(self, progress):
270                 smooth_limit = -1
271                 if self.smoothing=='NONE':
272                         for f in self.faces:
273                                 f.use_smooth = False
274
275                         smooth_limit = 1
276                 elif self.use_auto_smooth:
277                         smooth_limit = math.cos(self.auto_smooth_angle)
278
279                 for e in self.edges:
280                         e.check_smooth(smooth_limit)
281
282                 progress.push_task("Sharp edges", 0.0, 0.7)
283                 self.split_vertices(self.find_smooth_group, progress)
284
285                 if self.smoothing!='BLENDER':
286                         progress.set_task("Updating normals", 0.7, 1.0)
287                         self.compute_normals(progress)
288
289                 progress.pop_task()
290
291         def prepare_vertex_groups(self, obj):
292                 for v in self.vertices:
293                         if v.groups:
294                                 weight_sum = sum(g.weight for g in v.groups)
295                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
296                                 weight_scale = weight_sum/sum(g.weight for g in v.groups)
297                                 for g in v.groups:
298                                         g.weight *= weight_scale
299
300                 if obj.parent and obj.parent.type=="ARMATURE":
301                         armature = obj.parent.data
302                         bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
303                         group_index_map = {i: i for i in range(len(obj.vertex_groups))}
304                         for g in first_obj.vertex_groups:
305                                 if g.name in bone_indices:
306                                         group_index_map[g.index] = bone_indices[g.name]
307
308                         for v in self.vertices:
309                                 for g in v.groups:
310                                         g.group = group_index_map[g.group]
311
312         def prepare_uv(self, obj, progress):
313                 if obj.material_tex and self.use_uv!='NONE':
314                         layer = UvLayer("material_tex")
315
316                         if self.use_uv=='UNIT0':
317                                 self.uv_layers = [layer]
318                                 layer.unit = 0
319                         else:
320                                 self.uv_layers.append(layer)
321                                 layer.unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
322
323                         layer.uvs = [None]*len(self.loops)
324                         for f in self.faces:
325                                 uv = mathutils.Vector(((f.material_index+0.5)/len(self.materials), 0.5))
326                                 for i in f.loop_indices:
327                                         layer.uvs[i] = uv
328
329                 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']
330                 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
331
332                 if array_uv_layers:
333                         for f in self.faces:
334                                 layer = 0
335                                 if f.material_index<len(self.materials):
336                                         mat = self.materials[f.material_index]
337                                         if mat and mat.array_atlas:
338                                                 layer = mat.array_layer
339
340                                 for l in array_uv_layers:
341                                         for i in f.loop_indices:
342                                                 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
343
344                 for f in self.faces:
345                         for u in self.uv_layers:
346                                 f.uvs.append([u.uvs[i] for i in f.loop_indices])
347
348                 prog_count = len(self.uv_layers)
349                 prog_step = 0
350
351                 tbn_layer_index = -1
352                 if self.tbn_vecs:
353                         uv_names = [u.name for u in self.uv_layers]
354                         if self.tbn_uvtex in uv_names:
355                                 prog_count += 1
356                                 tbn_layer_index = uv_names.index(self.tbn_uvtex)
357                                 progress.push_task_slice("Computing TBN", 0, prog_count)
358                                 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
359                                 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
360                                 self.compute_tbn(tbn_layer_index, progress)
361                                 progress.pop_task()
362                                 prog_step = 2
363
364                 for i, u in enumerate(self.uv_layers):
365                         if i==tbn_layer_index:
366                                 continue
367
368                         progress.push_task_slice(u.name, prog_step, prog_count)
369                         self.split_vertices(self.find_uv_group, progress, i)
370                         progress.pop_task()
371                         prog_step += 1
372
373                 for v in self.vertices:
374                         if v.faces:
375                                 f = v.faces[0]
376                                 i = f.vertices.index(v)
377                                 v.uvs = [u[i] for u in f.uvs]
378                         else:
379                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
380
381         def split_vertices(self, find_group_func, progress, *args):
382                 groups = []
383                 for i in range(len(self.vertices)):
384                         v = self.vertices[i]
385                         for f in v.faces:
386                                 f.flag = False
387
388                         vg = []
389                         for f in v.faces:
390                                 if not f.flag:
391                                         vg.append(find_group_func(v, f, *args))
392
393                         groups.append(vg)
394
395                         progress.set_progress(i*0.5/len(self.vertices))
396
397                 for i in range(len(self.vertices)):
398                         for g in groups[i][1:]:
399                                 v = Vertex(self.vertices[i])
400                                 v.index = len(self.vertices)
401                                 self.vertices.append(v)
402
403                                 v_edges = []
404                                 for e in self.vertices[i].edges:
405                                         e_faces_in_g = [f for f in e.faces if f in g]
406                                         if e_faces_in_g:
407                                                 boundary = len(e_faces_in_g)<len(e.faces)
408                                                 v_edges.append((e, boundary, e_faces_in_g))
409
410                                 for e, boundary, e_faces_in_g in v_edges:
411                                         if boundary:
412                                                 ne = Edge(e)
413                                                 ne.index = len(self.edges)
414                                                 self.edges.append(ne)
415
416                                                 ne.other_vertex(self.vertices[i]).edges.append(ne)
417
418                                                 for f in e_faces_in_g:
419                                                         e.faces.remove(f)
420                                                         f.edges[f.edges.index(e)] = ne
421                                                         ne.faces.append(f)
422                                                 e = ne
423                                         else:
424                                                 del self.edge_map[e.key]
425                                                 self.vertices[i].edges.remove(e)
426
427                                         e.vertices[e.vertices.index(self.vertices[i])] = v
428                                         v.edges.append(e)
429
430                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
431                                         self.edge_map[e.key] = e
432
433                                 for f in g:
434                                         self.vertices[i].faces.remove(f)
435                                         f.vertices[f.vertices.index(self.vertices[i])] = v
436                                         v.faces.append(f)
437
438                         progress.set_progress(0.5+i*0.5/len(self.vertices))
439
440         def find_smooth_group(self, vertex, face):
441                 face.flag = True
442
443                 edges = [e for e in face.edges if vertex in e.vertices]
444
445                 group = [face]
446                 for e in edges:
447                         f = face
448                         while e.smooth:
449                                 f = e.other_face(f)
450                                 if not f or f.flag:
451                                         break
452
453                                 f.flag = True
454                                 group.append(f)
455                                 e = f.other_edge(e, vertex)
456
457                 return group
458
459         def find_uv_group(self, vertex, face, index):
460                 uv = face.uvs[index][face.vertices.index(vertex)]
461                 face.flag = True
462
463                 group = [face]
464                 for f in vertex.faces:
465                         if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
466                                 f.flag = True
467                                 group.append(f)
468
469                 return group
470
471         def compute_normals(self, progress):
472                 for i, v in enumerate(self.vertices):
473                         v.normal = mathutils.Vector()
474                         for f in v.faces:
475                                 fv = f.pivot_vertices(v)
476                                 edge1 = fv[1].co-fv[0].co
477                                 edge2 = fv[-1].co-fv[0].co
478                                 if edge1.length and edge2.length:
479                                         v.normal += f.normal*edge1.angle(edge2)
480
481                         if v.normal.length:
482                                 v.normal.normalize()
483                         else:
484                                 v.normal = mathutils.Vector((0, 0, 1))
485
486                         progress.set_progress(i/len(self.vertices))
487
488         def compute_tbn(self, index, progress):
489                 layer_uvs = self.uv_layers[index].uvs
490
491                 for i, v in enumerate(self.vertices):
492                         v.tan = mathutils.Vector()
493                         v.bino = mathutils.Vector()
494                         for f in v.faces:
495                                 vi = f.pivot_vertex(v)
496                                 uv0 = layer_uvs[f.loop_indices[vi[0]]]
497                                 uv1 = layer_uvs[f.loop_indices[vi[1]]]
498                                 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
499                                 du1 = uv1[0]-uv0[0]
500                                 du2 = uv2[0]-uv0[0]
501                                 dv1 = uv1[1]-uv0[1]
502                                 dv2 = uv2[1]-uv0[1]
503                                 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
504                                 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
505                                 div = (du1*dv2-du2*dv1)
506                                 if div:
507                                         mul = edge1.angle(edge2)/div
508                                         v.tan += (edge1*dv2-edge2*dv1)*mul
509                                         v.bino += (edge2*du1-edge1*du2)*mul
510
511                         if v.tan.length:
512                                 v.tan.normalize()
513                         if v.bino.length:
514                                 v.bino.normalize()
515
516                         progress.set_progress(i/len(self.vertices))
517
518         def drop_references(self):
519                 for v in self.vertices:
520                         v._mvert = None
521                         for g in v.groups:
522                                 g._base = None
523                 for e in self.edges:
524                         e._medge = None
525                 for f in self.faces:
526                         f._mface = None
527                 for u in self.uv_layers:
528                         u._layer = None
529                 self._mesh = None
530
531         def create_strip(self, face, max_len):
532                 # Find an edge with another unused face next to it
533                 edge = None
534                 for e in face.edges:
535                         other = e.other_face(face)
536                         if other and not other.flag:
537                                 edge = e
538                                 break
539
540                 if not edge:
541                         return None
542
543                 # Add initial vertices so that we'll complete the edge on the first
544                 # iteration
545                 vertices = face.pivot_vertices(*edge.vertices)
546                 if len(vertices)==3:
547                         result = [vertices[-1], vertices[0]]
548                 else:
549                         result = [vertices[-2], vertices[-1]]
550
551                 while 1:
552                         face.flag = True
553
554                         vertices = face.pivot_vertices(*result[-2:])
555                         k = len(result)%2
556
557                         # Quads need special handling because the winding of every other
558                         # triangle in the strip is reversed
559                         if len(vertices)==4 and not k:
560                                 result.append(vertices[3])
561                         result.append(vertices[2])
562                         if len(vertices)==4 and k:
563                                 result.append(vertices[3])
564
565                         if len(result)>=max_len:
566                                 break
567
568                         # Hop over the last edge
569                         edge = face.get_edge(*result[-2:])
570                         face = edge.other_face(face)
571                         if not face or face.flag:
572                                 break
573
574                 return result
575
576 def create_mesh_from_object(context, obj, progress):
577         if obj.type!="MESH":
578                 raise Exception("Object is not a mesh")
579
580         progress.push_task("Preparing mesh", 0.0, 0.3)
581
582         objs = [(obj, mathutils.Matrix())]
583         i = 0
584         while i<len(objs):
585                 o, m = objs[i]
586                 i += 1
587                 for c in o.children:
588                         if c.type=="MESH" and c.compound:
589                                 objs.append((c, m*c.matrix_local))
590
591         mesh = None
592         bmeshes = []
593         for o, m in objs:
594                 bmesh = o.to_mesh(context.scene, True, "PREVIEW")
595                 bmeshes.append(bmesh)
596
597                 # Object.to_mesh does not copy custom properties
598                 bmesh.winding_test = o.data.winding_test
599                 bmesh.smoothing = o.data.smoothing
600                 bmesh.use_lines = o.data.use_lines
601                 bmesh.vertex_groups = o.data.vertex_groups
602                 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
603                 bmesh.use_uv = o.data.use_uv
604                 bmesh.tbn_vecs = o.data.tbn_vecs
605                 bmesh.tbn_uvtex = o.data.tbn_uvtex
606
607                 me = Mesh(bmesh)
608                 me.transform(m)
609
610                 if mesh:
611                         mesh.splice(me)
612                 else:
613                         mesh = me
614
615         progress.set_task("Smoothing", 0.3, 0.6)
616         mesh.prepare_smoothing(progress)
617         progress.set_task("Vertex groups", 0.6, 0.7)
618         mesh.prepare_vertex_groups(obj)
619         progress.set_task("Preparing UVs", 0.7, 1.0)
620         mesh.prepare_uv(obj, progress)
621
622         mesh.drop_references()
623         for m in bmeshes:
624                 bpy.data.meshes.remove(m)
625
626         progress.pop_task()
627
628         return mesh