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