]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/export_mesh.py
Properly handle compound children with non-identity local matrix
[libs/gl.git] / blender / io_mspgl / export_mesh.py
1 import itertools
2 import bpy
3 import mathutils
4
5 class VertexCache:
6         def __init__(self, size):
7                 self.size = size
8                 self.slots = [-1]*self.size
9
10         def fetch(self, v):
11                 hit = v.index in self.slots
12                 if hit:
13                         self.slots.remove(v.index)
14                 self.slots.append(v.index)
15                 if not hit:
16                         del self.slots[0]
17                 return hit
18
19         def fetch_strip(self, strip):
20                 hits = 0
21                 for v in strip:
22                         if self.fetch(v):
23                                 hits += 1
24                 return hits
25
26         def test_strip(self, strip):
27                 hits = 0
28                 for i in range(len(strip)):
29                         if i>=self.size:
30                                 break
31                         if strip[i].index in self.slots[i:]:
32                                 hits += 1
33                 return hits
34
35
36 class MeshExporter:
37         def __init__(self):
38                 self.show_progress = True
39                 self.use_strips = True
40                 self.use_degen_tris = False
41                 self.max_strip_len = 1024
42                 self.optimize_cache = True
43                 self.cache_size = 64
44                 self.export_lines = False
45                 self.export_uv = "UNIT0"
46                 self.tbn_vecs = False
47                 self.tbn_uvtex = ""
48                 self.compound = False
49                 self.material_tex = False
50                 self.smoothing = "MSPGL"
51                 self.export_groups = False
52                 self.max_groups = 2
53
54         def stripify(self, mesh, progress=None):
55                 for f in mesh.faces:
56                         f.flag = False
57
58                 faces_done = 0
59                 strips = []
60                 loose = []
61
62                 cache = None
63                 if self.optimize_cache:
64                         cache = VertexCache(self.cache_size)
65
66                 island = []
67                 island_strips = []
68                 while 1:
69                         if not island:
70                                 # No current island; find any unused face to start from
71                                 queue = []
72                                 for f in mesh.faces:
73                                         if not f.flag:
74                                                 f.flag = True
75                                                 queue.append(f)
76                                                 break
77
78                                 if not queue:
79                                         break
80
81                                 # Find all faces connected to the first one
82                                 while queue:
83                                         face = queue.pop(0)
84                                         island.append(face)
85
86                                         for n in f.get_neighbors():
87                                                 if not n.flag:
88                                                         n.flag = True
89                                                         queue.append(n)
90
91                                 # Unflag the island for the next phase
92                                 for f in island:
93                                         f.flag = False
94
95                         # Find an unused face with as few unused neighbors as possible, but
96                         # at least one.  This heuristic gives a preference to faces in corners
97                         # or along borders of a non-closed island.
98                         best = 5
99                         face = None
100                         for f in island:
101                                 if f.flag:
102                                         continue
103
104                                 score = sum(not n.flag for n in f.get_neighbors())
105                                 if score>0 and score<best:
106                                         face = f
107                                         best = score
108
109                         if face:
110                                 # Create a strip starting from the face.  This will flag the faces.
111                                 strip = mesh.create_strip(face, self.max_strip_len)
112                                 if strip:
113                                         island_strips.append(strip)
114                                 else:
115                                         face.flag = True
116                         else:
117                                 # Couldn't find a candidate face for starting a strip, so we're
118                                 # done with this island
119                                 while island_strips:
120                                         best = 0
121                                         if cache:
122                                                 # Find the strip that benefits the most from the current
123                                                 # contents of the vertex cache
124                                                 best_hits = 0
125                                                 for i in range(len(island_strips)):
126                                                         hits = cache.test_strip(island_strips[i])
127                                                         if hits>best_hits:
128                                                                 best = i
129                                                                 best_hits = hits
130
131                                         strip = island_strips.pop(best)
132                                         strips.append(strip)
133
134                                         if cache:
135                                                 cache.fetch_strip(strip)
136
137                                 faces_done += len(island)
138                                 if progress:
139                                         progress.set_progress(float(faces_done)/len(mesh.faces))
140
141                                 # Collect any faces that weren't used in strips
142                                 loose += [f for f in island if not f.flag]
143                                 for f in island:
144                                         f.flag = True
145
146                                 island = []
147                                 island_strips = []
148
149                 if cache:
150                         cache = VertexCache(self.cache_size)
151                         total_hits = 0
152
153                 if self.use_degen_tris and strips:
154                         big_strip = []
155
156                         for s in strips:
157                                 if big_strip:
158                                         # Generate glue elements, ensuring that the next strip begins at
159                                         # an even position
160                                         glue = [big_strip[-1], s[0]]
161                                         if len(big_strip)%2:
162                                                 glue += [s[0]]
163
164                                         big_strip += glue
165                                         if cache:
166                                                 total_hits += cache.fetch_strip(glue)
167
168                                 big_strip += s
169                                 if cache:
170                                         total_hits += cache.fetch_strip(s)
171
172                         for f in loose:
173                                 # Add loose faces to the end.  This wastes space, using five
174                                 # elements per triangle and six elements per quad.
175                                 if len(big_strip)%2:
176                                         order = (-1, -2, 0, 1)
177                                 else:
178                                         order = (0, 1, -1, -2)
179                                 vertices = [f.vertices[i] for i in order[:len(f.vertices)]]
180
181                                 if big_strip:
182                                         glue = [big_strip[-1], vertices[0]]
183                                         big_strip += glue
184                                         if cache:
185                                                 total_hits += cache.fetch_strip(glue)
186
187                                 big_strip += vertices
188                                 if cache:
189                                         total_hits += cache.fetch_strip(vertices)
190
191                         strips = [big_strip]
192                         loose = []
193
194                 return strips, loose
195
196         def export(self, context, out_file, objs=None, progress=None):
197                 if objs:
198                         objs = [(o, mathutils.Matrix()) for i in objs]
199
200                 if self.compound:
201                         if objs is None:
202                                 objs = [(o, mathutils.Matrix()) for o in context.selected_objects]
203                         check = objs
204                         while check:
205                                 children = []
206                                 for o, m in check:
207                                         for c in o.children:
208                                                 if c.compound:
209                                                         children.append((c, m*c.matrix_local))
210                                 objs += children
211                                 check = children
212                 elif objs is None:
213                         objs = [(context.active_object, mathutils.Matrix())]
214
215                 if not objs:
216                         raise Exception("Nothing to export")
217                 for o, m in objs:
218                         if o.type!="MESH":
219                                 raise Exception("Can only export Mesh data")
220
221                 from .mesh import Mesh
222                 from .util import Progress
223
224                 if self.show_progress:
225                         if not progress:
226                                 progress = Progress(context)
227                         progress.set_task("Preparing", 0.0, 0.0)
228                 else:
229                         progress = None
230
231                 mesh = None
232                 bmeshes = []
233                 for o, m in objs:
234                         bmesh = o.to_mesh(context.scene, True, "PREVIEW")
235                         bmeshes.append(bmesh)
236                         me = Mesh(bmesh)
237                         me.transform(m)
238                         if not mesh:
239                                 mesh = me
240                         else:
241                                 mesh.splice(me)
242
243                 if progress:
244                         progress.set_task("Smoothing", 0.05, 0.35)
245                 if self.smoothing=="NONE":
246                         mesh.flatten_faces()
247                 mesh.split_smooth(progress)
248
249                 if self.smoothing!="BLENDER":
250                         mesh.compute_normals()
251
252                 if self.export_groups:
253                         mesh.sort_vertex_groups(self.max_groups)
254
255                         # Create a mapping from vertex group indices to bone indices
256                         first_obj = objs[0][0]
257                         group_index_map = dict((i, i) for i in range(len(first_obj.vertex_groups)))
258                         if first_obj.parent and first_obj.parent.type=="ARMATURE":
259                                 armature = first_obj.parent.data
260                                 bone_indices = dict((armature.bones[i].name, i) for i in range(len(armature.bones)))
261                                 for g in first_obj.vertex_groups:
262                                         if g.name in bone_indices:
263                                                 group_index_map[g.index] = bone_indices[g.name]
264
265                 if self.material_tex and mesh.materials:
266                         mesh.generate_material_uv()
267
268                 texunits = []
269                 force_unit0 = False
270                 if mesh.uv_layers and (self.export_uv!="NONE" or self.material_tex):
271                         # Figure out which UV layers to export
272                         if self.export_uv=="ALL":
273                                 texunits = range(len(mesh.uv_layers))
274                         elif self.material_tex:
275                                 # The material UV layer is always the last one
276                                 texunits = [len(mesh.uv_layers)-1]
277                                 force_unit0 = True
278                         else:
279                                 for i, u in enumerate(mesh.uv_layers):
280                                         if u.unit==0:
281                                                 texunits = [i]
282                                                 break
283                         texunits = [(i, mesh.uv_layers[i]) for i in texunits]
284                         texunits = [u for u in texunits if not u[1].hidden]
285
286                         if self.tbn_vecs:
287                                 # TBN coordinates must be generated before vertices are split by any other layer
288                                 uv_names = [u.name for i, u in texunits]
289                                 if self.tbn_uvtex in uv_names:
290                                         tbn_index = uv_names.index(self.tbn_uvtex)
291                                         unit = texunits[tbn_index]
292                                         del texunits[tbn_index]
293                                         texunits.insert(0, unit)
294
295                         for i, u in texunits:
296                                 if progress:
297                                         progress.set_task("Splitting UVs", 0.35+0.3*i/len(texunits), 0.35+0.3*(i+1)/len(texunits))
298                                 mesh.split_uv(i, progress)
299                                 if self.tbn_vecs and u.name==self.tbn_uvtex:
300                                         mesh.compute_uv()
301                                         mesh.compute_tbn(i)
302
303                         mesh.compute_uv()
304
305                 strips = []
306                 loose = mesh.faces
307                 if self.use_strips:
308                         if progress:
309                                 progress.set_task("Creating strips", 0.65, 0.95)
310                         strips, loose = self.stripify(mesh, progress)
311
312                 if progress:
313                         progress.set_task("Writing file", 0.95, 1.0)
314
315                 from .outfile import open_output
316                 out_file = open_output(out_file)
317
318                 fmt = ["NORMAL3"]
319                 if texunits:
320                         for i, u in texunits:
321                                 if u.unit==0 or force_unit0:
322                                         fmt.append("TEXCOORD2")
323                                 else:
324                                         fmt.append("TEXCOORD2_%d"%u.unit)
325                         if self.tbn_vecs:
326                                 fmt += ["TANGENT3", "BINORMAL3"]
327                 if self.export_groups:
328                         fmt.append("ATTRIB%d_5"%(self.max_groups*2))
329                 fmt.append("VERTEX3")
330                 out_file.begin("vertices", *fmt)
331                 normal = None
332                 uvs = {}
333                 tan = None
334                 bino = None
335                 group = None
336                 for v in mesh.vertices:
337                         if v.normal!=normal:
338                                 out_file.write("normal3", *v.normal)
339                                 normal = v.normal
340                         for i, u in texunits:
341                                 if v.uvs[i]!=uvs.get(i):
342                                         if u.unit==0 or force_unit0:
343                                                 out_file.write("texcoord2", *v.uvs[i])
344                                         else:
345                                                 out_file.write("multitexcoord2", u.unit, *v.uvs[i])
346                                         uvs[i] = v.uvs[i]
347                         if self.tbn_vecs:
348                                 if v.tan!=tan:
349                                         out_file.write("tangent3", *v.tan)
350                                         tan = v.tan
351                                 if v.bino!=bino:
352                                         out_file.write("binormal3", *v.bino)
353                                         bino = v.bino
354                         if self.export_groups:
355                                 group_attr = [(group_index_map[g.group], g.weight*v.group_weight_scale) for g in v.groups[:self.max_groups]]
356                                 while len(group_attr)<self.max_groups:
357                                         group_attr.append((0, 0.0))
358                                 group_attr = list(itertools.chain(*group_attr))
359                                 if group_attr!=group:
360                                         out_file.write("attrib%d"%len(group_attr), 5, *group_attr)
361                                         group = group_attr
362                         out_file.write("vertex3", *v.co)
363                 out_file.end()
364                 for s in strips:
365                         out_file.begin("batch", "TRIANGLE_STRIP")
366                         indices = []
367                         n = 0
368                         for v in s:
369                                 indices.append(v.index)
370                                 if len(indices)>=32:
371                                         out_file.write("indices", *indices)
372                                         indices = []
373                         if indices:
374                                 out_file.write("indices", *indices)
375                         out_file.end()
376
377                 if loose:
378                         out_file.begin("batch", "TRIANGLES")
379                         for f in loose:
380                                 for i in range(2, len(f.vertices)):
381                                         out_file.write("indices", f.vertices[0].index, f.vertices[i-1].index, f.vertices[i].index)
382                         out_file.end()
383
384                 if self.export_lines and mesh.lines:
385                         out_file.begin("batch", "LINES")
386                         for l in mesh.lines:
387                                 out_file.write("indices", l.vertices[0].index, l.vertices[1].index)
388                         out_file.end()
389
390                 if progress:
391                         progress.set_task("Done", 1.0, 1.0)
392
393                 for m in bmeshes:
394                         bpy.data.meshes.remove(m)
395
396                 return mesh