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