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