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