OSDN Git Service

fix bone group name.
[meshio/meshio.git] / swig / blender / pmd_export.py
index 567edcf..43fc7f9 100644 (file)
@@ -19,6 +19,9 @@ This script exports a pmd model.
 1.0 20100530: implement basic features.
 1.1 20100612: integrate 2.4 and 2.5.
 1.2 20100616: implement rigid body.
+1.3 20100619: fix rigid body, bone weight.
+1.4 20100626: refactoring.
+1.5 20100629: sphere map.
 """
 
 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
@@ -34,6 +37,7 @@ RIGID_LINEAR_DAMPING='rigid_linear_damping'
 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
 RIGID_RESTITUTION='rigid_restitution'
 RIGID_FRICTION='rigid_friction'
+CONSTRAINT_NAME='constraint_name'
 CONSTRAINT_A='const_a'
 CONSTRAINT_B='const_b'
 CONSTRAINT_POS_MIN='const_pos_min'
@@ -64,6 +68,29 @@ if isBlender24():
 
     # wrapper
     import bl24 as bl
+
+    def setMaterialParams(material, m):
+        # diffuse
+        material.diffuse.r=m.R
+        material.diffuse.g=m.G
+        material.diffuse.b=m.B
+        material.diffuse.a=m.alpha
+        # specular
+        material.sinness=0 if m.spec<1e-5 else m.spec*10
+        material.specular.r=m.specR
+        material.specular.g=m.specG
+        material.specular.b=m.specB
+        # ambient
+        material.ambient.r=m.mirR
+        material.ambient.g=m.mirG
+        material.ambient.b=m.mirB
+        # flag
+        material.flag=1 if m.enableSSS else 0
+
+    def toCP932(s):
+        return s
+
+
 else:
     # for 2.5
     import bpy
@@ -75,6 +102,29 @@ else:
 
     xrange=range
 
+    def setMaterialParams(material, m):
+        # diffuse
+        material.diffuse.r=m.diffuse_color[0]
+        material.diffuse.g=m.diffuse_color[1]
+        material.diffuse.b=m.diffuse_color[2]
+        material.diffuse.a=m.alpha
+        # specular
+        material.sinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
+        material.specular.r=m.specular_color[0]
+        material.specular.g=m.specular_color[1]
+        material.specular.b=m.specular_color[2]
+        # ambient
+        material.ambient.r=m.mirror_color[0]
+        material.ambient.g=m.mirror_color[1]
+        material.ambient.b=m.mirror_color[2]
+        # flag
+        material.flag=1 if m.subsurface_scattering.enabled else 0
+        # toon
+        material.toon_index=7
+
+    def toCP932(s):
+        return s.encode('cp932')
+
 
 class Node(object):
     __slots__=['o', 'children']
@@ -157,6 +207,12 @@ class VertexArray(object):
                 self.vertices, self.normals, self.uvs,
                 self.b0, self.b1, self.weight)
 
+    def each(self):
+        keys=[key for key in self.indexArrays.keys()]
+        keys.sort()
+        for key in keys:
+            yield(key, self.indexArrays[key])
+
     def __getIndex(self, obj, base_index, pos, normal, uv, b0, b1, weight0):
         """
         頂点属性からその頂点のインデックスを得る
@@ -202,13 +258,12 @@ class VertexArray(object):
             b1_0, b1_1, b1_2,
             weight0, weight1, weight2
             ):
