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