Newer
Older
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)
CoDEmanX
committed
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")
CoDEmanX
committed
WriteArmatureChildBones(Config, Object, Bone.children, skelFile)
def WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, File, isRestPoseNotAnimPose):
CoDEmanX
committed
# Compute armature scale :
# 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
CoDEmanX
committed
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
CoDEmanX
committed
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)
CoDEmanX
committed
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))
if isRestPoseNotAnimPose:
File.write("\t}\n")
CoDEmanX
committed
def WriteKeyedAnimationSet(Config, Scene):
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:
CoDEmanX
committed
actions = bpy.data.actions[:]
DefaultAction = Object.animation_data.action
CoDEmanX
committed
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))
CoDEmanX
committed
#Object animated (aka single bone object)
#build key frame time list
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
Benoit Muller
committed
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
## ensure_dir(animfullname)
## if Config.Verbose:
## print(" Creating anim file (single bone animation) %s" % (animfullname))
## animFile = open(animfullname, "w")
CoDEmanX
committed
## 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:
CoDEmanX
committed
## #Scene.frame_set(KeyframeTime)
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
## 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
CoDEmanX
committed
#riged bones animated
#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
Benoit Muller
committed
keyframeTimes.update(range(Scene.frame_start, Scene.frame_end + 1, 1))
CoDEmanX
committed
keyframeTimes = list(keyframeTimes)
keyframeTimes.sort()
Benoit Muller
committed
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")
CoDEmanX
committed
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
CoDEmanX
committed
################## Utilities
CoDEmanX
committed
def StripBoneName(name):
return name.replace(" ", "")
def StripName(Name):
CoDEmanX
committed
def ReplaceSet(String, OldSet, NewChar):
for OldChar in OldSet:
String = String.replace(OldChar, NewChar)
return String
CoDEmanX
committed
CoDEmanX
committed
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)
CoDEmanX
committed
def CloseFile(Config):
if Config.Verbose:
print("Closing File...")
Config.File.close()
if Config.Verbose:
print("Done")
CoordinateSystems = (
("1", "Left-Handed", ""),
("2", "Right-Handed", ""),
)
AnimationFrameModes = (
("0", "None", ""),
("1", "Keyframes Only", ""),
("2", "Full Animation", ""),
)
AnimationActions = (
("0", "Default Animation", ""),
("1", "All Animations", ""),
)
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
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')
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")
CoDEmanX
committed
name="Scale Percent",
description="Scale percentage applied for export",
default=100, min=1, max=1000)
CoDEmanX
committed
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,
CoDEmanX
committed
default="0")
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)
CoordinateSystem: EnumProperty(
name="System",
description="Select a coordinate system to export to",
items=CoordinateSystems,
default="1")
CoDEmanX
committed
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)
Sebastian Nell
committed
return {'FINISHED'}
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)
Sebastian Nell
committed
return {'RUNNING_MODAL'}
def menu_func(self, context):
self.layout.operator(MarmaladeExporter.bl_idname, text="Marmalade cross-platform Apps (.group)")
def register():
bpy.utils.register_module(__name__)
Brecht Van Lommel
committed
bpy.types.TOPBAR_MT_file_export.append(menu_func)
def unregister():
bpy.utils.unregister_module(__name__)
Brecht Van Lommel
committed
bpy.types.TOPBAR_MT_file_export.remove(menu_func)
if __name__ == "__main__":
register()