Skip to content

Instantly share code, notes, and snippets.

@defTechAndrew
Created April 1, 2019 22:01
Show Gist options
  • Save defTechAndrew/e4abbf6453581653ad234cf7d5716653 to your computer and use it in GitHub Desktop.
Save defTechAndrew/e4abbf6453581653ad234cf7d5716653 to your computer and use it in GitHub Desktop.
Here are some useful calls I've developed for editing FBX animation files using the Python FBX SDK.
import FbxCommon
def fbx_trim_keys(scene, start, end, take_buffer=10):
"""
Uses the FBX SDK to remove unnecessary keys.
:param scene: FBX SDK scene class that hold data to edit
:param int start: start frame of animation keys to keep
:param int end: end frame of animation keys to keep
:param int take_buffer: number of frames to keep as head and tail of clip
"""
# Get animation stack and associated layer
stack = scene.GetCurrentAnimationStack()
layer = stack.GetSrcObject()
# Build FbxTimeSpan class for keys that should be saved
anim_start = FbxCommon.FbxTime()
anim_start.SetFrame(start - take_buffer)
anim_end = FbxCommon.FbxTime()
anim_end.SetFrame(end + take_buffer)
anim_range = FbxCommon.FbxTimeSpan(anim_start, anim_end)
# Iterate through all animation nodes in the layer
for l in range(layer.GetMemberCount()):
anim_node = layer.GetMember(l)
# Check node has keys
if anim_node.IsAnimated():
# Each node has a curve for every animated attribute
for c in range(anim_node.GetChannelsCount()):
anim_curve = anim_node.GetCurve(c)
anim_curve.KeyModifyBegin()
# Iterate though every key on a given curve
for k in reversed(range(anim_curve.KeyGetCount())):
key_time = anim_curve.KeyGetTime(k)
# Check if key's time is not inside the range to save
if not anim_range.IsInside(key_time):
anim_curve.KeyRemove(k)
anim_curve.KeyModifyEnd()
def fbx_name_take(scene, name):
"""
Maya's FBX plug-in is limited in how it allows you to name take. Using the FBX SDK we can pass a custom string.
:param scene: FBX SDK scene class that holds take to rename
:param unicode name: name for animation take
"""
stack = scene.GetCurrentAnimationStack()
stack.SetName(name)
# Example
animFilePath = "C:\\Users\\andrewc\\Desktop\\test.fbx"
manager, scene = FbxCommon.InitializeSdkObjects()
result = FbxCommon.LoadScene(manager, scene, animFilePath)
fbx_trim_keys(scene, 30, 60)
fbx_name_take(scene, 'SuperCoolAnim')
FbxCommon.SaveScene(manager, scene, animFilePath)
@juaneloDev
Copy link

juaneloDev commented Jun 11, 2022

Do you know in what way it would be possible to use this to actually clip the timeline ranges for the exported file? (as opposed to saving them to 'takes'). More specifically, exporting each take as a separate .fbx file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment