]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/export_mesh.py
Add properties to export materials as texture array layers
[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                 winding_test = False
234                 for o, m in objs:
235                         if o.data.winding_test:
236                                 winding_test = True
237                         bmesh = o.to_mesh(context.scene, True, "PREVIEW")
238                         bmeshes.append(bmesh)
239                         me = Mesh(bmesh)
240                         me.transform(m)
241                         if not mesh:
242                                 mesh = me
243                         else:
244                                 mesh.splice(me)
245
246                 if progress:
247                         progress.set_task("Smoothing", 0.05, 0.35)
248                 if self.smoothing=="NONE":
249                         mesh.flatten_faces()
250                 mesh.split_smooth(progress)
251
252                 if self.smoothing!="BLENDER":
253                         mesh.compute_normals()
254
255                 if self.export_groups:
256                         mesh.sort_vertex_groups(self.max_groups)
257
258                         # Create a mapping from vertex group indices to bone indices
259                         first_obj = objs[0][0]
260                         group_index_map = dict((i, i) for i in range(len(first_obj.vertex_groups)))
261                         if first_obj.parent and first_obj.parent.type=="ARMATURE":
262                                 armature = first_obj.parent.data
263                                 bone_indices = dict((armature.bones[i].name, i) for i in range(len(armature.bones)))
264                                 for g in first_obj.vertex_groups:
265                                         if g.name in bone_indices:
266                                                 group_index_map[g.index] = bone_indices[g.name]
267
268                 if self.material_tex and mesh.materials:
269                         mesh.generate_material_uv()
270
271                 texunits = []
272                 force_unit0 = False
273                 if mesh.uv_layers and (self.export_uv!="NONE" or self.material_tex):
274                         # Figure out which UV layers to export
275                         if self.export_uv=="ALL":
276                                 texunits = range(len(mesh.uv_layers))
277                         elif self.material_tex:
278                                 # The material UV layer is always the last one
279                                 texunits = [len(mesh.uv_layers)-1]
280                                 force_unit0 = True
281                         else:
282                                 for i, u in enumerate(mesh.uv_layers):
283                                         if u.unit==0:
284                                                 texunits = [i]
285                                                 break
286                         texunits = [(i, mesh.uv_layers[i]) for i in texunits]
287                         texunits = [u for u in texunits if not u[1].hidden]
288
289                         if self.tbn_vecs:
290                                 # TBN coordinates must be generated before vertices are split by any other layer
291                                 uv_names = [u.name for i, u in texunits]
292                                 if self.tbn_uvtex in uv_names:
293                                         tbn_index = uv_names.index(self.tbn_uvtex)
294                                         unit = texunits[tbn_index]
295                                         del texunits[tbn_index]
296                                         texunits.insert(0, unit)
297
298                         for i, u in texunits:
299                                 if progress:
300                                         progress.set_task("Splitting UVs", 0.35+0.3*i/len(texunits), 0.35+0.3*(i+1)/len(texunits))
301                                 mesh.split_uv(i, progress)
302                                 if self.tbn_vecs and u.name==self.tbn_uvtex:
303                                         mesh.compute_uv()
304                                         mesh.compute_tbn(i)
305
306                         mesh.compute_uv()
307
308                 strips = []
309                 loose = mesh.faces
310                 if self.use_strips:
311                         if progress:
312                                 progress.set_task("Creating strips", 0.65, 0.95)
313                         strips, loose = self.stripify(mesh, progress)
314
315                 if progress:
316                         progress.set_task("Writing file", 0.95, 1.0)
317
318                 from .outfile import open_output
319                 out_file = open_output(out_file)
320
321                 fmt = ["NORMAL3"]
322                 if texunits:
323                         for i, u in texunits:
324                                 size = str(len(mesh.vertices[0].uvs[i]))
325                                 if u.unit==0 or force_unit0:
326                                         fmt.append("TEXCOORD"+size)
327                                 else:
328                                         fmt.append("TEXCOORD%s_%d"%(size, u.unit))
329                         if self.tbn_vecs:
330                                 fmt += ["TANGENT3", "BINORMAL3"]
331                 if self.export_groups:
332                         fmt.append("ATTRIB%d_5"%(self.max_groups*2))
333                 fmt.append("VERTEX3")
334                 out_file.begin("vertices", *fmt)
335                 normal = None
336                 uvs = {}
337                 tan = None
338                 bino = None
339                 group = None
340                 for v in mesh.vertices:
341                         if v.normal!=normal:
342                                 out_file.write("normal3", *v.normal)
343                                 normal = v.normal
344                         for i, u in texunits:
345                                 if v.uvs[i]!=uvs.get(i):
346                                         size = str(len(v.uvs[i]))
347                                         if u.unit==0 or force_unit0:
348                                                 out_file.write("texcoord"+size, *v.uvs[i])
349                                         else:
350                                                 out_file.write("multitexcoord"+size, u.unit, *v.uvs[i])
351                                         uvs[i] = v.uvs[i]
352                         if self.tbn_vecs:
353                                 if v.tan!=tan:
354                                         out_file.write("tangent3", *v.tan)
355                                         tan = v.tan
356                                 if v.bino!=bino:
357                                         out_file.write("binormal3", *v.bino)
358                                         bino = v.bino
359                         if self.export_groups:
360                                 group_attr = [(group_index_map[g.group], g.weight*v.group_weight_scale) for g in v.groups[:self.max_groups]]
361                                 while len(group_attr)<self.max_groups:
362                                         group_attr.append((0, 0.0))
363                                 group_attr = list(itertools.chain(*group_attr))
364                                 if group_attr!=group:
365                                         out_file.write("attrib%d"%len(group_attr), 5, *group_attr)
366                                         group = group_attr
367                         out_file.write("vertex3", *v.co)
368                 out_file.end()
369                 for s in strips:
370                         out_file.begin("batch", "TRIANGLE_STRIP")
371                         indices = []
372                         n = 0
373                         for v in s:
374                                 indices.append(v.index)
375                                 if len(indices)>=32:
376                                         out_file.write("indices", *indices)
377                                         indices = []
378                         if indices:
379                                 out_file.write("indices", *indices)
380                         out_file.end()
381
382                 if loose:
383                         out_file.begin("batch", "TRIANGLES")
384                         for f in loose:
385                                 for i in range(2, len(f.vertices)):
386                                         out_file.write("indices", f.vertices[0].index, f.vertices[i-1].index, f.vertices[i].index)
387                         out_file.end()
388
389                 if self.export_lines and mesh.lines:
390                         out_file.begin("batch", "LINES")
391                         for l in mesh.lines:
392                                 out_file.write("indices", l.vertices[0].index, l.vertices[1].index)
393                         out_file.end()
394
395                 if winding_test:
396                         out_file.write("winding", "COUNTERCLOCKWISE")
397
398                 if progress:
399                         progress.set_task("Done", 1.0, 1.0)
400
401                 for m in bmeshes:
402                         bpy.data.meshes.remove(m)
403
404                 return mesh