-        if not material in self.indexArrays:
-            self.indexArrays[material]=[]
-
         index0=self.__getIndex(obj, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
         index1=self.__getIndex(obj, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
         index2=self.__getIndex(obj, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
 
+        if not material in self.indexArrays:
+            self.indexArrays[material]=[]
         self.indexArrays[material]+=[index0, index1, index2]
 
 
@@ -260,25 +315,17 @@ class OneSkinMesh(object):
                 len(self.morphList))
 
     def addMesh(self, obj):
-        if bl.objectIsVisible(obj):
-            # 非表示
+        if bl.object.isVisible(obj):
+            return
+        if not bl.modifier.hasType(obj, 'ARMATURE'):
             return
         self.__mesh(obj)
         self.__skin(obj)
         self.__rigidbody(obj)
         self.__constraint(obj)
 
-    def __mesh(self, obj):
-        if isBlender24():
-            pass
-        else:
-            if RIGID_SHAPE_TYPE in obj:
-                return
-            if CONSTRAINT_A in obj:
-                return
-
-        print("export", obj.name)
-        mesh=bl.objectGetData(obj)
+    def __getWeightMap(self, obj, mesh):
+        # bone weight
         weightMap={}
         secondWeightMap={}
         def setWeight(i, name, w):
@@ -286,9 +333,9 @@ class OneSkinMesh(object):
                 if i in weightMap:
                     if i in secondWeightMap:
                         # 上位2つのweightを採用する
-                        if w<secondWeightMap[i]:
+                        if w<secondWeightMap[i][1]:
                             pass
-                        elif w<weightMap[i]:
+                        elif w<weightMap[i][1]:
                             # 2つ目を入れ替え
                             secondWeightMap[i]=(name, w)
                         else:
@@ -305,13 +352,16 @@ class OneSkinMesh(object):
                     weightMap[i]=(name, w)
 
         if isBlender24():
-            for name in bl.meshVertexGroupNames(obj):
+            for name in bl.object.getVertexGroupNames(obj):
                 for i, w in mesh.getVertsFromGroup(name, 1):
                     setWeight(i, name, w)
         else:
             for i, v in enumerate(mesh.verts):
-                for g in v.groups:
-                    setWeight(i, obj.vertex_groups[g.group].name, g.weight)
+                if len(v.groups)>0:
+                    for g in v.groups:
+                        setWeight(i, obj.vertex_groups[g.group].name, g.weight)
+                else:
+                    setWeight(i, obj.vertex_groups[0].name, 1)
 
         # 合計値が1になるようにする
         for i in xrange(len(mesh.verts)):
@@ -326,102 +376,156 @@ class OneSkinMesh(object):
                 weightMap[i]=("", 0)
                 secondWeightMap[i]=("", 0)
 
-        # メッシュのコピーを生成してオブジェクトの行列を適用する
-        copyMesh, copyObj=bl.objectDuplicate(self.scene, obj)
-        if len(copyMesh.verts)==0:
-            return
-
-        for i, face in enumerate(copyMesh.faces):
-            faceVertexCount=bl.faceVertexCount(face)
-            material=copyMesh.materials[bl.faceMaterialIndex(face)]
-            v=[copyMesh.verts[index] for index in bl.faceVertices(face)]
-            uv=bl.meshFaceUv(copyMesh, i, face)
+        return weightMap, secondWeightMap
+
+    def __processFaces(self, mesh, weightMap, secondWeightMap):
+        # 各面の処理
+        for i, face in enumerate(mesh.faces):
+            faceVertexCount=bl.face.getVertexCount(face)
+            material=mesh.materials[bl.face.getMaterialIndex(face)]
+            v=[mesh.verts[index] for index in bl.face.getVertices(face)]
+            uv=bl.mesh.getFaceUV(
+                    mesh, i, face, bl.face.getVertexCount(face))
+            # flip triangle
             if faceVertexCount==3:
                 # triangle
                 self.vertexArray.addTriangle(
                         self.obj_index, material.name,
-                        v[0].index, v[1].index, v[2].index,
-                        v[0].co, v[1].co, v[2].co,
+                        v[2].index, 
+                        v[1].index, 
+                        v[0].index,
+                        v[2].co, 
+                        v[1].co, 
+                        v[0].co,
                         # ToDo vertex normal
                         #v0.no, v1.no, v2.no,
-                        bl.faceNormal(face), 
-                        bl.faceNormal(face), 
-                        bl.faceNormal(face),
-                        uv[0], uv[1], uv[2],
-                        weightMap[v[0].index][0],
-                        weightMap[v[1].index][0],
+                        bl.face.getNormal(face), 
+                        bl.face.getNormal(face), 
+                        bl.face.getNormal(face),
+                        uv[2], 
+                        uv[1], 
+                        uv[0],
                         weightMap[v[2].index][0],
-                        secondWeightMap[v[0].index][0],
-                        secondWeightMap[v[1].index][0],
+                        weightMap[v[1].index][0],
+                        weightMap[v[0].index][0],
                         secondWeightMap[v[2].index][0],
-                        weightMap[v[0].index][1],
+                        secondWeightMap[v[1].index][0],
+                        secondWeightMap[v[0].index][0],
+                        weightMap[v[2].index][1],
                         weightMap[v[1].index][1],
-                        weightMap[v[2].index][1]
+                        weightMap[v[0].index][1]
                         )
             elif faceVertexCount==4:
                 # quadrangle
                 self.vertexArray.addTriangle(
                         self.obj_index, material.name,
-                        v[0].index, v[1].index, v[2].index,
-                        v[0].co, v[1].co, v[2].co,
+                        v[2].index, 
+                        v[1].index, 
+                        v[0].index,
+                        v[2].co, 
+                        v[1].co, 
+                        v[0].co,
                         #v0.no, v1.no, v2.no,
-                        bl.faceNormal(face), 
-                        bl.faceNormal(face), 
-                        bl.faceNormal(face), 
-                        uv[0], uv[1], uv[2],
-                        weightMap[v[0].index][0],
-                        weightMap[v[1].index][0],
+                        bl.face.getNormal(face), 
+                        bl.face.getNormal(face), 
+                        bl.face.getNormal(face), 
+                        uv[2], 
+                        uv[1], 
+                        uv[0],
                         weightMap[v[2].index][0],
-                        secondWeightMap[v[0].index][0],
-                        secondWeightMap[v[1].index][0],
+                        weightMap[v[1].index][0],
+                        weightMap[v[0].index][0],
                         secondWeightMap[v[2].index][0],
-                        weightMap[v[0].index][1],
+                        secondWeightMap[v[1].index][0],
+                        secondWeightMap[v[0].index][0],
+                        weightMap[v[2].index][1],
                         weightMap[v[1].index][1],
-                        weightMap[v[2].index][1]
+                        weightMap[v[0].index][1]
                         )
                 self.vertexArray.addTriangle(
                         self.obj_index, material.name,
-                        v[2].index, v[3].index, v[0].index,
-                        v[2].co, v[3].co, v[0].co,
+                        v[0].index, 
+                        v[3].index, 
+                        v[2].index,
+                        v[0].co, 
+                        v[3].co, 
+                        v[2].co,
                         #v2.no, v3.no, v0.no,
-                        bl.faceNormal(face), 
-                        bl.faceNormal(face), 
-                        bl.faceNormal(face), 
-                        uv[2], uv[3], uv[0],
-                        weightMap[v[2].index][0],
-                        weightMap[v[3].index][0],
+                        bl.face.getNormal(face), 
+                        bl.face.getNormal(face), 
+                        bl.face.getNormal(face), 
+                        uv[0], 
+                        uv[3], 
+                        uv[2],
                         weightMap[v[0].index][0],
-                        secondWeightMap[v[2].index][0],
-                        secondWeightMap[v[3].index][0],
+                        weightMap[v[3].index][0],
+                        weightMap[v[2].index][0],
                         secondWeightMap[v[0].index][0],
-                        weightMap[v[2].index][1],
+                        secondWeightMap[v[3].index][0],
+                        secondWeightMap[v[2].index][0],
+                        weightMap[v[0].index][1],
                         weightMap[v[3].index][1],
-                        weightMap[v[0].index][1]
+                        weightMap[v[2].index][1]
                         )
-        bl.objectDelete(self.scene, copyObj)
+
+    def __mesh(self, obj):
+        if isBlender24():
+            pass
+        else:
+            if RIGID_SHAPE_TYPE in obj:
+                return
+            if CONSTRAINT_A in obj:
+                return
+
+        print("export", obj.name)
+
+        # メッシュのコピーを生成してオブジェクトの行列を適用する
+        copyMesh, copyObj=bl.object.duplicate(obj)
+        if len(copyMesh.verts)==0:
+            return
+        # apply transform
+        copyObj.scale=obj.scale
+        bpy.ops.object.scale_apply()
+        copyObj.rotation_euler=obj.rotation_euler
+        bpy.ops.object.rotation_apply()
+        copyObj.location=obj.location
+        bpy.ops.object.location_apply()
+        # apply modifier
+        for m in [m for m in copyObj.modifiers]:
+            if m.type=='SOLIDFY':
+                continue
+            bpy.ops.object.modifier_apply(modifier=m.name)
+
+        weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
+        self.__processFaces(copyMesh, weightMap, secondWeightMap)
+
+        bl.object.delete(copyObj)
         self.obj_index+=1
 
+    def createEmptyBasicSkin(self):
+        self.__getOrCreateMorph('base', 0)
+
     def __skin(self, obj):
-        if not bl.objectHasShapeKey(obj):
+        if not bl.object.hasShapeKey(obj):
             return
 
         indexRelativeMap={}
-        blenderMesh=bl.objectGetData(obj)
+        blenderMesh=bl.object.getData(obj)
         baseMorph=None
 
         # shape keys
-        vg=bl.meshVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
+        vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
 
         # base
         used=set()
-        for b in bl.objectShapeKeys(obj):
+        for b in bl.object.getShapeKeys(obj):
             if b.name==BASE_SHAPE_NAME:
                 baseMorph=self.__getOrCreateMorph('base', 0)
                 basis=b
 
                 relativeIndex=0
                 for index in vg:
-                    v=bl.shapeKeyGet(b, index)
+                    v=bl.shapekey.getByIndex(b, index)
                     pos=[v[0], v[1], v[2]]
                     indices=self.vertexArray.getMappedIndices(index)
                     for i in indices:
@@ -441,7 +545,7 @@ class OneSkinMesh(object):
             return
 
         # shape keys
-        for b in bl.objectShapeKeys(obj):
+        for b in bl.object.getShapeKeys(obj):
             if b.name==BASE_SHAPE_NAME:
                 continue
 
@@ -450,8 +554,8 @@ class OneSkinMesh(object):
             used=set()
             for index, src, dst in zip(
                     xrange(len(blenderMesh.verts)),
-                    bl.shapeKeys(basis),
-                    bl.shapeKeys(b)):
+                    bl.shapekey.get(basis),
+                    bl.shapekey.get(b)):
                 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
                     continue
@@ -470,6 +574,7 @@ class OneSkinMesh(object):
                 if v[0]==morph.name:
                     return i
             print(morph)
+            return len(englishmap.skinMap)
         if isBlender24():
             self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
         else:
@@ -533,13 +638,13 @@ class BoneBuilder(object):
             return
 
         print("gather bones")
-        armature=bl.objectGetData(armatureObj)
+        armature=bl.object.getData(armatureObj)
         for b in armature.bones.values():
             if b.name=='center':
                 # root bone
                 bone=Bone(b.name, 
-                        bl.boneHeadLocal(b),
-                        bl.boneTailLocal(b))
+                        bl.bone.getHeadLocal(b),
+                        bl.bone.getTailLocal(b))
                 self.__addBone(bone)
                 self.__getBone(bone, b)
 
