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