Untitled

 avatar
unknown
python
a month ago
3.2 kB
5
Indexable
import bpy
import re
import os

# File location
file_path = r"C:\Users\User\sequence.txt"

# Reading the file
with open(file_path, "r") as file:
    data = file.read()

# Extracting all actions from the file (extracting only the final action name)
actions = re.findall(r'normal/.*/(.*?)\.inf\s*{[^}]*"startframe"\s*"(\d+)"[^}]*"duration"\s*"(\d+)"', data)

if not actions:
    raise ValueError("No actions were found in the file.")

# Total number of actions
total_actions = len(actions)

# Ensure an armature is selected
if not (bpy.context.object and bpy.context.object.type == 'ARMATURE'):
    raise ValueError("Select an armature before running the script.")

obj = bpy.context.object

if not (obj.animation_data and obj.animation_data.action):
    raise ValueError("No action exists on the selected armature.")

original_action = obj.animation_data.action

# Export folder for FBX files
export_dir = r"C:\Users\user\exports"
os.makedirs(export_dir, exist_ok=True)

# Processing all actions
for i, (action_name, start_frame, duration) in enumerate(actions):
    start_frame = int(start_frame)
    duration = int(duration)
    end_frame = start_frame + duration - 1  # Ignoring the last frame

    # Duplicate the action
    new_action = original_action.copy()
    new_action.name = action_name
    new_action.use_fake_user = True  # Keep the action even without a direct connection to the object
    obj.animation_data.action = new_action

    # Keep only the keyframes within the required range
    for fcurve in new_action.fcurves:
        keyframes = [kp for kp in fcurve.keyframe_points if start_frame <= kp.co[0] <= end_frame]

        # Clear all keyframes
        fcurve.keyframe_points.clear()

        # Add only the keyframes within the range
        for kp in keyframes:
            new_time = kp.co[0] - start_frame + 1  # Shift the start frame to 1
            fcurve.keyframe_points.insert(new_time, kp.co[1])

    # Bake the animation
    bpy.context.scene.frame_start = 1
    bpy.context.scene.frame_end = duration
    bpy.ops.nla.bake(
        frame_start=1,
        frame_end=duration,
        only_selected=False,  # Bake all objects
        visual_keying=True,   # Bake visual data
        clear_constraints=False,
        clear_parents=False,
        bake_types={'POSE'}   # Bake pose animation
    )

    # Export FBX file
    export_path = os.path.join(export_dir, f"{action_name}.fbx")
    bpy.ops.export_scene.fbx(
        filepath=export_path,
        use_selection=False,  # Export all items in the scene
        bake_anim=True,       # Bake animation
        bake_anim_force_startend_keying=True,  # Force keyframes at start and end
        bake_anim_simplify_factor=0.0,        # No simplification of keyframes
        add_leaf_bones=False,
        apply_unit_scale=True
    )

    # Print progress percentage
    progress = (i + 1) / total_actions * 100
    print(f"Action {i + 1}/{total_actions}: '{action_name}' created and saved as FBX. Progress: {progress:.2f}%")

print("All actions were successfully completed and saved as FBX files!")
Leave a Comment