@@ -547,8 +652,8 @@ class BoneBuilder(object):
             if not b.parent and b.name!='center':
                 # root bone
                 bone=Bone(b.name, 
-                        bl.boneHeadLocal(b),
-                        bl.boneTailLocal(b))
+                        bl.bone.getHeadLocal(b),
+                        bl.bone.getTailLocal(b))
                 self.__addBone(bone)
                 self.__getBone(bone, b)
 
@@ -558,14 +663,14 @@ class BoneBuilder(object):
                 self.__checkConnection(b, None)
 
         print("gather ik")
-        pose = bl.objectGetPose(armatureObj)
+        pose = bl.object.getPose(armatureObj)
         for b in pose.bones.values():
             for c in b.constraints:
-                if bl.constraintIsIKSolver(c):
+                if bl.constraint.isIKSolver(c):
                     ####################
                     # IK target
                     ####################
-                    target=self.__boneByName(bl.ikTarget(c))
+                    target=self.__boneByName(bl.constraint.ikTarget(c))
                     target.type=2
 
                     ####################
@@ -577,7 +682,7 @@ class BoneBuilder(object):
 
                     # IK chain
                     e=b.parent
-                    chainLength=bl.ikChainLen(c)
+                    chainLength=bl.constraint.ikChainLen(c)
                     for i in range(chainLength):
                         # IK影響下
                         chainBone=self.__boneByName(e.name)
