Drivers And Space Switches¶
A driver connects a node of one component to something else, usually another component, after every component has been built. Drivers are stored on the definition of the component which is driven.
The examples on this page are real files in docs/source/examplecode/hivedrivers/, the unit tests run them.
Driver Types¶
Type |
Constant |
Use |
|---|---|---|
|
|
A control which the animator can make follow different nodes, an enum on the control panel. |
|
|
Fixed constraint, the driven node follows one or more nodes. |
|
|
Connects one attribute to another, optionally through a multiplier the animator can edit. |
|
|
Advanced. Blends the motion of other nodes into the driven attributes with weights and multipliers,
used by the face components. See |
Every driver has a label which is unique in the component. enabled False keeps the driver in the definition
but doesn’t build it.
Path Expressions¶
Drivers refer to nodes with path expressions instead of names or python objects, that way they survive renaming, saving to templates and rebuilds.
Expression |
Meaning |
|---|---|
|
The rig layer node with id |
|
The input node of this component, what the parent component drives. |
|
A node of another component, |
|
Space switches only. Resolves to no node, the choice means the control keeps inheriting from its parent in the
hierarchy, as it would with no space switch. Built in components use it for their |
Create them with api.pathAsDefExpression(("self", "rigLayer", "endik")) or ask
component.connectables() which nodes a component allows to connect.
Note
Changing a definition doesn’t touch the scene. Make the change, then rebuild the rig
(rig.buildRigs()). Drivers are created at the end of the rig build, so they can reference any built component.
Space Switches¶
A space switch makes a control follow one of several drivers, for example an IK hand which follows the shoulder, the world or a prop. Hive builds the enum attribute on the control panel, the constraint, and it publishes the attribute to the container.
Many Hive components come with space switches, armcomponent has ikSpace, fkSpace and poleVectorSpace.
The built in choices are protected, code and riggers can add choices but can’t remove or rename the built in ones.
{
"type": "spaceSwitch",
"label": "ikSpace",
"enabled": true,
"params": {
"type": "parent",
"driven": "@{self.rigLayer.endik}",
"controlPanelFilter": {
"default": "world",
"group": {"label": "Space", "name": "__", "insertAfter": "lock"}
},
"permissions": {"allowRename": false, "allowDriverChange": true, "value": true},
"drivers": [
{"label": "parent", "driver": "@{self.inputLayer.upr}",
"permissions": {"allowDriverChange": false, "allowRename": false, "value": true}},
{"label": "world", "driver": "@{self.inputLayer.world}",
"permissions": {"allowDriverChange": false, "allowRename": false, "value": true}}
]
}
}
typeis the constraint type:parent,orient,point,scale,aimormatrix.controlPanelFilter.defaultis the driver which is active after the build.controlPanelFilter.groupputs a title above the attribute in the channel box. The groupnamemust be unique in the control panel.permissionsprotect the space,value: truemeans it is protected.
Listing Space Switches¶
Before a build the definition is the source of truth, after a build the scene is.
def spaceSwitches(component):
"""Returns ``{spaceLabel: [driverLabel, ...]}`` for every space switch in the component definition.
The definition is the source of truth before a build, it doesn't need a rig in the scene.
"""
return {driver.label: [i.label for i in driver.params.drivers]
for driver in component.definition.drivers
if driver.type == api.constants.DRIVER_TYPE_SPACE_SWITCH}
def sceneSpaceSwitches(component):
"""Returns ``{attributeName: [driverLabel, ...]}`` for the space switches built in the scene."""
return {constraint.controllerAttrName().split(".")[-1]: [label for label, _ in constraint.drivers()]
for constraint in component.rigLayer().spaceSwitches()}
Adding A Choice To A Space Switch¶
def addDriverToSpace(component, spaceLabel, driverLabel, driverExpression):
"""Adds a new choice to a space switch the component already has, the built in choices are kept.
:param component: The component which owns the space switch.
:type component: :class:`api.Component`
:param spaceLabel: The space label eg. "ikSpace".
:param driverLabel: The label shown in the enum for the new choice.
:param driverExpression: A hive path expression to the node to follow eg. "@{prop:M.rigLayer.fk00}".
:rtype: :class:`api.SpaceSwitchDriverDefinition`
"""
space = component.definition.driver(spaceLabel)
return space.params.createDriver({"label": driverLabel, "driver": driverExpression})
Creating A Space Switch¶
def createSpace(component, label, drivenExpression, constraintType, drivers, default=None):
"""Creates a new space switch on a component.
:param label: The unique space label, this becomes the attribute name on the control panel.
:param drivenExpression: Path expression to the driven node eg. "@{self.rigLayer.uprfk}".
:param constraintType: "parent", "orient", "point", "scale", "aim" or "matrix".
:param drivers: A list of ``(label, expression)``. The first is the default unless ``default`` is given.
:param default: The driver label which is active when the rig is built.
:rtype: :class:`api.DriverDef`
"""
default = default or drivers[0][0]
return component.definition.createSpaceSwitch(
label, drivenExpression, constraintType,
# the group puts a title above the attribute in the channel box, name must be unique in the control panel
{"default": default, "group": {"label": "", "name": "", "insertAfter": ""}, "insertAfter": ""},
{},
[{"label": driverLabel, "driver": expr} for driverLabel, expr in drivers])
Switching Space¶
The enum on its own moves the control, so switch and then put the control back where it was. This is what the Hive marking menu does.
def switchSpace(component, spaceLabel, driverLabel, keepPose=True):
"""Changes the active driver of a built space switch.
Setting the enum on its own moves the control, the pose is what the animator cares about so
the world matrix is put back afterwards, this is what the Hive marking menu does.
:param component: The built component.
:param spaceLabel: The space label eg. "ikSpace".
:param driverLabel: The label of the driver to switch to.
:param keepPose: Match the driven control to where it was before the switch.
:return: True if the space was switched.
:rtype: bool
"""
for constraint in component.rigLayer().spaceSwitches():
if constraint.controllerAttrName().split(".")[-1] != spaceLabel:
continue
labels = [label for label, _ in constraint.drivers()]
if driverLabel not in labels:
return False
# the srt is the driven node of the constraint, the control below it is what the animator moves
control = component.rigLayer().controlForSrt(constraint.driven())
matrix = control.worldMatrix()
# the name is a variable so use attribute(), everywhere else attributes are read with dot access
component.controlPanel().attribute(spaceLabel).set(labels.index(driverLabel))
if keepPose:
control.setWorldMatrix(matrix)
return True
return False
Putting it together:
def demo():
"""Extends a built in space, adds a new one, builds, then switches. Returns what happened."""
rig, godnode, arm, prop = createCharacter()
result = {"before": spaceSwitches(arm)}
addDriverToSpace(arm, "ikSpace", "prop", "@{prop:M.rigLayer.fk00}")
createSpace(arm, "fkFollow", "@{self.rigLayer.uprfk}", "orient",
[("parent", "@{inherit}"), ("god", "@{godnode:M.rigLayer.godnode}")])
result["after"] = spaceSwitches(arm)
rig.buildRigs()
result["scene"] = sceneSpaceSwitches(arm)
result["default"] = arm.controlPanel().ikSpace.value()
control = arm.rigLayer().control("endik")
before = control.worldMatrix()
result["switched"] = switchSpace(arm, "ikSpace", "prop")
result["value"] = arm.controlPanel().ikSpace.value()
result["poseKept"] = _matricesMatch(before, control.worldMatrix())
# the control now follows the prop
propControl = prop.rigLayer().control("fk00")
followed = control.worldMatrix()
cmds.xform(propControl.fullPathName(), translation=(0, 9, 0), worldSpace=True)
result["follows"] = not _matricesMatch(followed, control.worldMatrix())
result["rig"] = rig
return result
Space Switches In A Component Definition¶
Space switches which ship with a component are declared in its definition,
definition.createSpaceSwitch(...) in createwheeldefinition.py of the
custom component example is a complete one.
Direct Drivers¶
A direct driver connects an attribute to an attribute. With expression a multiplier is built and its value is
added to the control panel for the animator to change.
def driveRotationFromTranslation(component, driverExpression, multiplier=1.0):
"""Connects a driver attribute to a driven attribute, scaled by an attribute the animator can change.
The component gets a new ``dialMultiplier`` attribute on its control panel. The connection is made
on a new srt above the driven control, the animator's channels stay free for animation.
:param component: The component which is driven.
:param driverExpression: Path expression of the node which is read.
:param multiplier: Default value of the multiplier attribute.
:rtype: :class:`api.DriverDef`
"""
return component.definition.createDriver(
api.constants.DRIVER_TYPE_DIRECT,
"dialFromGod",
{
"driver": driverExpression,
"driverAttribute": "translateX",
"driven": "@{self.rigLayer.fk00}",
"drivenAttribute": "rotateZ",
# createSrt True builds the connection on a new srt buffer instead of the animation control
"createSrt": True,
# optional, adds a multiply between the two attributes with the value exposed on the control panel
"expression": {"type": 0, "invert": False,
"attr": {"name": "dialMultiplier", "Type": zapi.attrtypes.kMFnNumericFloat,
"value": multiplier, "default": multiplier, "min": -100.0, "max": 100.0,
"keyable": True, "channelBox": True}},
})
createSrt builds the connection on a new srt buffer above the control. The channels of the control stay free so an
animator can keyframe the control on top of the driver.
Matrix Drivers¶
def followWithMatrixConstraint(component, drivers, drivenExpression="@{self.rigLayer.fk00}", maintainOffset=True):
"""Constrains a node to one or more nodes with a matrix constraint.
The most robust way to follow other nodes, there are no constraint nodes with cycle issues and scene
files open without Zoo Tools loaded.
:param drivers: A list of ``(label, expression)``, with more than one they are blended equally.
:param maintainOffset: Keep the current offset between the driven and the drivers.
:rtype: :class:`api.DriverDef`
"""
return component.definition.createDriver(
api.constants.DRIVER_TYPE_MATRIX,
"followGod",
{"drivers": [list(i) for i in drivers], "driven": drivenExpression,
"maintainOffset": maintainOffset, "createSrt": True})
Matrix constraints are the most robust way of following a node, they add no constraint nodes with evaluation cycles and the scene opens without Zoo Tools loaded. With more than one driver the transforms are blended equally.
Enabling And Disabling¶
def disableDriver(component, label):
"""Turns a driver off without deleting it, it isn't built until it is enabled again."""
driver = component.definition.driver(label)
driver.enabled = False
return driver
Removing Drivers¶
# remove a whole driver
component.definition.removeDriver("followGod")
# or several at once
component.definition.removeDrivers(["dialFromGod", "followGod"])
# remove one choice of a space switch
component.definition.driver("ikSpace").params.removeDriver("prop")
The last one raises ValueError for the protected choices which ship with a component.
Full Example Files¶
def demoDirect():
"""Rotate a dial when the god node moves along x. Returns the rotation for a translation of 5."""
rig, godnode, dial = createRigWithDial()
driveRotationFromTranslation(dial, "@{godnode:M.rigLayer.godnode}", multiplier=2.0)
rig.buildRigs()
godControl = godnode.rigLayer().control("godnode")
dialControl = dial.rigLayer().control("fk00")
godControl.translateX.set(5.0)
# srts are listed in creation order, the srt the driver created is the last one. Angle plugs return a maya angle.
driverSrt = list(dialControl.iterSrts())[-1]
rotation = driverSrt.rotateZ.value().asDegrees()
return {"rig": rig, "rotateZ": rotation, "panel": dial.controlPanel().dialMultiplier.value()}
def demoMatrix():
"""A prop which follows the god node, returns where the prop is after the god node moved."""
rig, godnode, dial = createRigWithDial()
followWithMatrixConstraint(dial, [("god", "@{godnode:M.rigLayer.godnode}")])
rig.buildRigs()
before = dial.rigLayer().control("fk00").translation(zapi.kWorldSpace)
godnode.rigLayer().control("godnode").translateX.set(3.0)
after = dial.rigLayer().control("fk00").translation(zapi.kWorldSpace)
return {"rig": rig, "moved": after.x - before.x}