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