Skip to content
Snippets Groups Projects
io_export_marmalade.py 61.6 KiB
Newer Older
  • Learn to ignore specific revisions
  •     for Bone in RootBonesList:
            if Config.Verbose:
                print("      Writing Root Bone: {}...".format(Bone.name))
    
            PoseBone = PoseBones[Bone.name]
            WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, skelFile, True)
            if Config.Verbose:
                print("      Done")
            WriteArmatureChildBones(Config, Object, Bone.children, skelFile)
    
    
    def WriteArmatureChildBones(Config, Object, BonesList, skelFile):
        PoseBones = Object.pose.bones
        for Bone in BonesList:
            if Config.Verbose:
                print("      Writing Child Bone: {}...".format(Bone.name))
            PoseBone = PoseBones[Bone.name]
            WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, skelFile, True)
            if Config.Verbose:
                print("      Done")
    
            WriteArmatureChildBones(Config, Object, Bone.children, skelFile)
    
    
    
    def WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, File, isRestPoseNotAnimPose):
    
        # Many others exporter require sthe user to do Apply Scale in Object Mode to have 1,1,1 scale and so that anim data are correctly scaled
        # Here we retreive the Scale of the Armture Object.matrix_world.to_scale() and we use it to scale the bones :-)
        # So new Blender user should not complain about bad animation export if they forgot to apply the Scale to 1,1,1
    
        armScale = Object.matrix_world.to_scale()
    
        armRot = Object.matrix_world.to_quaternion()
        if isRestPoseNotAnimPose:
    
            #skel file, bone header
            File.write("\tCIwAnimBone\n")
            File.write("\t{\n")
            File.write("\t\tname \"%s\"\n" % StripBoneName(Bone.name))
    
            #get bone local matrix for rest pose
    
            if Bone.parent:
                File.write("\t\tparent \"%s\"\n" % StripBoneName(Bone.parent.name))
    
                localmat = Bone.parent.matrix_local.inverted() * Bone.matrix_local
            else:
                localmat = Bone.matrix_local
    
        else:
            #anim file, bone header
            File.write("\t\t\n")
            File.write("\t\tbone \"%s\" \n" % StripBoneName(Bone.name))
    
            localmat = PoseBone.matrix
            #get bone local matrix for current anim pose
            if Bone.parent:
                ParentPoseBone = PoseBones[Bone.parent.name]
                localmat = ParentPoseBone.matrix.inverted() * PoseBone.matrix
            else:
                localmat = PoseBone.matrix
    
        if not Bone.parent:
            #Flip Y Z axes (only on root bone, other bones are local to root bones, so no need to rotate)
    
            X_ROT = mathutils.Matrix.Rotation(-math.pi / 2, 4, 'X')
    
            if Config.MergeModes > 0:
                # Merge mode is in world coordinates and not in model coordinates: so apply the world coordinate on the rootbone
                localmat = X_ROT * Object.matrix_world * localmat
                armScale.x =  armScale.y = armScale.z = 1
            else:
                localmat= X_ROT * armRot.to_matrix().to_4x4() * localmat #apply the armature rotation on the root bone
    
    
        loc = localmat.to_translation()
        quat = localmat.to_quaternion()
    
    
        #Scale the bone
        loc.x *= (armScale.x * Config.Scale)
        loc.y *= (armScale.y * Config.Scale)
        loc.z *= (armScale.z * Config.Scale)
    
        File.write("\t\tpos { %.9f, %.9f, %.9f }\n" % (loc[0], loc[1], loc[2]))
        File.write("\t\trot { %.9f, %.9f, %.9f, %.9f }\n" % (quat.w, quat.x, quat.y, quat.z))
    
    
        for Object in [Object for Object in Config.ObjectList if Object.animation_data]:
            if Config.Verbose:
                print("  Writing Animation Data for Object: {}".format(Object.name))
    
            actions = []
            if Config.ExportAnimationActions == 0 and Object.animation_data.action:
                actions.append(Object.animation_data.action)
            else:
    
                DefaultAction = Object.animation_data.action
    
            for Action in actions:
                if Config.ExportAnimationActions == 0:
                    animFileName = StripName(Object.name)
                else:
                    Object.animation_data.action = Action
                    animFileName = "%s_%s" % (StripName(Object.name),StripName(Action.name))
    
                #Object animated (aka single bone object)
                #build key frame time list
    
                keyframeTimes = set()
    
                if Config.ExportAnimationFrames == 1:
    
                    # Exports only key frames
                    for FCurve in Action.fcurves:
                        for Keyframe in FCurve.keyframe_points:
    
                            if Keyframe.co[0] < Scene.frame_start:
                                keyframeTimes.add(Scene.frame_start)
                            elif Keyframe.co[0] > Scene.frame_end:
                                keyframeTimes.add(Scene.frame_end)
    
                            else:
                                keyframeTimes.add(int(Keyframe.co[0]))
                else:
                    # Exports all frames
    
                    keyframeTimes.update(range(Scene.frame_start, Scene.frame_end + 1, 1))
    
                keyframeTimes = list(keyframeTimes)
                keyframeTimes.sort()
                if len(keyframeTimes):
                    #Create the anim file for offset animation (or single bone animation
    
                    animfullname = os.path.dirname(Config.FilePath) + os.sep + "anims" + os.sep + "%s_offset.anim" % animFileName
    
                    #not yet supported
    
                    ##    ensure_dir(animfullname)
                    ##    if Config.Verbose:
                    ##        print("      Creating anim file (single bone animation) %s" % (animfullname))
                    ##    animFile = open(animfullname, "w")
    
                    ##    animFile.write('// anim file exported from : %r\n' % os.path.basename(bpy.data.filepath))
    
                    ##    animFile.write("CIwAnim\n")
                    ##    animFile.write("{\n")
                    ##    animFile.write("\tent \"%s\"\n" % (StripName(Object.name)))
                    ##    animFile.write("\tskeleton \"SingleBone\"\n")
                    ##    animFile.write("\t\t\n")
                    ##
    
                    ##    Config.File.write("\t\".\\anims\\%s_offset.anim\"\n" % animFileName))
    
                    ##
                    ##    for KeyframeTime in keyframeTimes:
    
                    ##        animFile.write("\tCIwAnimKeyFrame\n")
                    ##        animFile.write("\t{\n")
                    ##        animFile.write("\t\ttime %.2f // frame num %d \n" % (KeyframeTime/Config.AnimFPS, KeyframeTime))
                    ##        animFile.write("\t\t\n")
                    ##        animFile.write("\t\tbone \"SingleBone\" \n")
                    ##        #postion
                    ##        posx = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "location" and FCurve.array_index == 0: posx = FCurve.evaluate(KeyframeTime)
                    ##        posy = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "location" and FCurve.array_index == 1: posy = FCurve.evaluate(KeyframeTime)
                    ##        posz = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "location" and FCurve.array_index == 2: posz = FCurve.evaluate(KeyframeTime)
                    ##        animFile.write("\t\tpos {%.9f,%.9f,%.9f}\n" % (posx, posy, posz))
                    ##        #rotation
                    ##        rot = Euler()
                    ##        rot[0] = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "rotation_euler" and FCurve.array_index == 1: rot[0] = FCurve.evaluate(KeyframeTime)
                    ##        rot[1] = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "rotation_euler" and FCurve.array_index == 2: rot[1] = FCurve.evaluate(KeyframeTime)
                    ##        rot[2] = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "rotation_euler" and FCurve.array_index == 3: rot[2] = FCurve.evaluate(KeyframeTime)
                    ##        rot = rot.to_quaternion()
                    ##        animFile.write("\t\trot {%.9f,%.9f,%.9f,%.9f}\n" % (rot[0], rot[1], rot[2], rot[3]))
                    ##        #scale
                    ##        scalex = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "scale" and FCurve.array_index == 0: scalex = FCurve.evaluate(KeyframeTime)
                    ##        scaley = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "scale" and FCurve.array_index == 1: scaley = FCurve.evaluate(KeyframeTime)
                    ##        scalez = 0
                    ##        for FCurve in Action.fcurves:
                    ##            if FCurve.data_path == "scale" and FCurve.array_index == 2: scalez = FCurve.evaluate(KeyframeTime)
                    ##        animFile.write("\t\t//scale {%.9f,%.9f,%.9f}\n" % (scalex, scaley, scalez))
                    ##        #keyframe done
                    ##        animFile.write("\t}\n")
                    ##    animFile.write("}\n")
                    ##    animFile.close()
    
                else:
                    if Config.Verbose:
                        print("    Object %s has no useable animation data." % (StripName(Object.name)))
    
                if Config.ExportArmatures and Object.type == "ARMATURE":
                    if Config.Verbose:
                        print("    Writing Armature Bone Animation Data...\n")
                    PoseBones = Object.pose.bones
                    Bones = Object.data.bones
    
                    #build key frame time list
                    keyframeTimes = set()
    
                    if Config.ExportAnimationFrames == 1:
    
                        # Exports only key frames
                        for FCurve in Action.fcurves:
                            for Keyframe in FCurve.keyframe_points:
    
                                if Keyframe.co[0] < Scene.frame_start:
                                    keyframeTimes.add(Scene.frame_start)
                                elif Keyframe.co[0] > Scene.frame_end:
                                    keyframeTimes.add(Scene.frame_end)
    
                                else:
                                    keyframeTimes.add(int(Keyframe.co[0]))
                    else:
                        # Exports all frame
    
                        keyframeTimes.update(range(Scene.frame_start, Scene.frame_end + 1, 1))
    
                    keyframeTimes = list(keyframeTimes)
                    keyframeTimes.sort()
    
                    if Config.Verbose:
                        print("Exporting frames: ")
                        print(keyframeTimes)
                        if (Scene.frame_preview_end > Scene.frame_end):
                            print(" WARNING: END Frame of animation in UI preview is Higher than the Scene Frame end:\n Scene.frame_end %d versus Scene.frame_preview_end %d.\n"
                                  % (Scene.frame_end, Scene.frame_preview_end))
                            print(" => You might need to change the Scene End Frame, to match the current UI preview frame end...\n=> if you don't want to miss end of animation.\n")
    
    
                    if len(keyframeTimes):
                        #Create the anim file
    
                        animfullname = os.path.dirname(Config.FilePath) + os.sep + "anims" + os.sep + "%s.anim" % animFileName
    
                        ensure_dir(animfullname)
                        if Config.Verbose:
                            print("      Creating anim file (bones animation) %s\n" % (animfullname))
                            print("      Frame count %d \n" % (len(keyframeTimes)))
                        animFile = open(animfullname, "w")
    
                        animFile.write('// anim file exported from : %r\n' % os.path.basename(bpy.data.filepath))
    
                        animFile.write("CIwAnim\n")
                        animFile.write("{\n")
                        animFile.write("\tskeleton \"%s\"\n" % (StripName(Object.name)))
                        animFile.write("\t\t\n")
    
    
                        Config.File.write("\t\".\\anims\\%s.anim\"\n" % animFileName)
    
    
                        for KeyframeTime in keyframeTimes:
                            if Config.Verbose:
                                print("     Writing Frame %d:" % KeyframeTime)
                            animFile.write("\tCIwAnimKeyFrame\n")
                            animFile.write("\t{\n")
                            animFile.write("\t\ttime %.2f // frame num %d \n" % (KeyframeTime / Config.AnimFPS, KeyframeTime))
                            #for every frame write bones positions
    
                            Scene.frame_set(KeyframeTime)
    
                            for PoseBone in PoseBones:
                                if Config.Verbose:
                                    print("      Writing Bone: {}...".format(PoseBone.name))
                                animFile.write("\t\t\n")
    
                                Bone = Bones[PoseBone.name]
                                WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, animFile, False)
                            #keyframe done
                            animFile.write("\t}\n")
                        animFile.write("}\n")
                        animFile.close()
                else:
                    if Config.Verbose:
                        print("    Object %s has no useable animation data." % (StripName(Object.name)))
    
            if Config.ExportAnimationActions == 1:
                #set back the original default animation
                Object.animation_data.action = DefaultAction
    
            if Config.Verbose:
                print("  Done") #Done with Object
    
    
    ################## Utilities
    
    def StripBoneName(name):
        return name.replace(" ", "")
    
    
    def StripName(Name):
    
        def ReplaceSet(String, OldSet, NewChar):
            for OldChar in OldSet:
                String = String.replace(OldChar, NewChar)
            return String
    
        NewName = ReplaceSet(Name, string.punctuation + " ", "_")
        return NewName
    
    
    def ensure_dir(f):
        d = os.path.dirname(f)
        if not os.path.exists(d):
            os.makedirs(d)
    
    
    def CloseFile(Config):
        if Config.Verbose:
            print("Closing File...")
        Config.File.close()
        if Config.Verbose:
            print("Done")
    
    
    CoordinateSystems = (
        ("1", "Left-Handed", ""),
        ("2", "Right-Handed", ""),
        )
    
    
    
        ("0", "None", ""),
        ("1", "Keyframes Only", ""),
        ("2", "Full Animation", ""),
        )
    
    
    AnimationActions = (
        ("0", "Default Animation", ""),
        ("1", "All Animations", ""),
        )
    
    
    ExportModes = (
        ("1", "All Objects", ""),
        ("2", "Selected Objects", ""),
        )
    
    MergeModes = (
        ("0", "None", ""),
        ("1", "Merge in one big Mesh", ""),
        ("2", "Merge in unique Geo File containing several meshes", ""),
        )
    
    
    from bpy.props import StringProperty, EnumProperty, BoolProperty, IntProperty
    
    
    class MarmaladeExporter(bpy.types.Operator):
        """Export to the Marmalade model format (.group)"""
    
        bl_idname = "export.marmalade"
        bl_label = "Export Marmalade"
    
        filepath = StringProperty(subtype='FILE_PATH')
         #Export Mode
        ExportMode = EnumProperty(
            name="Export",
            description="Select which objects to export. Only Mesh, Empty, " \
                        "and Armature objects will be exported",
            items=ExportModes,
            default="1")
    
        MergeModes = EnumProperty(
            name="Merge",
            description="Select if objects should be merged in one Geo File (it can be usefull if a scene is done by several cube/forms)." \
                        "Do not merge rigged character that have an armature.",
            items=MergeModes,
            default="0")
    
        #General Options
        Scale = IntProperty(
            name="Scale Percent",
            description="Scale percentage applied for export",
            default=100, min=1, max=1000)
    
        FlipNormals = BoolProperty(
            name="Flip Normals",
            description="",
            default=False)
        ApplyModifiers = BoolProperty(
            name="Apply Modifiers",
            description="Apply object modifiers before export",
            default=False)
        ExportVertexColors = BoolProperty(
            name="Export Vertices Colors",
            description="Export colors set on vertices, if any",
            default=True)
        ExportMaterialColors = BoolProperty(
            name="Export Material Colors",
            description="Ambient color is exported on the Material",
            default=True)
        ExportTextures = BoolProperty(
            name="Export Textures and UVs",
            description="Exports UVs and Reference external image files to be used by the model",
            default=True)
        CopyTextureFiles = BoolProperty(
            name="Copy Textures Files",
            description="Copy referenced Textures files in the models\\textures directory",
            default=True)
        ExportArmatures = BoolProperty(
            name="Export Armatures",
            description="Export the bones of any armatures to deform meshes",
            default=True)
    
        ExportAnimationFrames = EnumProperty(
            name="Animations Frames",
    
            description="Select the type of animations to export. Only object " \
    
                        "and armature bone animations can be exported. Keyframes exports only the keyed frames" \
                        "Full Animation exports every frames, None disables animationq export. ",
            items=AnimationFrameModes,
    
        ExportAnimationActions = EnumProperty(
            name="Animations Actions",
            description="By default only the Default Animation Action assoiated to an armature is exported." \
                        "However if you have defined several animations on the same armature,"\
                        "you can select to export all animations. You can see the list of animation actions in the DopeSheet window.",
            items=AnimationActions,
    
        AnimFPS = IntProperty(
            name="Animation FPS",
            description="Frame rate used to export animation in seconds (can be used to artficially slow down the exported animation, or to speed up it",
    
            default=30, min=1, max=300)
    
    
        #Advance Options
        CoordinateSystem = EnumProperty(
            name="System",
            description="Select a coordinate system to export to",
            items=CoordinateSystems,
            default="1")
    
        Verbose = BoolProperty(
            name="Verbose",
            description="Run the exporter in debug mode. Check the console for output",
            default=True)
    
        def execute(self, context):
            #Append .group
            FilePath = bpy.path.ensure_ext(self.filepath, ".group")
    
            Config = MarmaladeExporterSettings(context,
                                             FilePath,
                                             CoordinateSystem=self.CoordinateSystem,
                                             FlipNormals=self.FlipNormals,
                                             ApplyModifiers=self.ApplyModifiers,
                                             Scale=self.Scale,
                                             AnimFPS=self.AnimFPS,
                                             ExportVertexColors=self.ExportVertexColors,
                                             ExportMaterialColors=self.ExportMaterialColors,
                                             ExportTextures=self.ExportTextures,
                                             CopyTextureFiles=self.CopyTextureFiles,
                                             ExportArmatures=self.ExportArmatures,
    
                                             ExportAnimationFrames=self.ExportAnimationFrames,
                                             ExportAnimationActions=self.ExportAnimationActions,
    
                                             ExportMode=self.ExportMode,
                                             MergeModes=self.MergeModes,
                                             Verbose=self.Verbose)
    
            # Exit edit mode before exporting, so current object states are exported properly.
            if bpy.ops.object.mode_set.poll():
                bpy.ops.object.mode_set(mode='OBJECT')
    
            ExportMadeWithMarmaladeGroup(Config)
    
    
        def invoke(self, context, event):
            if not self.filepath:
                self.filepath = bpy.path.ensure_ext(bpy.data.filepath, ".group")
            WindowManager = context.window_manager
            WindowManager.fileselect_add(self)
    
    
    
    def menu_func(self, context):
        self.layout.operator(MarmaladeExporter.bl_idname, text="Marmalade cross-platform Apps (.group)")
    
    
    def register():
        bpy.utils.register_module(__name__)
    
        bpy.types.INFO_MT_file_export.append(menu_func)
    
    
    def unregister():
        bpy.utils.unregister_module(__name__)
    
        bpy.types.INFO_MT_file_export.remove(menu_func)
    
    
    if __name__ == "__main__":
        register()