]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
Raise an exception if attempting to export a mesh with ngons
[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                         if len(f.vertices)>4:
152                                 raise ValueError("Ngons are not supported")
153                         f.vertices = [self.vertices[i] for i in f.vertices]
154                         for v in f.vertices:
155                                 v.faces.append(f)
156                         for u in self.uv_layers:
157                                 f.uvs.append([u.data[f.loop_indices[i]].uv for i in range(len(f.vertices))])
158
159                 self.edges = dict([(e.key, Edge(e)) for e in self.edges])
160                 for f in self.faces:
161                         for k in f.edge_keys:
162                                 e = self.edges[k]
163                                 e.faces.append(self.faces[f.index])
164                                 f.edges.append(e)
165
166                 self.lines = [Line(e) for e in self.edges.values() if not e.faces]
167                 for l in self.lines:
168                         l.vertices = [self.vertices[i] for i in l.vertices]
169
170                 if self.use_auto_smooth:
171                         smooth_limit = math.cos(self.auto_smooth_angle)
172                 else:
173                         smooth_limit = -1
174
175                 for e in self.edges.values():
176                         e.vertices = [self.vertices[i] for i in e.vertices]
177                         e.check_smooth(smooth_limit)
178
179         def __getattr__(self, attr):
180                 return getattr(self._mesh, attr)
181
182         def splice(self, other):
183                 material_map = []
184                 for m in other.materials:
185                         if m in self.materials:
186                                 material_map.append(self.materials.index(m))
187                         else:
188                                 material_map.append(len(self.materials))
189                                 self.materials.append(m)
190
191                 offset = len(self.vertices)
192                 for v in other.vertices:
193                         v.index += offset
194                         self.vertices.append(v)
195
196                 offset = len(self.faces)
197                 for f in other.faces:
198                         f.index += offset
199                         if other.materials:
200                                 f.material_index = material_map[f.material_index]
201                         self.faces.append(f)
202
203                 for e in other.edges.values():
204                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
205                         self.edges[e.key] = e
206
207                 self.lines += other.lines
208
209         def flatten_faces(self):
210                 for f in self.faces:
211                         f.use_smooth = False
212
213                 for e in self.edges.values():
214                         e.check_smooth(1)
215
216         def assign_texture_units(self):
217                 # Assign texture units for any non-hidden UV layers that lack one
218                 units = [u.unit for u in self.uv_layers if u.unit is not None]
219                 if units:
220                         free_unit = max(units)+1
221                 else:
222                         free_unit = 0
223                 for u in self.uv_layers:
224                         if u.unit is None:
225                                 if not u.hidden:
226                                         u.unit = free_unit
227                                         free_unit += 1
228
229         def generate_material_uv(self):
230                 self.uv_layers.append(FakeUvLayer("material_tex"))
231                 self.assign_texture_units()
232                 for f in self.faces:
233                         f.uvs.append([((f.material_index+0.5)/len(self.materials), 0.5)]*len(f.vertices))
234
235         def split_vertices(self, find_group_func, progress, *args):
236                 groups = []
237                 for i in range(len(self.vertices)):
238                         v = self.vertices[i]
239                         for f in v.faces:
240                                 f.flag = False
241
242                         vg = []
243                         for f in v.faces:
244                                 if not f.flag:
245                                         vg.append(find_group_func(v, f, *args))
246
247                         groups.append(vg)
248
249                         if progress:
250                                 progress.set_progress(i*0.5/len(self.vertices))
251
252                 for i in range(len(self.vertices)):
253                         if len(groups[i])==1:
254                                 continue
255
256                         for g in groups[i][1:]:
257                                 v = Vertex(self.vertices[i])
258                                 v.index = len(self.vertices)
259                                 self.vertices.append(v)
260
261                                 v_edges = []
262                                 v_edge_keys = set()
263                                 for f in g:
264                                         for e in f.edges:
265                                                 if e.key in v_edge_keys or self.vertices[i] not in e.vertices:
266                                                         continue
267
268                                                 e_faces_in_g = [c for c in e.faces if c in g]
269                                                 boundary = len(e_faces_in_g)<len(e.faces)
270                                                 v_edges.append((e, boundary, e_faces_in_g))
271                                                 v_edge_keys.add(e.key)
272
273                                 for e, boundary, e_faces_in_g in v_edges:
274                                         if boundary:
275                                                 ne = Edge(e)
276                                                 for c in e_faces_in_g:
277                                                         e.faces.remove(c)
278                                                         c.edges[c.edges.index(e)] = ne
279                                                         ne.faces.append(c)
280                                                 e = ne
281                                         else:
282                                                 del self.edges[e.key]
283
284                                         e.vertices[e.vertices.index(self.vertices[i])] = v
285
286                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
287                                         self.edges[e.key] = e
288
289                                 for f in g:
290                                         self.vertices[i].faces.remove(f)
291                                         f.vertices[f.vertices.index(self.vertices[i])] = v
292                                         v.faces.append(f)
293
294                         if progress:
295                                 progress.set_progress(0.5+i*0.5/len(self.vertices))
296
297         def split_smooth(self, progress=None):
298                 self.split_vertices(self.find_smooth_group, progress)
299
300         def split_uv(self, index, progress=None):
301                 self.split_vertices(self.find_uv_group, progress, index)
302
303         def find_smooth_group(self, vertex, face):
304                 face.flag = True
305                 queue = [face]
306
307                 for f in queue:
308                         for e in f.edges:
309                                 other = e.other_face(f)
310                                 if other not in vertex.faces:
311                                         continue
312
313                                 if e.smooth:
314                                         if not other.flag:
315                                                 other.flag = True
316                                                 queue.append(other)
317
318                 return queue
319
320         def find_uv_group(self, vertex, face, index):
321                 uv = face.uvs[index][face.vertices.index(vertex)]
322                 face.flag = True
323                 group = [face]
324                 for f in vertex.faces:
325                         if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
326                                 f.flag = True
327                                 group.append(f)
328                 return group
329
330         def compute_normals(self):
331                 for v in self.vertices:
332                         if v.faces:
333                                 v.normal = mathutils.Vector()
334                                 for f in v.faces:
335                                         fv = f.pivot_vertices(v)
336                                         edge1 = fv[1].co-fv[0].co
337                                         edge2 = fv[-1].co-fv[0].co
338                                         if edge1.length and edge2.length:
339                                                 weight = 1
340                                                 if len(f.get_edge(fv[0], fv[1]).faces)==1:
341                                                         weight += 1
342                                                 if len(f.get_edge(fv[0], fv[-1]).faces)==1:
343                                                         weight += 1
344                                                 v.normal += f.normal*edge1.angle(edge2)*weight
345                                 if v.normal.length:
346                                         v.normal.normalize()
347                                 else:
348                                         v.normal = mathutils.Vector((0, 0, 1))
349                         else:
350                                 # XXX Should use edges to compute normal
351                                 v.normal = mathutils.Vector((0, 0, 1))
352
353         def compute_uv(self):
354                 for v in self.vertices:
355                         if v.faces:
356                                 f = v.faces[0]
357                                 i = f.vertices.index(v)
358                                 v.uvs = [u[i] for u in f.uvs]
359                         else:
360                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
361
362         def compute_tbn(self, index):
363                 if not self.uv_layers:
364                         return
365
366                 for v in self.vertices:
367                         v.tan = mathutils.Vector()
368                         v.bino = mathutils.Vector()
369                         for f in v.faces:
370                                 fv = f.pivot_vertices(v)
371                                 uv0 = fv[0].uvs[index]
372                                 uv1 = fv[1].uvs[index]
373                                 uv2 = fv[-1].uvs[index]
374                                 du1 = uv1[0]-uv0[0]
375                                 du2 = uv2[0]-uv0[0]
376                                 dv1 = uv1[1]-uv0[1]
377                                 dv2 = uv2[1]-uv0[1]
378                                 edge1 = fv[1].co-fv[0].co
379                                 edge2 = fv[-1].co-fv[0].co
380                                 div = (du1*dv2-du2*dv1)
381                                 if div:
382                                         mul = edge1.angle(edge2)/div
383                                         v.tan += (edge1*dv2-edge2*dv1)*mul
384                                         v.bino += (edge2*du1-edge1*du2)*mul
385
386                         if v.tan.length:
387                                 v.tan.normalize()
388                         if v.bino.length:
389                                 v.bino.normalize()
390
391         def sort_vertex_groups(self, max_groups):
392                 for v in self.vertices:
393                         if v.groups:
394                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)
395                                 v.group_weight_scale = 1.0/sum(g.weight for g in v.groups[:max_groups])
396
397         def create_strip(self, face, max_len):
398                 # Find an edge with another unused face next to it
399                 edge = None
400                 for e in face.edges:
401                         other = e.other_face(face)
402                         if other and not other.flag:
403                                 edge = e
404                                 break
405
406                 if not edge:
407                         return None
408
409                 # Add initial vertices so that we'll complete the edge on the first
410                 # iteration
411                 vertices = face.pivot_vertices(*edge.vertices)
412                 if len(vertices)==3:
413                         result = [vertices[-1], vertices[0]]
414                 else:
415                         result = [vertices[-2], vertices[-1]]
416
417                 while 1:
418                         face.flag = True
419
420                         vertices = face.pivot_vertices(*result[-2:])
421                         k = len(result)%2
422
423                         # Quads need special handling because the winding of every other
424                         # triangle in the strip is reversed
425                         if len(vertices)==4 and not k:
426                                 result.append(vertices[3])
427                         result.append(vertices[2])
428                         if len(vertices)==4 and k:
429                                 result.append(vertices[3])
430
431                         if len(result)>=max_len:
432                                 break
433
434                         # Hop over the last edge
435                         edge = face.get_edge(*result[-2:])
436                         face = edge.other_face(face)
437                         if not face or face.flag:
438                                 break
439
440                 return result