]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
Properly handle compound children with non-identity local matrix
[libs/gl.git] / blender / io_mspgl / mesh.py
1 import math
2 import mathutils
3
4 def make_edge_key(i1, i2):
5         return (min(i1, i2), max(i1, i2))
6
7 class Edge:
8         def __init__(self, me):
9                 if me.__class__==Edge:
10                         self._medge = me._medge
11                         self.vertices = me.vertices[:]
12                         self.smooth = me.smooth
13                 else:
14                         self._medge = me
15                         self.smooth = False
16                 self.faces = []
17
18         def __getattr__(self, attr):
19                 return getattr(self._medge, attr)
20
21         def check_smooth(self, limit):
22                 if len(self.faces)!=2:
23                         return
24
25                 d = self.faces[0].normal.dot(self.faces[1].normal)
26                 self.smooth = ((d>limit and self.faces[0].use_smooth and self.faces[1].use_smooth) or d>0.99995)
27
28         def other_face(self, f):
29                 if f.index==self.faces[0].index:
30                         if len(self.faces)>=2:
31                                 return self.faces[1]
32                         else:
33                                 return None
34                 else:
35                         return self.faces[0]
36
37         def other_vertex(self, v):
38                 if v.index==self.vertices[0].index:
39                         return self.vertices[1]
40                 else:
41                         return self.vertices[0]
42
43
44 class Vertex:
45         def __init__(self, mv):
46                 if mv.__class__==Vertex:
47                         self._mvert = mv._mvert
48                         self.co = mv.co
49                         self.normal = mv.normal
50                         self.uvs = mv.uvs[:]
51                         self.tan = mv.tan
52                         self.bino = mv.bino
53                         self.group_weight_scale = mv.group_weight_scale
54                 else:
55                         self._mvert = mv
56                         self.co = mv.co
57                         self.normal = mv.normal
58                         self.uvs = []
59                         self.tan = None
60                         self.bino = None
61                         self.group_weight_scale = 1
62                 self.flag = False
63                 self.faces = []
64
65         def __getattr__(self, attr):
66                 return getattr(self._mvert, attr)
67
68         def __cmp__(self, other):
69                 if other is None:
70                         return 1
71                 return cmp(self.index, other.index)
72
73
74 class Face:
75         def __init__(self, mf):
76                 self._mface = mf
77                 self.edges = []
78                 self.vertices = mf.vertices[:]
79                 self.uvs = []
80                 self.flag = False
81
82         def __getattr__(self, attr):
83                 return getattr(self._mface, attr)
84
85         def __cmp__(self, other):
86                 if other is None:
87                         return 1
88                 return cmp(self.index, other.index)
89
90         def pivot_vertices(self, *vt):
91                 flags = [(v in vt) for v in self.vertices]
92                 l = len(self.vertices)
93                 for i in range(l):
94                         if flags[i] and not flags[(i+l-1)%l]:
95                                 return self.vertices[i:]+self.vertices[:i]
96
97         def get_edge(self, v1, v2):     
98                 key = make_edge_key(v1.index, v2.index)
99                 for e in self.edges:
100                         if e.key==key:
101                                 return e
102                 raise KeyError("No edge %s"%(key,))
103
104         def get_neighbors(self):
105                 neighbors = [e.other_face(self) for e in self.edges]
106                 return list(filter(bool, neighbors))
107
108
109 class Line:
110         def __init__(self, e):
111                 self.edge = e
112                 self.vertices = e.vertices[:]
113                 self.flag = False
114
115
116 class UvLayer:
117         def __init__(self, l, t):
118                 self._layer = l
119                 self.uvtex = t
120                 self.name = self.uvtex.name
121                 self.unit = None
122                 self.hidden = False
123                 dot = self.name.find('.')
124                 if dot>=0:
125                         ext = self.name[dot:]
126                         if ext.startswith(".unit") and ext[5:].isdigit():
127                                 self.unit = int(ext[5:])
128                         elif ext==".hidden":
129                                 self.hidden = True
130
131         def __getattr__(self, attr):
132                 return getattr(self._layer, attr)
133
134 class FakeUvLayer:
135         def __init__(self, n):
136                 self.uvtex = None
137                 self.name = n
138                 self.unit = None
139                 self.hidden = False
140
141 class Mesh:
142         def __init__(self, m):
143                 self._mesh = m
144
145                 self.vertices = [Vertex(v) for v in self.vertices]
146                 self.faces = [Face(f) for f in self.polygons]
147
148                 self.materials = self.materials[:]
149
150                 self.uv_layers = [UvLayer(self.uv_layers[i], self.uv_textures[i]) for i in range(len(self.uv_layers))]
151                 self.assign_texture_units()
152
153                 for f in self.faces:
154                         if len(f.vertices)>4:
155                                 raise ValueError("Ngons are not supported")
156                         f.vertices = [self.vertices[i] for i in f.vertices]
157                         for v in f.vertices:
158                                 v.faces.append(f)
159                         for u in self.uv_layers:
160                                 f.uvs.append([u.data[f.loop_indices[i]].uv for i in range(len(f.vertices))])
161
162                 self.edges = dict([(e.key, Edge(e)) for e in self.edges])
163                 for f in self.faces:
164                         for k in f.edge_keys:
165                                 e = self.edges[k]
166                                 e.faces.append(self.faces[f.index])
167                                 f.edges.append(e)
168
169                 self.lines = [Line(e) for e in self.edges.values() if not e.faces]
170                 for l in self.lines:
171                         l.vertices = [self.vertices[i] for i in l.vertices]
172
173                 if self.use_auto_smooth:
174                         smooth_limit = math.cos(self.auto_smooth_angle)
175                 else:
176                         smooth_limit = -1
177
178                 for e in self.edges.values():
179                         e.vertices = [self.vertices[i] for i in e.vertices]
180                         e.check_smooth(smooth_limit)
181
182         def __getattr__(self, attr):
183                 return getattr(self._mesh, attr)
184
185         def transform(self, matrix):
186                 for v in self.vertices:
187                         v.co = matrix*v.co
188
189         def splice(self, other):
190                 material_map = []
191                 for m in other.materials:
192                         if m in self.materials:
193                                 material_map.append(self.materials.index(m))
194                         else:
195                                 material_map.append(len(self.materials))
196                                 self.materials.append(m)
197
198                 offset = len(self.vertices)
199                 for v in other.vertices:
200                         v.index += offset
201                         self.vertices.append(v)
202
203                 offset = len(self.faces)
204                 for f in other.faces:
205                         f.index += offset
206                         if other.materials:
207                                 f.material_index = material_map[f.material_index]
208                         self.faces.append(f)
209
210                 for e in other.edges.values():
211                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
212                         self.edges[e.key] = e
213
214                 self.lines += other.lines
215
216         def flatten_faces(self):
217                 for f in self.faces:
218                         f.use_smooth = False
219
220                 for e in self.edges.values():
221                         e.check_smooth(1)
222
223         def assign_texture_units(self):
224                 # Assign texture units for any non-hidden UV layers that lack one
225                 units = [u.unit for u in self.uv_layers if u.unit is not None]
226                 if units:
227                         free_unit = max(units)+1
228                 else:
229                         free_unit = 0
230                 for u in self.uv_layers:
231                         if u.unit is None:
232                                 if not u.hidden:
233                                         u.unit = free_unit
234                                         free_unit += 1
235
236         def generate_material_uv(self):
237                 self.uv_layers.append(FakeUvLayer("material_tex"))
238                 self.assign_texture_units()
239                 for f in self.faces:
240                         f.uvs.append([((f.material_index+0.5)/len(self.materials), 0.5)]*len(f.vertices))
241
242         def split_vertices(self, find_group_func, progress, *args):
243                 groups = []
244                 for i in range(len(self.vertices)):
245                         v = self.vertices[i]
246                         for f in v.faces:
247                                 f.flag = False
248
249                         vg = []
250                         for f in v.faces:
251                                 if not f.flag:
252                                         vg.append(find_group_func(v, f, *args))
253
254                         groups.append(vg)
255
256                         if progress:
257                                 progress.set_progress(i*0.5/len(self.vertices))
258
259                 for i in range(len(self.vertices)):
260                         if len(groups[i])==1:
261                                 continue
262
263                         for g in groups[i][1:]:
264                                 v = Vertex(self.vertices[i])
265                                 v.index = len(self.vertices)
266                                 self.vertices.append(v)
267
268                                 v_edges = []
269                                 v_edge_keys = set()
270                                 for f in g:
271                                         for e in f.edges:
272                                                 if e.key in v_edge_keys or self.vertices[i] not in e.vertices:
273                                                         continue
274
275                                                 e_faces_in_g = [c for c in e.faces if c in g]
276                                                 boundary = len(e_faces_in_g)<len(e.faces)
277                                                 v_edges.append((e, boundary, e_faces_in_g))
278                                                 v_edge_keys.add(e.key)
279
280                                 for e, boundary, e_faces_in_g in v_edges:
281                                         if boundary:
282                                                 ne = Edge(e)
283                                                 for c in e_faces_in_g:
284                                                         e.faces.remove(c)
285                                                         c.edges[c.edges.index(e)] = ne
286                                                         ne.faces.append(c)
287                                                 e = ne
288                                         else:
289                                                 del self.edges[e.key]
290
291                                         e.vertices[e.vertices.index(self.vertices[i])] = v
292
293                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
294                                         self.edges[e.key] = e
295
296                                 for f in g:
297                                         self.vertices[i].faces.remove(f)
298                                         f.vertices[f.vertices.index(self.vertices[i])] = v
299                                         v.faces.append(f)
300
301                         if progress:
302                                 progress.set_progress(0.5+i*0.5/len(self.vertices))
303
304         def split_smooth(self, progress=None):
305                 self.split_vertices(self.find_smooth_group, progress)
306
307         def split_uv(self, index, progress=None):
308                 self.split_vertices(self.find_uv_group, progress, index)
309
310         def find_smooth_group(self, vertex, face):
311                 face.flag = True
312                 queue = [face]
313
314                 for f in queue:
315                         for e in f.edges:
316                                 other = e.other_face(f)
317                                 if other not in vertex.faces:
318                                         continue
319
320                                 if e.smooth:
321                                         if not other.flag:
322                                                 other.flag = True
323                                                 queue.append(other)
324
325                 return queue
326
327         def find_uv_group(self, vertex, face, index):
328                 uv = face.uvs[index][face.vertices.index(vertex)]
329                 face.flag = True
330                 group = [face]
331                 for f in vertex.faces:
332                         if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
333                                 f.flag = True
334                                 group.append(f)
335                 return group
336
337         def compute_normals(self):
338                 for v in self.vertices:
339                         if v.faces:
340                                 v.normal = mathutils.Vector()
341                                 for f in v.faces:
342                                         fv = f.pivot_vertices(v)
343                                         edge1 = fv[1].co-fv[0].co
344                                         edge2 = fv[-1].co-fv[0].co
345                                         if edge1.length and edge2.length:
346                                                 weight = 1
347                                                 if len(f.get_edge(fv[0], fv[1]).faces)==1:
348                                                         weight += 1
349                                                 if len(f.get_edge(fv[0], fv[-1]).faces)==1:
350                                                         weight += 1
351                                                 v.normal += f.normal*edge1.angle(edge2)*weight
352                                 if v.normal.length:
353                                         v.normal.normalize()
354                                 else:
355                                         v.normal = mathutils.Vector((0, 0, 1))
356                         else:
357                                 # XXX Should use edges to compute normal
358                                 v.normal = mathutils.Vector((0, 0, 1))
359
360         def compute_uv(self):
361                 for v in self.vertices:
362                         if v.faces:
363                                 f = v.faces[0]
364                                 i = f.vertices.index(v)
365                                 v.uvs = [u[i] for u in f.uvs]
366                         else:
367                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
368
369         def compute_tbn(self, index):
370                 if not self.uv_layers:
371                         return
372
373                 for v in self.vertices:
374                         v.tan = mathutils.Vector()
375                         v.bino = mathutils.Vector()
376                         for f in v.faces:
377                                 fv = f.pivot_vertices(v)
378                                 uv0 = fv[0].uvs[index]
379                                 uv1 = fv[1].uvs[index]
380                                 uv2 = fv[-1].uvs[index]
381                                 du1 = uv1[0]-uv0[0]
382                                 du2 = uv2[0]-uv0[0]
383                                 dv1 = uv1[1]-uv0[1]
384                                 dv2 = uv2[1]-uv0[1]
385                                 edge1 = fv[1].co-fv[0].co
386                                 edge2 = fv[-1].co-fv[0].co
387                                 div = (du1*dv2-du2*dv1)
388                                 if div:
389                                         mul = edge1.angle(edge2)/div
390                                         v.tan += (edge1*dv2-edge2*dv1)*mul
391                                         v.bino += (edge2*du1-edge1*du2)*mul
392
393                         if v.tan.length:
394                                 v.tan.normalize()
395                         if v.bino.length:
396                                 v.bino.normalize()
397
398         def sort_vertex_groups(self, max_groups):
399                 for v in self.vertices:
400                         if v.groups:
401                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)
402                                 v.group_weight_scale = 1.0/sum(g.weight for g in v.groups[:max_groups])
403
404         def create_strip(self, face, max_len):
405                 # Find an edge with another unused face next to it
406                 edge = None
407                 for e in face.edges:
408                         other = e.other_face(face)
409                         if other and not other.flag:
410                                 edge = e
411                                 break
412
413                 if not edge:
414                         return None
415
416                 # Add initial vertices so that we'll complete the edge on the first
417                 # iteration
418                 vertices = face.pivot_vertices(*edge.vertices)
419                 if len(vertices)==3:
420                         result = [vertices[-1], vertices[0]]
421                 else:
422                         result = [vertices[-2], vertices[-1]]
423
424                 while 1:
425                         face.flag = True
426
427                         vertices = face.pivot_vertices(*result[-2:])
428                         k = len(result)%2
429
430                         # Quads need special handling because the winding of every other
431                         # triangle in the strip is reversed
432                         if len(vertices)==4 and not k:
433                                 result.append(vertices[3])
434                         result.append(vertices[2])
435                         if len(vertices)==4 and k:
436                                 result.append(vertices[3])
437
438                         if len(result)>=max_len:
439                                 break
440
441                         # Hop over the last edge
442                         edge = face.get_edge(*result[-2:])
443                         face = edge.other_face(face)
444                         if not face or face.flag:
445                                 break
446
447                 return result