@@ -586,8 +691,8 @@ class BoneBuilder(object):
                         e=e.parent
                     self.ik_list.append(
                             IKSolver(target, link, chainLength, 
-                                int(bl.ikItration(c) * 0.1), 
-                                bl.ikRotationWeight(c)
+                                int(bl.constraint.ikItration(c) * 0.1), 
+                                bl.constraint.ikRotationWeight(c)
                                 ))
 
         # boneのsort
@@ -605,7 +710,7 @@ class BoneBuilder(object):
             self.ik_list.sort(key=getIndex)
 
     def __checkConnection(self, b, p):
-        if bl.boneIsConnected(b):
+        if bl.bone.isConnected(b):
             parent=self.__boneByName(p.name)
             parent.isConnect=True
 
@@ -623,6 +728,7 @@ class BoneBuilder(object):
                 if k_v[0]==bone.name:
                     return i
             print(bone)
+            return len(boneMap)
 
         if isBlender24():
             self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
@@ -684,8 +790,8 @@ class BoneBuilder(object):
 
         for i, c in enumerate(b.children):
             bone=Bone(c.name, 
-                    bl.boneHeadLocal(c),
-                    bl.boneTailLocal(c))
+                    bl.bone.getHeadLocal(c),
+                    bl.bone.getTailLocal(c))
             self.__addBone(bone)
             if parent:
                 bone.parent_index=parent.index
