"clamp" in python expression

Hello everyone,

I’m trying to “convert” myself from my maya usage and get more into blender. So I’ve come to the part when I need to make expression. I’ve learned simple stuff like

ob(“Cube.001”).LocY

So that Cube.001.LocY will be the driver of whatever parameter I chose to use it on. So far so good.
But I would like to be able to use a expression that I use in Maya all the time when I do my rigging, which is a clamp function. And I haven’t found yet in any document on how to do it.

Ex. Formula for the clamp
clamp( lowvalue, highvalue, driver )

Ex. in a maya expression
Face.JawOpen = clamp(-0.3, 1, Sync.TranslateY)

The above would force the blendshape “jawOpen” to go between -0.3 and 1 but no further. So… how would I go about to create this in Blender? And if you are wondering, I’m using the “osipa way” of doing my facial rigs :slight_smile:

best regards
stefan andersson

About the clamping: I can think of two ways of doing this in python, though they aren’t as elegant as the Maya way.

  1. Check if the value needs to be clamped and if so do it customily. (bit of an ugly solution)

Face.JawOpen = Sync.TranslateY
if (Face.JawOpen < -0.3): Face.JawOpen = -0.3
elif (Face.JawOpen > 1): Face.JawOpen = 1

  1. Create a custom clamp function. (more elegant, and certainly the way to go if you need to clamp values more often)

def clamp(lowvalue, highvalue, driver):
  if driver < lowvalue: driver = lowvalue
  elif driver > highvalue: driver = highvalue
  return driver

Face.JawOpen = clamp(-0.3, 1, Sync.TranslateY)

This was the easy part however. To apply this to shapekeys, I advise you do some research on pydrivers.

Here’s a quick rundown of the steps you’ll need to take:
Create the shapekey you’re going to need.
Go to the Ipo Curve Editor window
For Ipo type select ‘shape’
Select your shapekey
Press n-key
Press the snake button to use a one-line python expression as a driver
Write your driver

Short note: to overcome the restrictions of being able to use only 1 line, look here.

I hope that helps you a bit. Feel free to ask questions if anything isn’t clear.

ETA: here is an example .blend file, with the final result.