How to add a FCurveModifier to a FCurve via Python script?

Hi,
I’m using Blender 2.59, I have an object with an IPO Curve and two keyframes on the ‘Rotation’ channel, I’d like to add a ‘Cycles’ FCurveModifier to the selected ipo curve (roation_euler[2], the RotZ channel)… and I can’t.

“bpy.ops.graph.fmodifier_add(type=‘CYCLES’, only_active=True)” doesn’t work (“RuntimeError: Operator bpy.ops.graph.fmodifier_add.poll() failed, context is incorrect”, I don’t know how to fix it - if possible).

I’m sorry for my bad English :frowning:
Thank you very much!

Hi redbaron85,

In my experience, using the bpy.ops operators can cause some problems because of the context issues that you’re experiencing. For that reason I often edit the data directly, it may not look as nice but it gives more control. So here goes for your situation:


import bpy

# Get the object
ob = bpy.context.active_object

# Get all the fcurves related to the z rotation
fcurves = [f for f in ob.animation_data.action.fcurves if f.data_path == 'rotation_euler' and f.array_index == 2]

# Use only the first found
fcu = fcurves[0]

# Add the modifier
mod = fcu.modifiers.new(type='CYCLES')

# Edit some modifier settings
mod.cycles_before = 1
mod.cycles_after = 5

This is a pretty basic example and it can break if there are already modifiers on the fcurve. Hope this helps.

Cheers,
Truman

Hi TrumanBlending,
well… IT WORKS!!! :smiley:

Thank you! Thank you very much!! :wink:

Cheers,
— Francesco