@@ -722,6 +828,10 @@ class PmdExporter(object):
         self.oneSkinMesh=OneSkinMesh(scene)
         self.__createOneSkinMesh(root)
         print(self.oneSkinMesh)
+        if len(self.oneSkinMesh.morphList)==0:
+            # create emtpy skin
+            self.oneSkinMesh.createEmptyBasicSkin()
+
         self.name=root.o.name
 
         # skeleton
@@ -733,8 +843,8 @@ class PmdExporter(object):
         # search armature modifier
         ############################################################
         for m in node.o.modifiers:
-            if bl.modifierIsArmature(m):
-                armatureObj=bl.armatureModifierGetObject(m)
+            if bl.modifier.isType(m, 'ARMATURE'):
+                armatureObj=bl.modifier.getArmatureObject(m)
                 if not self.armatureObj:
                     self.armatureObj=armatureObj
                 elif self.armatureObj!=armatureObj:
@@ -764,7 +874,7 @@ class PmdExporter(object):
             v.normal.y=normal[2]
             v.normal.z=normal[1]
             v.uv.x=uv[0]
-            v.uv.y=uv[1]
+            v.uv.y=1.0-uv[1] # reverse vertical
             v.bone0=self.builder.indexByName(b0)
             v.bone1=self.builder.indexByName(b1)
             v.weight0=int(100*weight)
@@ -772,41 +882,21 @@ class PmdExporter(object):
 
         # 面とマテリアル
         vertexCount=self.oneSkinMesh.getVertexCount()
-        for material_name, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
-            m=bl.materialGet(self.scene, material_name)
+        for material_name, indices in self.oneSkinMesh.vertexArray.each():
+            print('material:', material_name)
+            m=bl.material.get(material_name)
             # マテリアル
             material=io.addMaterial()
-            if isBlender24():
-                material.diffuse.r=m.R
-                material.diffuse.g=m.G
-                material.diffuse.b=m.B
-                material.diffuse.a=m.alpha
-                material.sinness=0 if m.spec<1e-5 else m.spec*10
-                material.specular.r=m.specR
-                material.specular.g=m.specG
-                material.specular.b=m.specB
-                material.ambient.r=m.mirR
-                material.ambient.g=m.mirG
-                material.ambient.b=m.mirB
-                material.flag=1 if m.enableSSS else 0
-            else:
-                material.diffuse.r=m.diffuse_color[0]
-                material.diffuse.g=m.diffuse_color[1]
-                material.diffuse.b=m.diffuse_color[2]
-                material.diffuse.a=m.alpha
-                material.sinness=0 if m.specular_hardness<1e-5 else m.specular_hardness*10
-                material.specular.r=m.specular_color[0]
-                material.specular.g=m.specular_color[1]
-                material.specular.b=m.specular_color[2]
-                material.ambient.r=m.mirror_color[0]
-                material.ambient.g=m.mirror_color[1]
-                material.ambient.b=m.mirror_color[2]
-                material.flag=1 if m.subsurface_scattering.enabled else 0
+            setMaterialParams(material, m)
 
             material.vertex_count=len(indices)
             material.toon_index=0
