5 Name: 'MSP GL Mesh (.mesh)...'
15 def make_edge_key(i1, i2):
16 return (min(i1, i2), max(i1, i2))
20 def __init__(self, me):
21 if me.__class__==Edge:
22 self._medge = me._medge
25 self.smooth = me.smooth
31 def __getattr__(self, attr):
32 return getattr(self._medge, attr)
34 def check_smooth(self, limit):
35 if len(self.faces)!=2:
38 d = Blender.Mathutils.DotVecs(self.faces[0].no, self.faces[1].no)
39 if (d>limit and self.faces[0].smooth and self.faces[1].smooth) or d>0.999:
42 def other_face(self, f):
43 if f.index==self.faces[0].index:
44 if len(self.faces)>=2:
53 def __init__(self, mv):
54 if mv.__class__==Vertex:
55 self._mvert = mv._mvert
66 def __getattr__(self, attr):
67 return getattr(self._mvert, attr)
69 def __cmp__(self, other):
72 return cmp(self.index, other.index)
75 return "<Vert %d (%.4f, %.4f, %.4f) (%.4f, %.4f, %.4f)>"%(self.index, self.co[0], self.co[1], self.co[2], self.no[0], self.no[1], self.no[2])
81 def __init__(self, mf):
84 self.verts = [v for v in mf.verts]
87 def __getattr__(self, attr):
88 return getattr(self._mface, attr)
90 def __cmp__(self, other):
93 return cmp(self.index, other.index)
96 return "<Face %d (%s)>"%(self.index, " ".join([str(v.index) for v in self.verts]))
100 def pivot_vertices(self, *vt):
101 flags = [(v in vt) for v in self.verts]
104 if flags[i] and not flags[(i+l-1)%l]:
105 return self.verts[i:]+self.verts[:i]
107 def get_edge(self, v1, v2):
108 key = make_edge_key(v1.index, v2.index)
112 raise KeyError, "No edge %s"%(key,)
116 def __init__(self, e):
118 self.verts = [e.v1, e.v2]
122 return "<Line (%d %d)>"%(self.verts[0].index, self.verts[1].index)
128 def __init__(self, m):
130 self.verts = [Vertex(v) for v in m.verts]
131 self.faces = [Face(f) for f in m.faces]
134 for i in range(len(f.verts)):
135 f.verts[i] = self.verts[f.verts[i].index]
136 f.verts[i].faces.append(f)
138 self.edges = dict([(e.key, Edge(e)) for e in m.edges])
140 for k in f.edge_keys:
142 e.faces.append(self.faces[f.index])
145 self.lines = [Line(e) for e in self.edges.itervalues() if not e.faces]
147 if m.mode&Blender.Mesh.Modes.AUTOSMOOTH:
148 smooth_limit = math.cos(m.degr*math.pi/180)
152 for e in self.edges.itervalues():
153 e.v1 = self.verts[e.v1.index]
154 e.v2 = self.verts[e.v2.index]
155 e.check_smooth(smooth_limit)
157 def __getattr__(self, attr):
158 return getattr(self._mesh, attr)
160 def splice(self, other):
161 offset = len(self.verts)
162 for v in other.verts:
166 offset = len(self.faces)
167 for f in other.faces:
171 for e in other.edges.itervalues():
172 e.key = make_edge_key(e.v1.index, e.v2.index)
173 self.edges[e.key] = e
175 self.lines += other.lines
177 def split_vertices(self, find_group_func, debug):
186 vg.append(find_group_func(v, f))
190 for i in range(len(self.verts)):
191 if len(groups[i])==1:
195 print "Vertex %s has %d groups"%(self.verts[i], len(groups[i]))
197 for g in groups[i][1:]:
198 v = Vertex(self.verts[i])
199 v.index = len(self.verts)
203 print " -> %d %s"%(v.index, [f.index for f in g])
206 for j in range(len(f.edges)):
209 if e.v1!=self.verts[i] and e.v2!=self.verts[i]:
213 print " Splitting edge %s with faces %s"%(e.key, e.faces)
215 if e.other_face(f) not in g and len(e.faces)>=2:
222 del self.edges[e.key]
224 if e.v1==self.verts[i]:
226 elif e.v2==self.verts[i]:
229 e.key = make_edge_key(e.v1.index, e.v2.index)
230 self.edges[e.key] = e
232 self.verts[i].faces.remove(f)
233 f.verts[f.verts.index(self.verts[i])] = v
236 def split_smooth(self, debug = False):
237 self.split_vertices(self.find_smooth_group, debug)
239 def split_uv(self, debug = False):
240 self.split_vertices(self.find_uv_group, debug)
242 def find_smooth_group(self, vert, face):
248 other = e.other_face(f)
249 #if not other or other.index not in face_indices:
250 if other not in vert.faces:
260 def find_uv_group(self, vert, face):
261 uv = face.uv[face.verts.index(vert)]
265 if not f.flag and f.uv[f.verts.index(vert)]==uv:
270 def compute_normals(self):
273 v.no = Blender.Mathutils.Vector()
278 # XXX Should use edges to compute normal
279 v.no = Blender.Mathutils.Vector(0, 0, 1)
281 def compute_uv(self):
284 v.uv = v.faces[0].uv[v.faces[0].verts.index(v)]
286 def compute_tbn(self):
288 v.tan = Blender.Mathutils.Vector()
289 v.bino = Blender.Mathutils.Vector()
291 fverts = f.pivot_vertices(False, v)
294 du1 = v1.uv[0]-v.uv[0]
295 du2 = v2.uv[0]-v.uv[0]
296 dv1 = v1.uv[1]-v.uv[1]
297 dv2 = v2.uv[1]-v.uv[1]
298 div = du1*dv2-du2*dv1
299 edge1 = fverts[1].co-fverts[0].co
300 edge2 = fverts[-1].co-fverts[0].co
301 v.tan += (edge1*dv2-edge2*dv1)/div
302 v.bino += (edge2*du1-edge1*du2)/div
306 def create_strip(self, face, max_len, debug):
309 other = e.other_face(face)
310 if other and not other.flag:
318 print "Starting strip from %s, edge %s"%([v.index for v in face.verts], (edge.v1.index, edge.v2.index))
320 verts = face.pivot_vertices(edge.v1, edge.v2)
322 result = [verts[-1], verts[0]]
324 result = [verts[-2], verts[-1]]
328 print " Adding %s"%face
330 verts = face.pivot_vertices(*result[-2:])
334 if len(verts)==4 and not k:
335 result.append(verts[3])
336 result.append(verts[2])
337 if len(verts)==4 and k:
338 result.append(verts[3])
340 if len(result)>=max_len:
342 print " Max length exceeded"
345 edge = face.get_edge(*result[-2:])
348 print " Next edge is %s"%(edge.key, )
350 next = edge.other_face(face)
351 if not next or next.flag:
356 print " %s"%[v.index for v in result]
362 def __init__(self, size):
364 self.slots = [-1]*self.size
367 hit = v.index in self.slots
369 self.slots.remove(v.index)
370 self.slots.append(v.index)
375 def fetch_strip(self, strip):
382 def test_strip(self, strip):
384 for i in range(len(strip)):
387 if strip[i].index in self.slots[i:]:
393 def __init__(self, fn):
396 self.out_file = sys.stdout
398 self.out_file = file(fn, "w")
399 self.use_strips = True
400 self.use_degen_tris = True
401 self.max_strip_len = 1024
402 self.optimize_cache = False
404 self.export_lines = True
405 self.tbn_vecs = False
406 self.compound = False
408 self.strip_debug = False
409 self.split_debug = False
411 def stripify(self, mesh):
425 other = e.other_face(f)
426 if other and not other.flag:
428 if score>0 and score<best:
435 strip = mesh.create_strip(face, self.max_strip_len, self.strip_debug)
439 loose = [f for f in mesh.faces if not f.flag]
442 print "%d strips:"%len(strips)
443 for i in range(len(strips)):
444 print " %d: %d indices"%(i, len(strips[i]))
445 print "%d loose faces"%len([f for f in mesh.faces if not f.flag])
446 nind = sum([len(s) for s in strips])+sum([len(f.verts) for f in loose])
447 print "%d indices total"%nind
449 if self.use_degen_tris and strips:
454 if self.optimize_cache:
455 cache = VertexCache(self.cache_size)
461 for i in range(len(strips)):
462 hits = cache.test_strip(strips[i])
470 glue = [big_strip[-1], s[0]]
476 total_hits += cache.fetch_strip(glue)
480 total_hits += cache.fetch_strip(s)
486 order = (-1, -2, 0, 1)
488 order = (0, 1, -1, -2)
489 verts = [f.verts[i] for i in order[:len(f.verts)]]
491 glue = [big_strip[-1], verts[0]]
494 total_hits += cache.fetch_strip(glue)
497 total_hits += cache.fetch_strip(verts)
503 nind = len(big_strip)
504 print "Big strip has %d indices"%nind
505 if self.optimize_cache:
506 print "%d cache hits"%total_hits
509 ntris = sum([len(f.verts)-2 for f in mesh.faces])
510 print "%.2f indices per triangle"%(float(nind)/max(ntris, 1))
515 scene = bpy.data.scenes.active
517 objs = Blender.Object.GetSelected()
519 raise Exception, "Nothing to export"
521 if o.getType()!="Mesh":
522 raise Exception, "Can only export Mesh data"
524 mesh = Blender.Mesh.New("export_tmp")
525 mesh.getFromObject(objs[0])
530 bmesh = Blender.Mesh.New("export_tmp")
531 bmesh.getFromObject(o)
532 bmeshes.append(bmesh)
533 mesh.splice(Mesh(bmesh))
536 ntris = sum([len(f.verts)-2 for f in mesh.faces])
537 print "Starting with %d vertices, %d faces (%d triangles) and %d edges"%(len(mesh.verts), len(mesh.faces), ntris, len(mesh.edges))
539 mesh.split_smooth(self.split_debug)
542 print "After smooth splitting %d vertices and %d edges"%(len(mesh.verts), len(mesh.edges))
544 mesh.compute_normals()
547 mesh.split_uv(self.split_debug)
549 print "After UV splitting %d vertices and %d edges"%(len(mesh.verts), len(mesh.edges))
558 strips, loose = self.stripify(mesh)
560 self.out_file.write("vertices NORMAL3")
562 self.out_file.write("_TEXCOORD2")
564 self.out_file.write("_ATTRIB33_ATTRIB34")
565 self.out_file.write("_VERTEX3\n{\n")
572 self.out_file.write("\tnormal3 %f %f %f;\n"%tuple(v.no))
575 self.out_file.write("\ttexcoord2 %f %f;\n"%tuple(v.uv))
578 self.out_file.write("\tattrib3 3 %f %f %f;\n"%tuple(v.tan))
581 self.out_file.write("\tattrib3 4 %f %f %f;\n"%tuple(v.bino))
583 self.out_file.write("\tvertex3 %f %f %f;\n"%tuple(v.co))
584 self.out_file.write("};\n")
586 self.out_file.write("batch TRIANGLE_STRIP\n{\n\tindices")
589 self.out_file.write(" %u"%v.index)
592 self.out_file.write(";\n\tindices")
593 self.out_file.write(";\n};\n")
598 self.out_file.write("batch TRIANGLES\n{\n")
600 for i in range(2, len(f.verts)):
601 self.out_file.write("\tindices %u %u %u;\n"%(f.verts[0].index, f.verts[i-1].index, f.verts[i].index))
603 self.out_file.write("};\n")
605 if self.export_lines and mesh.lines:
606 self.out_file.write("batch LINES\n{\n")
608 self.out_file.write("\tindices %u %u;\n"%(l.verts[0].index, l.verts[1].index))
609 self.out_file.write("};\n")
614 self.config = Blender.Registry.GetKey('mspgl_export', True) or {}
615 self.temp_config = Blender.Registry.GetKey('mspgl_export_temp') or {}
618 self.use_strips = Blender.Draw.Create(self.config.get('use_strips', True))
619 self.use_degen_tris = Blender.Draw.Create(self.config.get('use_degen_tris', True))
620 self.max_strip_len = Blender.Draw.Create(self.config.get('max_strip_len', 1024))
621 self.optimize_cache = Blender.Draw.Create(self.config.get('optimize_cache', False))
622 self.cache_size = Blender.Draw.Create(self.config.get('cache_size', 64))
623 self.export_lines = Blender.Draw.Create(self.config.get('export_lines', False))
624 self.tbn_vecs = Blender.Draw.Create(self.config.get('tbn_vecs', False))
625 self.compound = Blender.Draw.Create(self.config.get('compound', False))
626 self.debug = Blender.Draw.Create(self.config.get('debug', False))
627 self.strip_debug = Blender.Draw.Create(self.config.get('strip_debug', False))
628 self.split_debug = Blender.Draw.Create(self.config.get('split_debug', False))
629 ret = Blender.Draw.PupBlock("Export MSP GL mesh",
630 [("Use strips", self.use_strips, "Generage OpenGL triangle strips"),
631 ("Use degen tris", self.use_degen_tris, "Use degenerate triangles to combine triangle strips"),
632 ("Max strip len", self.max_strip_len, 4, 16384, "Maximum length of a triangle strip"),
633 ("Optimize cache", self.optimize_cache, "Optimize for vertex cache"),
634 ("Cache size", self.cache_size, 8, 1024, "Cache size to optimize for"),
635 ("Export lines", self.export_lines, "Export lone edges as lines"),
636 ("Compute T/B vecs", self.tbn_vecs, "Compute tangent/binormal vectors for bumpmapping"),
637 ("Compound", self.compound, "Create a compound mesh of all selected objects"),
638 ("Debugging options"),
639 ("Debug", self.debug),
640 ("Debug strips", self.strip_debug),
641 ("Debug splitting", self.split_debug)])
643 dirname = self.temp_config.get("dirname", Blender.sys.dirname(Blender.Get("filename")))
644 obj = Blender.Object.GetSelected()[0]
645 Blender.Window.FileSelector(self.export, "Export MSP GL mesh", "%s/%s.mesh"%(dirname, obj.name))
650 def export(self, fn):
651 self.config['use_strips'] = self.use_strips.val
652 self.config['use_degen_tris'] = self.use_degen_tris.val
653 self.config['max_strip_len'] = self.max_strip_len.val
654 self.config['optimize_cache'] = self.optimize_cache.val
655 self.config['cache_size'] = self.cache_size.val
656 self.config['export_lines'] = self.export_lines.val
657 self.config['tbn_vecs'] = self.tbn_vecs.val
658 self.config['compound'] = self.compound.val
659 self.config['debug'] = self.debug.val
660 self.config['strip_debug'] = self.strip_debug.val
661 self.config['split_debug'] = self.split_debug.val
662 Blender.Registry.SetKey('mspgl_export', self.config, True)
665 self.temp_config["dirname"] = os.path.dirname(fn)
666 Blender.Registry.SetKey('mspgl_export_temp', self.temp_config)
669 exp.use_strips = self.use_strips.val
670 exp.use_degen_tris = self.use_degen_tris.val
671 exp.max_strip_len = self.max_strip_len.val
672 exp.optimize_cache = self.optimize_cache.val
673 exp.cache_size = self.cache_size.val
674 exp.export_lines = self.export_lines.val
675 exp.tbn_vecs = self.tbn_vecs.val
676 exp.compound = self.compound.val
677 exp.debug = self.debug.val
678 exp.strip_debug = self.strip_debug.val
679 exp.split_debug = self.split_debug.val
683 if __name__=="__main__":