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]
132 self.materials = m.materials[:]
135 for i in range(len(f.verts)):
136 f.verts[i] = self.verts[f.verts[i].index]
137 f.verts[i].faces.append(f)
139 self.edges = dict([(e.key, Edge(e)) for e in m.edges])
141 for k in f.edge_keys:
143 e.faces.append(self.faces[f.index])
146 self.lines = [Line(e) for e in self.edges.itervalues() if not e.faces]
148 if m.mode&Blender.Mesh.Modes.AUTOSMOOTH:
149 smooth_limit = math.cos(m.degr*math.pi/180)
153 for e in self.edges.itervalues():
154 e.v1 = self.verts[e.v1.index]
155 e.v2 = self.verts[e.v2.index]
156 e.check_smooth(smooth_limit)
158 def __getattr__(self, attr):
159 return getattr(self._mesh, attr)
161 def splice(self, other):
163 for m in other.materials:
164 if m in self.materials:
165 material_map.append(self.materials.index(m))
167 material_map.append(len(self.materials))
168 self.materials.append(m)
170 offset = len(self.verts)
171 for v in other.verts:
175 offset = len(self.faces)
176 for f in other.faces:
178 f.mat = material_map[f.mat]
181 for e in other.edges.itervalues():
182 e.key = make_edge_key(e.v1.index, e.v2.index)
183 self.edges[e.key] = e
185 self.lines += other.lines
187 def generate_material_uv(self):
189 f.uv = ([(f.mat+0.5)/len(self.materials), 0.5],)*len(f.verts)
192 def split_vertices(self, find_group_func, debug):
201 vg.append(find_group_func(v, f))
205 for i in range(len(self.verts)):
206 if len(groups[i])==1:
210 print "Vertex %s has %d groups"%(self.verts[i], len(groups[i]))
212 for g in groups[i][1:]:
213 v = Vertex(self.verts[i])
214 v.index = len(self.verts)
218 print " -> %d %s"%(v.index, [f.index for f in g])
221 for j in range(len(f.edges)):
224 if e.v1!=self.verts[i] and e.v2!=self.verts[i]:
228 print " Splitting edge %s with faces %s"%(e.key, e.faces)
230 if e.other_face(f) not in g and len(e.faces)>=2:
237 del self.edges[e.key]
239 if e.v1==self.verts[i]:
241 elif e.v2==self.verts[i]:
244 e.key = make_edge_key(e.v1.index, e.v2.index)
245 self.edges[e.key] = e
247 self.verts[i].faces.remove(f)
248 f.verts[f.verts.index(self.verts[i])] = v
251 def split_smooth(self, debug = False):
252 self.split_vertices(self.find_smooth_group, debug)
254 def split_uv(self, debug = False):
255 self.split_vertices(self.find_uv_group, debug)
257 def find_smooth_group(self, vert, face):
263 other = e.other_face(f)
264 #if not other or other.index not in face_indices:
265 if other not in vert.faces:
275 def find_uv_group(self, vert, face):
276 uv = face.uv[face.verts.index(vert)]
280 if not f.flag and f.uv[f.verts.index(vert)]==uv:
285 def compute_normals(self):
288 v.no = Blender.Mathutils.Vector()
293 # XXX Should use edges to compute normal
294 v.no = Blender.Mathutils.Vector(0, 0, 1)
296 def compute_uv(self):
299 v.uv = v.faces[0].uv[v.faces[0].verts.index(v)]
301 def compute_tbn(self):
303 v.tan = Blender.Mathutils.Vector()
304 v.bino = Blender.Mathutils.Vector()
306 fverts = f.pivot_vertices(False, v)
309 du1 = v1.uv[0]-v.uv[0]
310 du2 = v2.uv[0]-v.uv[0]
311 dv1 = v1.uv[1]-v.uv[1]
312 dv2 = v2.uv[1]-v.uv[1]
313 div = du1*dv2-du2*dv1
314 edge1 = fverts[1].co-fverts[0].co
315 edge2 = fverts[-1].co-fverts[0].co
316 v.tan += (edge1*dv2-edge2*dv1)/div
317 v.bino += (edge2*du1-edge1*du2)/div
321 def create_strip(self, face, max_len, debug):
324 other = e.other_face(face)
325 if other and not other.flag:
333 print "Starting strip from %s, edge %s"%([v.index for v in face.verts], (edge.v1.index, edge.v2.index))
335 verts = face.pivot_vertices(edge.v1, edge.v2)
337 result = [verts[-1], verts[0]]
339 result = [verts[-2], verts[-1]]
343 print " Adding %s"%face
345 verts = face.pivot_vertices(*result[-2:])
349 if len(verts)==4 and not k:
350 result.append(verts[3])
351 result.append(verts[2])
352 if len(verts)==4 and k:
353 result.append(verts[3])
355 if len(result)>=max_len:
357 print " Max length exceeded"
360 edge = face.get_edge(*result[-2:])
363 print " Next edge is %s"%(edge.key, )
365 next = edge.other_face(face)
366 if not next or next.flag:
371 print " %s"%[v.index for v in result]
377 def __init__(self, size):
379 self.slots = [-1]*self.size
382 hit = v.index in self.slots
384 self.slots.remove(v.index)
385 self.slots.append(v.index)
390 def fetch_strip(self, strip):
397 def test_strip(self, strip):
399 for i in range(len(strip)):
402 if strip[i].index in self.slots[i:]:
408 def __init__(self, fn):
410 self.file = sys.stdout
412 self.file = open(fn, "w")
415 def make(self, kwd, *params):
422 return "%s%s"%(kwd, pstr)
424 def write(self, kwd, *params):
425 self.file.write("%s%s;\n"%('\t'*self.indent, self.make(kwd, *params)))
427 def begin(self, kwd, *params):
429 self.file.write("%s%s\n%s{\n"%(i, self.make(kwd, *params), i))
434 self.file.write("%s};\n"%('\t'*self.indent))
438 def __init__(self, fn):
439 self.out_file = OutFile(fn)
440 self.use_strips = True
441 self.use_degen_tris = True
442 self.max_strip_len = 1024
443 self.optimize_cache = False
445 self.export_lines = True
446 self.tbn_vecs = False
447 self.compound = False
449 self.material_tex = False
451 self.strip_debug = False
452 self.split_debug = False
454 def stripify(self, mesh):
468 other = e.other_face(f)
469 if other and not other.flag:
471 if score>0 and score<best:
478 strip = mesh.create_strip(face, self.max_strip_len, self.strip_debug)
482 loose = [f for f in mesh.faces if not f.flag]
485 print "%d strips:"%len(strips)
486 for i in range(len(strips)):
487 print " %d: %d indices"%(i, len(strips[i]))
488 print "%d loose faces"%len([f for f in mesh.faces if not f.flag])
489 nind = sum([len(s) for s in strips])+sum([len(f.verts) for f in loose])
490 print "%d indices total"%nind
492 if self.use_degen_tris and strips:
497 if self.optimize_cache:
498 cache = VertexCache(self.cache_size)
504 for i in range(len(strips)):
505 hits = cache.test_strip(strips[i])
513 glue = [big_strip[-1], s[0]]
519 total_hits += cache.fetch_strip(glue)
523 total_hits += cache.fetch_strip(s)
529 order = (-1, -2, 0, 1)
531 order = (0, 1, -1, -2)
532 verts = [f.verts[i] for i in order[:len(f.verts)]]
534 glue = [big_strip[-1], verts[0]]
537 total_hits += cache.fetch_strip(glue)
540 total_hits += cache.fetch_strip(verts)
546 nind = len(big_strip)
547 print "Big strip has %d indices"%nind
548 if self.optimize_cache:
549 print "%d cache hits"%total_hits
552 ntris = sum([len(f.verts)-2 for f in mesh.faces])
553 print "%.2f indices per triangle"%(float(nind)/max(ntris, 1))
558 scene = bpy.data.scenes.active
560 objs = Blender.Object.GetSelected()
562 raise Exception, "Nothing to export"
564 if o.getType()!="Mesh":
565 raise Exception, "Can only export Mesh data"
567 mesh = Blender.Mesh.New("export_tmp")
568 mesh.getFromObject(objs[0])
571 # Must keep a ref to each Blender mesh
574 bmesh = Blender.Mesh.New("export_tmp")
575 bmesh.getFromObject(o)
576 bmeshes.append(bmesh)
577 mesh.splice(Mesh(bmesh))
580 ntris = sum([len(f.verts)-2 for f in mesh.faces])
581 print "Starting with %d vertices, %d faces (%d triangles) and %d edges"%(len(mesh.verts), len(mesh.faces), ntris, len(mesh.edges))
583 mesh.split_smooth(self.split_debug)
586 print "After smooth splitting %d vertices and %d edges"%(len(mesh.verts), len(mesh.edges))
588 mesh.compute_normals()
590 if self.material_tex:
591 mesh.generate_material_uv()
594 mesh.split_uv(self.split_debug)
596 print "After UV splitting %d vertices and %d edges"%(len(mesh.verts), len(mesh.edges))
605 strips, loose = self.stripify(mesh)
608 self.out_file.begin("mesh")
614 fmt += "_ATTRIB33_ATTRIB34"
616 self.out_file.begin("vertices", fmt)
623 self.out_file.write("normal3", *v.no)
626 self.out_file.write("texcoord2", *v.uv)
629 self.out_file.write("attrib3", 3, *v.tan)
632 self.out_file.write("attrib3", 4, *v.bino)
634 self.out_file.write("vertex3", *v.co)
637 self.out_file.begin("batch", "TRIANGLE_STRIP")
641 indices.append(v.index)
643 self.out_file.write("indices", *indices)
646 self.out_file.write("indices", *indices)
650 self.out_file.begin("batch", "TRIANGLES")
652 for i in range(2, len(f.verts)):
653 self.out_file.write("indices", f.verts[0].index, f.verts[i-1].index, f.verts[i].index)
656 if self.export_lines and mesh.lines:
657 self.out_file.write("batch", "LINES")
659 self.out_file.write("indices", l.verts[0].index, l.verts[1].index)
664 self.out_file.begin("technique")
665 self.out_file.begin("pass", '""')
666 if self.material_tex:
667 self.out_file.begin("material")
668 self.out_file.write("diffuse", 1.0, 1.0, 1.0, 1.0)
670 self.out_file.begin("texunit", 0)
671 self.out_file.begin("texture2d")
672 self.out_file.write("min_filter", "NEAREST")
673 self.out_file.write("mag_filter", "NEAREST")
674 self.out_file.write("storage", "RGB", len(mesh.materials), 1, 0)
676 for m in mesh.materials:
677 texdata += "\\x%02X\\x%02X\\x%02X"%(int(m.R*255), int(m.G*255), int(m.B*255))
679 self.out_file.write("raw_data", texdata)
683 m = mesh.materials[0]
684 self.out_file.begin("material")
685 self.out_file.write("diffuse", m.R, m.G, m.B, 1.0)
686 self.out_file.write("ambient", m.R*m.amb, m.G*m.amb, m.B*m.amb, 1.0)
687 self.out_file.write("specular", m.specR*m.spec, m.specG*m.spec, m.specB*m.spec, 1.0)
688 self.out_file.write("shininess", m.hard);
696 self.config = Blender.Registry.GetKey('mspgl_export', True) or {}
697 self.temp_config = Blender.Registry.GetKey('mspgl_export_temp') or {}
700 self.use_strips = Blender.Draw.Create(self.config.get('use_strips', True))
701 self.use_degen_tris = Blender.Draw.Create(self.config.get('use_degen_tris', True))
702 self.max_strip_len = Blender.Draw.Create(self.config.get('max_strip_len', 1024))
703 self.optimize_cache = Blender.Draw.Create(self.config.get('optimize_cache', False))
704 self.cache_size = Blender.Draw.Create(self.config.get('cache_size', 64))
705 self.export_lines = Blender.Draw.Create(self.config.get('export_lines', False))
706 self.tbn_vecs = Blender.Draw.Create(self.config.get('tbn_vecs', False))
707 self.compound = Blender.Draw.Create(self.config.get('compound', False))
708 self.object = Blender.Draw.Create(self.config.get('object', False))
709 self.material_tex = Blender.Draw.Create(self.config.get('material_tex', False))
710 self.debug = Blender.Draw.Create(self.config.get('debug', False))
711 self.strip_debug = Blender.Draw.Create(self.config.get('strip_debug', False))
712 self.split_debug = Blender.Draw.Create(self.config.get('split_debug', False))
713 ret = Blender.Draw.PupBlock("Export MSP GL mesh",
714 [("Use strips", self.use_strips, "Generage OpenGL triangle strips"),
715 ("Use degen tris", self.use_degen_tris, "Use degenerate triangles to combine triangle strips"),
716 ("Max strip len", self.max_strip_len, 4, 16384, "Maximum length of a triangle strip"),
717 ("Optimize cache", self.optimize_cache, "Optimize for vertex cache"),
718 ("Cache size", self.cache_size, 8, 1024, "Cache size to optimize for"),
719 ("Export lines", self.export_lines, "Export lone edges as lines"),
720 ("Compute T/B vecs", self.tbn_vecs, "Compute tangent/binormal vectors for bumpmapping"),
721 ("Compound", self.compound, "Create a compound mesh of all selected objects"),
722 ("Object", self.object, "Export as an object"),
723 ("Material texture", self.material_tex, "Create a texture from material data"),
724 ("Debugging options"),
725 ("Debug", self.debug),
726 ("Debug strips", self.strip_debug),
727 ("Debug splitting", self.split_debug)])
729 dirname = self.temp_config.get("dirname", Blender.sys.dirname(Blender.Get("filename")))
730 obj = Blender.Object.GetSelected()[0]
734 Blender.Window.FileSelector(self.export, "Export MSP GL mesh", "%s/%s.%s"%(dirname, obj.name, ext))
739 def export(self, fn):
740 self.config['use_strips'] = self.use_strips.val
741 self.config['use_degen_tris'] = self.use_degen_tris.val
742 self.config['max_strip_len'] = self.max_strip_len.val
743 self.config['optimize_cache'] = self.optimize_cache.val
744 self.config['cache_size'] = self.cache_size.val
745 self.config['export_lines'] = self.export_lines.val
746 self.config['tbn_vecs'] = self.tbn_vecs.val
747 self.config['compound'] = self.compound.val
748 self.config['object'] = self.object.val
749 self.config['material_tex'] = self.material_tex.val
750 self.config['debug'] = self.debug.val
751 self.config['strip_debug'] = self.strip_debug.val
752 self.config['split_debug'] = self.split_debug.val
753 Blender.Registry.SetKey('mspgl_export', self.config, True)
756 self.temp_config["dirname"] = os.path.dirname(fn)
757 Blender.Registry.SetKey('mspgl_export_temp', self.temp_config)
760 exp.use_strips = self.use_strips.val
761 exp.use_degen_tris = self.use_degen_tris.val
762 exp.max_strip_len = self.max_strip_len.val
763 exp.optimize_cache = self.optimize_cache.val
764 exp.cache_size = self.cache_size.val
765 exp.export_lines = self.export_lines.val
766 exp.tbn_vecs = self.tbn_vecs.val
767 exp.compound = self.compound.val
768 exp.object = self.object.val
769 exp.material_tex = self.material_tex.val
770 exp.debug = self.debug.val
771 exp.strip_debug = self.strip_debug.val
772 exp.split_debug = self.split_debug.val
776 if __name__=="__main__":