-            # ToDo
-            material.texture=""
+            textures=[os.path.basename(path) 
+                for path in bl.material.eachTexturePath(m)]
+            if len(textures)>0:
+                material.setTexture(toCP932('*'.join(textures)))
+            else:
+                material.setTexture(toCP932(""))
             # 面
             for i in indices:
                 assert(i<vertexCount)
@@ -824,15 +914,17 @@ class PmdExporter(object):
             # name
             boneNameMap[b.name]=i
             v=englishmap.getUnicodeBoneName(b.name)
+            if not v:
+                v=[b.name, b.name]
             assert(v)
             cp932=v[1].encode('cp932')
             assert(len(cp932)<20)
             bone.setName(cp932)
 
             # english name
-            bone_english_name=b.name
+            bone_english_name=toCP932(b.name)
             assert(len(bone_english_name)<20)
-            bone.english_name=bone_english_name
+            bone.setEnglishName(bone_english_name)
 
             if len(v)>=3:
                 # has type
@@ -870,6 +962,8 @@ class PmdExporter(object):
             morph=io.addMorph()
 
             v=englishmap.getUnicodeSkinName(m.name)
+            if not v:
+                v=[m.name, m.name, 0]
             assert(v)
             cp932=v[1].encode('cp932')
             morph.setName(cp932)
@@ -898,14 +992,14 @@ class PmdExporter(object):
 
         # ボーン表示枠
         def createBoneDisplayName(name, english):
-            boneDisplayName=io.addBoneDisplayName()
+            boneDisplayName=io.addBoneGroup()
             if isBlender24():
                 boneDisplayName.name=name.decode('utf-8').encode('cp932')
                 boneDisplayName.english_name=english
             else:
                 boneDisplayName.setName(name.encode('cp932'))
                 boneDisplayName.setEnglishName(english.encode('cp932'))
-        boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
+        boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
         boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
         boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
         boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
@@ -973,7 +1067,7 @@ class PmdExporter(object):
         # constraint
         for obj in self.oneSkinMesh.constraints:
             constraint=io.addConstraint()
-            constraint.setName(obj.name[1:].encode('cp932'))
+            constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
             constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
             constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
             constraint.pos.x=obj.location[0]
@@ -1056,7 +1150,7 @@ def getBoneDisplayGroup(bone):
             return index
         index+=1
     print(bone)
-    return -1
+    return 0
 
 
 def __execute(filename, scene):
@@ -1064,30 +1158,20 @@ def __execute(filename, scene):
         print("abort. no active object.")
         return
 
-    bl.progress_start('pmd_export')
-    active=bl.objectGetActive(scene)
+    active=bl.object.getActive()
     exporter=PmdExporter()
     exporter.setup(scene)
     exporter.write(filename)
-    bl.objectActivate(scene, active)
-    bl.progress_finish()
+    bl.object.activate(active)
 
 
 if isBlender24():
     # for 2.4
     def execute_24(filename):
-        filename=filename.decode(bl.INTERNAL_ENCODING)
-        print("pmd exporter: %s" % filename)
-
-        Blender.Window.WaitCursor(1) 
-        t = Blender.sys.time() 
-
         scene = bpy.data.scenes.active
-        __execute(filename, scene)
-
-        print('finished in %.2f seconds' % (Blender.sys.time()-t))
-        Blender.Redraw()
-        Blender.Window.WaitCursor(0) 
+        bl.initialize('pmd_export', scene)
+        __execute(filename.decode(bl.INTERNAL_ENCODING), scene)
+        bl.finalize()
 
     Blender.Window.FileSelector(
              execute_24,
@@ -1096,8 +1180,10 @@ if isBlender24():
 
 else:
     # for 2.5
-    def execute_25(*args):
-        __execute(*args)
+    def execute_25(filename, scene):
+        bl.initialize('pmd_export', scene)
+        __execute(filename, scene)
+        bl.finalize()
 
     # operator
     class EXPORT_OT_pmd(bpy.types.Operator):