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