Skip to content

Instantly share code, notes, and snippets.

@pcote
Created September 2, 2012 02:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcote/3594354 to your computer and use it in GitHub Desktop.
Save pcote/3594354 to your computer and use it in GitHub Desktop.
Blender test script that swaps pairs of selected keyframe points.
import bpy
from pdb import set_trace
# quick handy little lambdas
first = lambda l : l[0]
last = lambda l : l[-1]
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i+n]
def swap_ys(p1, p2):
p1.co.y, p2.co.y = p2.co.y, p1.co.y
ob = bpy.context.object
fcurves = ob.animation_data.action.fcurves
fcrv = last([c for c in fcurves if c.select])
kps = fcrv.keyframe_points
kps = [kp for kp in kps if kp.select_control_point]
kps_pairs = list(chunks(kps, 2))
kps_pairs = filter(lambda l: len(l)>1, kps_pairs)
def swap_pair(pair):
def get_handle_diff(pt):
left_diff = pt.handle_left.y - pt.co.y
right_diff = pt.handle_right.y - pt.co.y
return left_diff, right_diff
# get the handle relative diff in advance before swapping
left_diff_0, right_diff_0 = get_handle_diff(pair[0])
left_diff_1, right_diff_1 = get_handle_diff(pair[1])
# do the coordinate swap
y1, y2 = pair[0].co.y, pair[1].co.y
pair[0].co.y, pair[1].co.y = y2, y1
# update the handles
pair[0].handle_left.y = pair[0].co.y + left_diff_0
pair[0].handle_right.y = pair[0].co.y + right_diff_0
pair[1].handle_left.y = pair[1].co.y + left_diff_1
pair[1].handle_right.y = pair[1].co.y + right_diff_1
for pair in kps_pairs:
swap_pair(pair)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment