4 Name: 'Metasequoia(.mqo)...'
\r
7 Tooltip: 'Import from Metasequoia file format (.mqo)'
\r
9 __author__=['ousttrue']
\r
10 __url__ = ["http://gunload.web.fc2.com/blender/"]
\r
11 __version__= '0.6 2010/05/05'
\r
16 This script imports a mqo into Blender for editing.
\r
18 0.2 20080123: update.
\r
19 0.3 20091125: modify for linux.
\r
20 0.4 20100310: rewrite.
\r
21 0.5 20100311: create armature from mikoto bone.
\r
22 0.6 20100505: C extension.
\r
23 0.7 20100606: integrate 2.4 and 2.5.
\r
27 ###############################################################################
\r
29 ###############################################################################
\r
35 from meshio import mqo
\r
38 return sys.version_info[0]<3
\r
43 from Blender import Mathutils
\r
51 from bpy.props import *
\r
57 ###############################################################################
\r
59 ###############################################################################
\r
60 def has_mikoto(mqo):
\r
64 def create_objects(scene, mqo, root, materials, imageMap=None, scale=None):
\r
66 create blender mesh objects.
\r
72 for o in mqo.objects:
\r
73 #print "%s:v(%d),f(%d)" % (o.name, len(o.vertices), len(o.faces))
\r
75 mesh = Blender.Mesh.New()
\r
76 mesh_object=scene.objects.new(mesh, o.name.encode('utf-8'))
\r
79 stack_depth=len(stack)-1
\r
80 print(o.depth, stack_depth)
\r
81 if o.depth<stack_depth:
\r
82 for i in range(stack_depth-o.depth):
\r
84 stack[-1].makeParent([mesh_object])
\r
85 stack.append(mesh_object)
\r
87 if o.name.startswith('sdef'):
\r
89 objects.append(mesh_object)
\r
90 elif o.name.startswith('anchor'):
\r
91 #print("hide %s" % o.name)
\r
92 #mesh_object.restrictDisplay=False
\r
93 mesh_object.layers=[2]
\r
94 elif o.name.startswith('bone'):
\r
95 mesh_object.layers=[2]
\r
98 mesh.verts.extend(Mathutils.Vector(0, 0, 0)) # dummy
\r
99 mesh.verts.extend([(v.x, -v.z, v.y) for v in o.vertices])
\r
102 for face in o.faces:
\r
104 for i in xrange(face.index_count):
\r
105 face_indices.append(face.getIndex(i)+1)
\r
106 mesh_faces.append(face_indices)
\r
107 #new_faces=mesh.faces.extend([face.indices for face in o.faces],
\r
108 new_faces=mesh.faces.extend(mesh_faces,
\r
113 # gather used materials
\r
116 for i in new_faces:
\r
118 usedMaterials[o.faces[i].material_index]=True
\r
120 # blender limits 16 materials per mesh
\r
122 for i, material_index in enumerate(usedMaterials.keys()):
\r
124 print("over 16 materials!")
\r
126 mesh.materials+=[materials[material_index]]
\r
127 usedMaterials[material_index]=i
\r
130 for i, f in enumerate(o.faces):
\r
131 if not type(new_faces[i]) is int:
\r
134 face=mesh.faces[new_faces[i]]
\r
137 for i in xrange(f.index_count):
\r
138 uv_array.append(Blender.Mathutils.Vector(
\r
144 except Exception as msg:
\r
146 #print face.index, uv_array
\r
149 if f.material_index in usedMaterials:
\r
150 face.mat = usedMaterials[f.material_index]
\r
154 # rmeove dummy 0 vertex
\r
155 mesh.verts.delete(0)
\r
157 mesh.mode |= Blender.Mesh.Modes.AUTOSMOOTH
\r
158 mesh.maxSmoothAngle = int(o.smoothing)
\r
166 mod=mesh_object.modifiers.append(Blender.Modifier.Types.MIRROR)
\r
171 class MikotoBone(object):
\r
174 'iHead', 'iTail', 'iUp',
\r
175 'vHead', 'vTail', 'vUp',
\r
176 'parent', 'isFloating',
\r
179 def __init__(self, face=None, vertices=None, materials=None):
\r
181 self.isFloating=False
\r
187 self.name=materials[face.material_index].name.encode('utf-8')
\r
198 sqNorm0=e01.getSqNorm()
\r
199 sqNorm1=e12.getSqNorm()
\r
200 sqNorm2=e20.getSqNorm()
\r
201 if sqNorm0>sqNorm1:
\r
202 if sqNorm1>sqNorm2:
\r
208 if sqNorm0>sqNorm2:
\r
220 if sqNorm1<sqNorm2:
\r
226 if sqNorm0<sqNorm2:
\r
236 self.vHead=vertices[self.iHead]
\r
237 self.vTail=vertices[self.iTail]
\r
238 self.vUp=vertices[self.iUp]
\r
240 if self.name.endswith('[]'):
\r
241 basename=self.name[0:-2]
\r
244 self.name="%s_L" % basename
\r
246 self.name="%s_R" % basename
\r
249 def setParent(self, parent, floating=False):
\r
251 self.isFloating=True
\r
253 parent.children.append(self)
\r
255 def printTree(self, indent=''):
\r
256 print("%s%s" % (indent, self.name))
\r
257 for child in self.children:
\r
258 child.printTree(indent+' ')
\r
261 def build_armature(armature, mikotoBone, parent=None):
\r
263 create a armature bone.
\r
265 bone = Armature.Editbone()
\r
266 bone.name = mikotoBone.name.encode('utf-8')
\r
267 armature.bones[bone.name] = bone
\r
269 bone.head = Mathutils.Vector(*mikotoBone.vHead.to_a())
\r
270 bone.tail = Mathutils.Vector(*mikotoBone.vTail.to_a())
\r
273 if mikotoBone.isFloating:
\r
276 bone.options=[Armature.CONNECTED]
\r
278 for child in mikotoBone.children:
\r
279 build_armature(armature, child, bone)
\r
282 def create_armature(scene, mqo):
\r
287 for o in mqo.objects:
\r
288 if o.name.startswith('bone'):
\r
295 for f in boneObject.faces:
\r
296 if f.index_count!=3:
\r
297 print("invalid index_count: %d" % f.index_count)
\r
299 b=MikotoBone(f, boneObject.vertices, mqo.materials)
\r
302 ####################
\r
303 # build mikoto bone tree
\r
304 ####################
\r
305 mikotoRoot=MikotoBone()
\r
307 for b in tailMap.values():
\r
308 # each bone has unique parent or is root bone.
\r
309 if b.iHead in tailMap:
\r
310 b.setParent(tailMap[b.iHead])
\r
313 for e in boneObject.edges:
\r
314 if b.iHead==e.indices[0]:
\r
316 if e.indices[1] in tailMap:
\r
317 b.setParent(tailMap[e.indices[1]], True)
\r
320 elif b.iHead==e.indices[1]:
\r
322 if e.indices[0] in tailMap:
\r
323 b.setParent(tailMap[e.indices[0]], True)
\r
330 b.setParent(mikotoRoot, True)
\r
332 if len(mikotoRoot.children)==0:
\r
333 print("no root bone")
\r
336 if len(mikotoRoot.children)==1:
\r
338 mikotoRoot=mikotoRoot.children[0]
\r
339 mikotoRoot.parent=None
\r
341 mikotoRoot.vHead=Vector3(0, 10, 0)
\r
342 mikotoRoot.vTail=Vector3(0, 0, 0)
\r
344 ####################
\r
346 ####################
\r
347 armature = Armature.New()
\r
349 armature_object = scene.objects.new(armature)
\r
351 act = Armature.NLA.NewAction()
\r
352 act.setActive(armature_object)
\r
354 armature_object.drawMode |= Object.DrawModes.XRAY
\r
355 # armature settings
\r
356 armature.drawType = Armature.OCTAHEDRON
\r
357 armature.envelopes = False
\r
358 armature.vertexGroups = True
\r
359 armature.mirrorEdit = True
\r
360 armature.drawNames=True
\r
363 armature.makeEditable()
\r
364 build_armature(armature, mikotoRoot)
\r
367 return armature_object
\r
370 class TrianglePlane(object):
\r
372 mikoto方式ボーンのアンカーウェイト計算用。
\r
375 __slots__=['normal',
\r
378 def __init__(self, v0, v1, v2):
\r
383 def isInsideXY(self, p):
\r
384 v0=Vector2(self.v0.x, self.v0.y)
\r
385 v1=Vector2(self.v1.x, self.v1.y)
\r
386 v2=Vector2(self.v2.x, self.v2.y)
\r
390 c0=Vector2.cross(e01, p-v0)
\r
391 c1=Vector2.cross(e12, p-v1)
\r
392 c2=Vector2.cross(e20, p-v2)
\r
393 if c0>=0 and c1>=0 and c2>=0:
\r
395 if c0<=0 and c1<=0 and c2<=0:
\r
398 def isInsideYZ(self, p):
\r
399 v0=Vector2(self.v0.y, self.v0.z)
\r
400 v1=Vector2(self.v1.y, self.v1.z)
\r
401 v2=Vector2(self.v2.y, self.v2.z)
\r
405 c0=Vector2.cross(e01, p-v0)
\r
406 c1=Vector2.cross(e12, p-v1)
\r
407 c2=Vector2.cross(e20, p-v2)
\r
408 if c0>=0 and c1>=0 and c2>=0:
\r
410 if c0<=0 and c1<=0 and c2<=0:
\r
413 def isInsideZX(self, p):
\r
414 v0=Vector2(self.v0.z, self.v0.x)
\r
415 v1=Vector2(self.v1.z, self.v1.x)
\r
416 v2=Vector2(self.v2.z, self.v2.x)
\r
420 c0=Vector2.cross(e01, p-v0)
\r
421 c1=Vector2.cross(e12, p-v1)
\r
422 c2=Vector2.cross(e20, p-v2)
\r
423 if c0>=0 and c1>=0 and c2>=0:
\r
425 if c0<=0 and c1<=0 and c2<=0:
\r
429 class MikotoAnchor(object):
\r
431 mikoto方式スケルトンのアンカー。
\r
434 "triangles", "bbox",
\r
436 def __init__(self):
\r
440 def push(self, face, vertices):
\r
441 if face.index_count==3:
\r
442 self.triangles.append(TrianglePlane(
\r
443 vertices[face.indices[0]],
\r
444 vertices[face.indices[1]],
\r
445 vertices[face.indices[2]]
\r
447 elif face.index_count==4:
\r
448 self.triangles.append(TrianglePlane(
\r
449 vertices[face.indices[0]],
\r
450 vertices[face.indices[1]],
\r
451 vertices[face.indices[2]]
\r
453 self.triangles.append(TrianglePlane(
\r
454 vertices[face.indices[2]],
\r
455 vertices[face.indices[3]],
\r
456 vertices[face.indices[0]]
\r
460 self.bbox=BoundingBox(vertices[face.indices[0]])
\r
461 for i in face.indices:
\r
462 self.bbox.expand(vertices[i])
\r
465 def calcWeight(self, v):
\r
466 if not self.bbox.isInside(v):
\r
469 if self.anyXY(v.x, v.y) and self.anyYZ(v.y, v.z) and self.anyZX(v.z, v.x):
\r
474 def anyXY(self, x, y):
\r
475 for t in self.triangles:
\r
476 if t.isInsideXY(Vector2(x, y)):
\r
480 def anyYZ(self, y, z):
\r
481 for t in self.triangles:
\r
482 if t.isInsideYZ(Vector2(y, z)):
\r
486 def anyZX(self, z, x):
\r
487 for t in self.triangles:
\r
488 if t.isInsideZX(Vector2(z, x)):
\r
493 def create_bone_weight(scene, mqo, armature_object, objects):
\r
495 create mikoto bone weight.
\r
498 # setup mikoto anchors
\r
499 for o in mqo.objects:
\r
500 if o.name.startswith("anchor"):
\r
502 name=mqo.materials[f.material_index].name
\r
503 if name.endswith('[]'):
\r
504 basename=name[0:-2]
\r
505 v=o.vertices[f.indices[0]]
\r
508 name_L=basename+'_L'
\r
509 if not name_L in anchorMap:
\r
510 anchorMap[name_L]=MikotoAnchor()
\r
511 anchorMap[name_L].push(f, o.vertices)
\r
514 name_R=basename+'_R'
\r
515 if not name_R in anchorMap:
\r
516 anchorMap[name_R]=MikotoAnchor()
\r
517 anchorMap[name_R].push(f, o.vertices)
\r
519 print("no side", v)
\r
521 if not name in anchorMap:
\r
522 anchorMap[name]=MikotoAnchor()
\r
523 anchorMap[name].push(f, o.vertices)
\r
526 # add armature modifier
\r
527 mod=o.modifiers.append(Modifier.Types.ARMATURE)
\r
528 mod[Modifier.Settings.OBJECT] = armature_object
\r
529 mod[Modifier.Settings.ENVELOPES] = False
\r
530 o.makeDisplayList()
\r
531 # create vertex group
\r
532 mesh=o.getData(mesh=True)
\r
533 for name in anchorMap.keys():
\r
534 mesh.addVertGroup(name)
\r
537 # assing vertices to vertex group
\r
539 mesh=o.getData(mesh=True)
\r
540 for i, mvert in enumerate(mesh.verts):
\r
542 for name, anchor in anchorMap.items():
\r
543 weight=anchor.calcWeight(mvert.co)
\r
545 mesh.assignVertsToGroup(
\r
546 name, [i], weight, Mesh.AssignModes.ADD)
\r
549 # debug orphan vertex
\r
550 print('orphan', mvert)
\r
556 def create_objects(scene, mqo, parent, materials, imageMap, scale):
\r
557 for o in mqo.objects:
\r
560 mesh=bpy.data.meshes.new("Mesh")
\r
561 meshObject= bpy.data.objects.new(o.getName(), mesh)
\r
562 scene.objects.link(meshObject)
\r
563 meshObject.parent=parent
\r
565 # count triangle and quadrangle
\r
568 if f.index_count==3 or f.index_count==4:
\r
570 mesh.add_geometry(len(o.vertices), 0, faceCount)
\r
573 unpackedVertices=[]
\r
574 for v in o.vertices:
\r
575 # convert right-handed y-up to right-handed z-up
\r
576 unpackedVertices.extend(
\r
577 (scale*v.x, scale*-v.z, scale*v.y))
\r
578 mesh.verts.foreach_set("co", unpackedVertices)
\r
586 for i in range(f.index_count):
\r
587 face.append(f.getIndex(i))
\r
592 if len(face) != 3 and len(face) != 4:
\r
593 print("{0} vertices in face.".format(len(face)))
\r
598 # rotate indices if the 4th is 0
\r
599 face = [face[3], face[0], face[1], face[2]]
\r
600 elif len(face) == 3:
\r
602 # rotate indices if the 3rd is 0
\r
603 face = [face[2], face[0], face[1], 0]
\r
607 unpackedFaces.extend(face)
\r
608 usedMaterial.add(f.material_index)
\r
610 mesh.faces.foreach_set("verts_raw", unpackedFaces)
\r
612 #print([getFace(f) for f in o.faces])
\r
613 print("fail to mesh.faces.foreach_set")
\r
619 for i in usedMaterial:
\r
620 mesh.add_material(materials[i])
\r
621 meshMaterialMap[i]=materialIndex
\r
625 mesh.add_uv_texture()
\r
626 for mqo_face, blender_face, uv_face in zip(
\r
627 o.faces, mesh.faces, mesh.uv_textures[0].data):
\r
628 if mqo_face.index_count<3:
\r
630 blender_face.material_index=meshMaterialMap[mqo_face.material_index]
\r
631 if mqo_face.index_count>=3:
\r
632 uv_face.uv1=[mqo_face.getUV(0).x, 1.0-mqo_face.getUV(0).y]
\r
633 uv_face.uv2=[mqo_face.getUV(1).x, 1.0-mqo_face.getUV(1).y]
\r
634 uv_face.uv3=[mqo_face.getUV(2).x, 1.0-mqo_face.getUV(2).y]
\r
635 if mqo_face.index_count==4:
\r
637 mqo_face.getUV(3).x, 1.0-mqo_face.getUV(3).y]
\r
638 if materials[mqo_face.material_index] in imageMap:
\r
639 uv_face.image=imageMap[mqo_face.material_index]
\r
645 def __createMaterials(scene, mqo, directory):
\r
647 create blender materials and renturn material list.
\r
652 if len(mqo.materials)>0:
\r
653 for material_index, m in enumerate(mqo.materials):
\r
655 material=bl.createMaterial(m)
\r
656 materials.append(material)
\r
658 texture_name=m.getTexture()
\r
659 if texture_name!='':
\r
660 if texture_name in textureMap:
\r
661 texture=textureMap[texture_name]
\r
663 # load texture image
\r
664 if os.path.isabs(texture_name):
\r
666 path = texture_name
\r
669 path = os.path.join(directory, texture_name)
\r
671 if os.path.exists(path):
\r
672 print("create texture:", path)
\r
673 texture, image=bl.createTexture(path)
\r
674 textureMap[texture_name]=texture
\r
675 imageMap[material_index]=image
\r
677 print("%s not exits" % path)
\r
679 bl.materialAddTexture(material, texture)
\r
683 return materials, imageMap
\r
686 def __execute(filename, scene, scale=1.0):
\r
689 if not io.read(filename):
\r
690 print("fail to load",filename)
\r
694 materials, imageMap=__createMaterials(scene, io, os.path.dirname(filename))
\r
697 root=bl.createEmptyObject(scene, os.path.basename(filename))
\r
698 objects=create_objects(scene, io, root, materials, imageMap, scale)
\r
701 # create mikoto bone
\r
702 armature_object=create_armature(scene, io)
\r
703 if armature_object:
\r
704 root.makeParent([armature_object])
\r
706 # create bone weight
\r
707 create_bone_weight(scene, io, armature_object, objects)
\r
710 ###############################################################################
\r
712 ###############################################################################
\r
714 def execute_24(filename):
\r
718 filename=filename.decode(bl.INTERNAL_ENCODING)
\r
719 print("##start mqo_import.py##")
\r
720 print(bl.INTERNAL_ENCODING, bl.FS_ENCODING)
\r
721 print("parse mqo file: %s" % (filename))
\r
723 Blender.Window.WaitCursor(1)
\r
724 t = Blender.sys.time()
\r
727 scene = Blender.Scene.GetCurrent()
\r
728 __execute(filename, scene)
\r
731 print('finished in %.2f seconds' % (Blender.sys.time()-t))
\r
734 Blender.Window.WaitCursor(0)
\r
738 Blender.Window.FileSelector(execute_24, 'Import MQO', '*.mqo')
\r
740 def execute_25(filename, context, scale):
\r
744 __execute(filename, context.scene, scale)
\r
748 class IMPORT_OT_mqo(bpy.types.Operator):
\r
749 '''Import from Metasequoia file format (.mqo)'''
\r
750 bl_idname = "import_scene.mqo"
\r
751 bl_label = 'Import MQO'
\r
753 # List of operator properties, the attributes will be assigned
\r
754 # to the class instance from the operator settings before calling.
\r
756 path = StringProperty(
\r
758 description="File path used for importing the MQO file",
\r
759 maxlen= 1024, default= "")
\r
760 filename = StringProperty(
\r
762 description="Name of the file.")
\r
763 directory = StringProperty(
\r
765 description="Directory of the file.")
\r
767 scale = FloatProperty(
\r
769 description="Scale the MQO by this value",
\r
770 min=0.0001, max=1000000.0,
\r
771 soft_min=0.001, soft_max=100.0, default=1.0)
\r
773 def execute(self, context):
\r
774 execute_25(self.properties.path, context, self.properties.scale)
\r
777 def invoke(self, context, event):
\r
779 wm.add_fileselect(self)
\r
780 return 'RUNNING_MODAL'
\r
784 def menu_func(self, context):
\r
785 self.layout.operator(IMPORT_OT_mqo.bl_idname,
\r
786 text="Metasequoia (.mqo)")
\r
789 bpy.types.register(IMPORT_OT_mqo)
\r
790 bpy.types.INFO_MT_file_import.append(menu_func)
\r
793 bpy.types.unregister(IMPORT_OT_mqo)
\r
794 bpy.types.INFO_MT_file_import.remove(menu_func)
\r
796 if __name__=="__main__":
\r