Writing A Custom Component

This tutorial writes a complete component, a wheel. It is small enough to read in one sitting and uses everything a real component needs:

  • Guides, guide settings, inputs, outputs and a skinning joint, described in a definition file.

  • A control the animator moves and a roll which follows the distance it travels, built from plain maya nodes.

  • Animator attributes on the control panel.

  • A space switch.

  • Parenting to other components.

The files are in docs/source/examplecode/customcomponent/ and the unit tests build them, so the tutorial is known to work.

File

Purpose

createwheeldefinition.py

Builds the definition with the definition API and writes wheelcomponent.definition.

wheelcomponent.definition

The generated definition, what Hive loads.

wheelcomponent.py

The component class, builds the rig from the definition.

registerwheel.py

Makes Hive discover the folder.

buildwheelscene.py

A mayapy script which builds and saves a wheel scene, wheelrig.ma is its output.

wheelrig.ma

The finished scene, open it to see the result.

How A Component Works

How a component is put togetherA component has a python class and a definition file. The registry finds both by the definition name, and creating a component makes an instance with a working copy of the definition and scene nodes. Class wheelcomponent.py definitionName = "wheelcomponent" builds the nodes Definition file wheelcomponent.definition "type": "wheelcomponent" the data Component registry HIVE_COMPONENT_PATH HIVE_DEFINITIONS_PATH matches the two by name createComponent Component instance Working definition a copy, edited by code Original definition the file, to see what changed Meta node the scene side, stores the definition Layers guide, input, deform, output and rig created by the build stages Unique to each component idMapping(): which ids belong together in every layer connectables(): what others may connect to setupRig(), postSetupRig(): what the definition can't say

Two files describe a component, a definition and a class. The definition is data: the guides, IO nodes, joints, settings and drivers. The class is behaviour: what is built from the data at each build stage. Hive creates every node in the definition for you, the class only builds what the definition can’t say, the controls, the constraints, the utility nodes.

Guides, inputs, outputs and joints are matched by id. The wheel guide, the wheel joint, the wheel output and the wheel control all have the id wheel, that is how Hive moves constraints between build stages when a rigger parents components. See Unique Identifiers.

The Build Stages

The build stagesA rig is built in four stages. Guides, skeleton, rig and polish, each creates its own layer and runs its own component methods. Every stage reads the scene back into the definition first. 1 Guides rig.buildGuides() the rigger places guides and edits the settings Creates, and runs Guide layer: guides, guide settings preSetupGuide setupGuide postSetupGuide 2 Skeleton rig.buildDeform() joints and the ins and outs between components Creates, and runs Input layer Deform layer: joints Output layer setupInputs setupDeformLayer setupOutputs postSetupDeform 3 Rig rig.buildRigs() animation controls, control panel and constraints Creates, and runs Rig layer: controls, control panel preSetupRig setupRig postSetupRig then every driver 4 Polish rig.polish() clean up for the animator Creates, and runs guides deleted layers hidden controls published to the container prePolish polish postPolish Every stage starts by reading the scene back into the definition so what a rigger changed by hand always wins, and the stage ends by saving the definition to the scene. Components are built parents first, drivers are created once every component has its rig.

The class methods run in this order, override only what the component needs and always call super() unless the base behaviour is being replaced.

Method

Called

preSetupGuide / setupGuide / postSetupGuide

While building guides. Change the definition here to match guide settings (fk chain does for jointCount).

setupInputs / setupOutputs

Positions the IO nodes, the definition already created them.

setupDeformLayer / postSetupDeform

While building the skeleton, the joints come from the definition.

setupRig

Creates controls and the nodes between them.

postSetupRig

Binds the rig to the outputs and the joints. Use this stage, every node exists.

setupDrivers

Called by Hive, after every component was built. Not overridden.

Step 1, The Definition

Writing the definition JSON by hand doesn’t scale. Build it with the definition API and serialize it once, rerun the script whenever the design changes.

def createDefinition():
    """Builds the wheel component definition.

    :return: The definition with every guide, input, output, joint, setting and driver of the component.
    :rtype: :class:`api.ComponentDefinition`
    """
    definition = api.ComponentDefinition.fromData({"name": "wheel", "side": "M", "type": COMPONENT_TYPE,
                                                   "version": "1.0.0"})
    # Guides: the "root" guide moves the whole component, "wheel" is the hub of the wheel and the only guide
    # which becomes a joint. The srts are the transforms above each guide, parenting constrains them.
    # Ids never change, code always finds nodes by id and never by name.
    guideLayer = definition.guideLayer
    guideLayer.createGuide(id="root", name="root", parent=None, shape="cube_bounding",
                           pivotShape="cube_bounding", pivotColor=(0.8, 0.0, 0.0),
                           translate=(0.0, 0.0, 0.0), rotate=(0.0, 0.0, 0.0, 1.0),
                           srts=[{"name": "root_guide_srt"}])
    guideLayer.createGuide(id="wheel", name="wheel", parent="root", shape="circle",
                           pivotShape="sphere_arrow", pivotColor=(1.0, 1.0, 0.0),
                           translate=(0.0, 1.0, 0.0), rotate=(0.0, 0.0, 0.0, 1.0), rotateOrder=0,
                           srts=[{"name": "wheel_guide_srt"}])
    # Guide settings are exposed to the rigger in the guide settings UI and are readable at build time.
    guideLayer.addGuideSetting(api.AttributeDefinition(name="radius", Type=zapi.attrtypes.kMFnNumericFloat,
                                                       value=1.0, default=1.0, min=0.001, channelBox=True))
    # The axis of the axle the wheel spins around, the component reads it when it builds the roll.
    guideLayer.addGuideSetting(api.AttributeDefinition(name="spinAxis", Type=zapi.attrtypes.kMFnkEnumAttribute,
                                                       enums=mayamath.AXIS_NAMES, value=mayamath.XAXIS, default=mayamath.XAXIS,
                                                       channelBox=True))

    # Inputs are how other components (the parent) drive this one. The "root" input is the primary input
    # which the parent component drives, "world" is a spare which space switches can use.
    inputLayer = definition.inputLayer
    inputLayer.createInput(id="parent", name="parent_in", root=True, translate=(0.0, 1.0, 0.0),
                           rotate=(0.0, 0.0, 0.0, 1.0))
    inputLayer.createInput(id="world", name="world_in", root=False, translate=(0.0, 0.0, 0.0),
                           rotate=(0.0, 0.0, 0.0, 1.0))
    # Outputs are how child components attach to this one.
    definition.outputLayer.createOutput(id="wheel", name="wheel_out", translate=(0.0, 1.0, 0.0),
                                        rotate=(0.0, 0.0, 0.0, 1.0))
    # The only skinning joint.
    definition.deformLayer.createJoint(id="wheel", name="wheel_srt", translate=(0.0, 1.0, 0.0),
                                       rotate=(0.0, 0.0, 0.0, 1.0), rotateOrder=0)
    # Anim attributes live on the control panel, the only settings node the animator sees.
    rigLayer = definition.rigLayer
    rigLayer.addSetting(api.constants.CONTROL_PANEL_TYPE, name="autoRoll", Type=zapi.attrtypes.kMFnNumericFloat,
                        value=1.0, default=1.0, min=0.0, max=1.0, keyable=True, channelBox=False)
    rigLayer.addSetting(api.constants.CONTROL_PANEL_TYPE, name="rollMultiplier", Type=zapi.attrtypes.kMFnNumericFloat,
                        value=1.0, default=1.0, softMin=-5.0, softMax=5.0, keyable=True, channelBox=False)
    # Which world axis the wheel rolls along, 0 is z (forward in maya) and 1 is x.
    rigLayer.addSetting(api.constants.CONTROL_PANEL_TYPE, name="rollAxis", Type=zapi.attrtypes.kMFnkEnumAttribute,
                        enums=["Z", "X"], value=0, default=0, keyable=True, channelBox=False)
    # The wheel control can follow the parent component or stay in world space.
    definition.createSpaceSwitch(
        "wheelSpace", "@{self.rigLayer.wheel}", "parent",
        {"default": "parent", "group": {"label": "Space", "name": "__", "insertAfter": ""}, "insertAfter": ""},
        {"allowRename": False, "allowDriverChange": True, "value": True},
        [{"label": "parent", "driver": "@{self.inputLayer.parent}",
          "permissions": {"allowRename": False, "allowDriverChange": False, "value": True}},
         {"label": "world", "driver": "@{self.inputLayer.world}",
          "permissions": {"allowRename": False, "allowDriverChange": False, "value": True}}])
    return definition
def save(path=DEFINITION_PATH):
    """Serializes the definition to disk.

    :param path: The file path to write.
    :type path: str
    :return: The path written.
    :rtype: str
    """
    definition = createDefinition()
    # serialize() diffs against the original, there is none for a brand new component.
    filesystem.saveJson(definition.serialize(api.ComponentDefinition.fromData({})), path, indent=4, sort_keys=True)
    return path

Run it with Maya and Zoo Tools loaded to write wheelcomponent.definition next to the script.

Note

"type" in the definition is what links it to the class, it must equal definitionName of the class.

Tip

Prototype in a scene first. Build the guides and settings with the rig API, call component.serializeFromScene() and use the result as the starting point of the definition.

Step 2, The Class

Identity

    creator = "Zoo Tools"
    # must match the "type" key of the definition file
    definitionName = "wheelcomponent"
    uiData = {"icon": "circle", "iconColor": (), "displayName": "Wheel"}
    documentation = "A wheel which rolls automatically when it moves along the forward axis."

definitionName must match the type of the definition. uiData sets the name and icon in the artist UI.

Id Mapping

    def idMapping(self):
        """Ties every node id in a layer to the ids of the nodes in other layers, hive uses this to move
        constraints between the guide, rig and skeleton stages.
        """
        return {
            api.constants.DEFORM_LAYER_TYPE: {"wheel": ("wheel",)},
            api.constants.INPUT_LAYER_TYPE: {"wheel": ("parent",)},
            api.constants.OUTPUT_LAYER_TYPE: {"wheel": ("wheel",)},
            api.constants.RIG_LAYER_TYPE: {"wheel": ("wheel",)},
            api.constants.ORDER_TYPE: {
                api.constants.DEFORM_LAYER_TYPE: [api.IdOrderGroup(api.constants.GENERAL_TYPE, [{"id": "wheel"}])],
                api.constants.GUIDE_LAYER_TYPE: [api.IdOrderGroup(api.constants.GENERAL_TYPE, [{"id": "wheel"}])],
                api.constants.RIG_LAYER_TYPE: [api.IdOrderGroup(api.constants.GENERAL_TYPE, [{"id": "wheel"}])],
            },
        }

idMapping returns, per layer, which node ids of that layer belong to a guide id. The order entries decide the order of nodes in the UI.

Connectables

    def connectables(self):
        """Nodes other components are allowed to connect to or from, this fills the parenting and space
        switch UI.
        """
        return [
            api.ConnectableNode(
                path=api.pathAsDefExpression(("self", "inputLayer", "parent")),
                guideId="", label="Parent Component", isOutput=False, isInput=True,
                allowsInputLocalTransform=True, allowsInputOffsetTransform=True, internal=True),
            api.ConnectableNode(
                path=api.pathAsDefExpression(("self", "inputLayer", "world")),
                guideId="", label="World Space", isOutput=False, isInput=True,
                allowsInputLocalTransform=True, allowsInputOffsetTransform=True, internal=True),
            api.ConnectableNode(
                path=api.pathAsDefExpression(("self", "rigLayer", "wheel")),
                guideId="wheel", label="Wheel", isOutput=True, isInput=True,
                allowsInputLocalTransform=True, allowsInputOffsetTransform=True),
        ]

Connectables are the nodes another component or a driver is allowed to connect to, this fills the parent UI and the space switch UI.

Inputs

    def setupInputs(self):
        """Creates the input nodes from the definition then positions them on the guides."""
        super(WheelComponent, self).setupInputs()
        wheelGuide = self.definition.guideLayer.guide("wheel")
        self.inputLayer().inputNode("parent").setWorldMatrix(wheelGuide.transformationMatrix(scale=False).asMatrix())

The rig

    def setupRig(self, parentNode):
        """Creates the animation control and the roll network."""
        rigLayer = self.rigLayer()
        inputLayer = self.inputLayer()
        namer = self.namingConfiguration()
        compName, compSide = self.name(), self.side()
        guideDef = self.definition.guideLayer.guide("wheel")

        ctrlName = namer.resolve("controlName", {"componentName": compName, "side": compSide,
                                                 "id": guideDef.id, "type": "control"})
        control = rigLayer.createControl(
            name=ctrlName, id=guideDef.id, rotateOrder=guideDef.rotateOrder, translate=guideDef.translate,
            rotate=guideDef.rotate, parent=None, shape=guideDef.shape,
            selectionChildHighlighting=self.configuration.selectionChildHighlighting,
            srts=[{"id": guideDef.id, "name": "_".join([ctrlName, "srt"])}])
        parentIn = inputLayer.inputNode("parent")
        extras = []
        # the control follows the parent input
        _, utilities = zapi.buildConstraint(control.srt(), {"targets": (("parent", parentIn),)},
                                            constraintType="matrix", maintainOffset=True)
        extras.extend(utilities)
        extras.extend(self._setupRoll(control, namer))
        rigLayer.addExtraNodes(extras)

A control is created on the rig layer, with the srt buffer above it. The srt follows the parent input with a matrix constraint and the control below it is what the animator moves.

    def _setupRoll(self, control, namer):
        """Roll = distance the control travelled along the forward axis / radius, in degrees.

        The roll is applied to a child of the control, the control can't depend on its own rotation, and
        it rolls when the parent moves the control or when the animator does. Only plain maya nodes are used so the
        scene opens without Zoo Tools loaded.
        """
        compName, compSide = self.name(), self.side()
        controlPanel = self.controlPanel()

        def node(section, nodeType):
            return zapi.createDG(namer.resolve("object", {"componentName": compName, "side": compSide,
                                                          "section": section, "type": nodeType}), nodeType)

        guideLayer = self.definition.guideLayer
        radius = guideLayer.guideSetting("radius").value
        # spinAxis is an enum guide setting, its value is an axis index from mayamath
        spinAttr = "rotate" + mayamath.AXIS_NAME_BY_IDX[guideLayer.guideSetting("spinAxis").value]
        decompose = node("rollPosition", "decomposeMatrix")
        control.worldMatrixPlug().connect(decompose.inputMatrix)
        # the distance travelled along z and along x, the animator picks which one rolls the wheel
        distanceZ = node("rollDistanceZ", "vectorProduct")
        distanceX = node("rollDistanceX", "vectorProduct")
        for dot, axis in ((distanceZ, mayamath.ZAXIS_VECTOR), (distanceX, mayamath.XAXIS_VECTOR)):
            dot.operation.set(1)  # dot product
            dot.input2.set(axis)
            decompose.outputTranslate.connect(dot.input1)
        distance = node("rollDistance", "blendTwoAttr")
        distanceZ.outputX.connect(distance.input[0])
        distanceX.outputX.connect(distance.input[1])
        controlPanel.rollAxis.connect(distance.attributesBlender)
        # degrees = distance / radius * 180 / pi
        toDegrees = node("rollDegrees", "multiplyDivide")
        toDegrees.input2X.set(math.degrees(1.0) / radius)
        distance.output.connect(toDegrees.input1X)
        # animator controls
        autoRoll = node("rollAuto", "multiplyDivide")
        toDegrees.outputX.connect(autoRoll.input1X)
        controlPanel.autoRoll.connect(autoRoll.input2X)
        multiplier = node("rollMultiplier", "multiplyDivide")
        autoRoll.outputX.connect(multiplier.input1X)
        controlPanel.rollMultiplier.connect(multiplier.input2X)
        rollName = namer.resolve("object", {"componentName": compName, "side": compSide,
                                            "section": "roll", "type": "transform"})
        rollNode = zapi.createDag(rollName, "transform", parent=control)
        # kept for postSetupRig, the same instance runs every stage of a build
        self._rollNode = rollNode
        # the attribute name is in a variable so use attribute()
        multiplier.outputX.connect(rollNode.attribute(spinAttr))
        return [decompose, distanceZ, distanceX, distance, toDegrees, autoRoll, multiplier]

The roll is distance / radius, in degrees, on a transform under the control. The axis it spins around is the spinAxis guide setting (X, Y or Z), the radius is the radius guide setting, so a rigger changes them in the guide settings without touching code. It can’t be on the control or above it, the roll reads the world position of the control and would depend on itself. The distance is projected on world z or x, the animator picks with rollAxis. The nodes are decomposeMatrix, vectorProduct, blendTwoAttr and multiplyDivide, nothing which needs Zoo Tools, so a scene opens in vanilla Maya.

Note

The roll is stateless, it is measured from where the wheel was built. It works for a wheel which travels along a line, which covers cars, carts and animation curves driven by the god node. A wheel which turns while it travels needs an accumulated roll, that requires an expression or a script and breaks the “opens without Zoo” rule.

Binding Everything Together

    def postSetupRig(self, parentNode):
        """Binds the rig to the outputs and the skeleton, done in postSetupRig so every node exists."""
        rigLayer = self.rigLayer()
        control = rigLayer.control("wheel")
        extras = []
        # the output follows the control so child components follow the wheel
        _, utilities = zapi.buildConstraint(self.outputLayer().outputNode("wheel"),
                                            {"targets": (("wheel", control),)},
                                            constraintType="matrix", maintainOffset=True)
        extras.extend(utilities)
        # the skinning joint follows the roll node under the control so it spins
        rollNode = self._rollNode
        _, utilities = zapi.buildConstraint(self.deformLayer().joint("wheel"),
                                            {"targets": (("roll", rollNode),)},
                                            constraintType="matrix", maintainOffset=True, decompose=True)
        extras.extend(utilities)
        rigLayer.addExtraNodes(extras)
        super(WheelComponent, self).postSetupRig(parentNode)

addExtraNodes hands the utility nodes to the rig layer so they are deleted with the rig. Forgetting it leaves orphan nodes when the rig is rebuilt.

Step 3, Register It

Hive discovers component classes from HIVE_COMPONENT_PATH and definitions from HIVE_DEFINITIONS_PATH.

def register(folder=FOLDER):
    """Adds the folder to the Hive component and definition paths then refreshes the registry.

    The folder needs an ``__init__.py``, Hive discovers components as python packages. To register a folder
    permanently set ``HIVE_COMPONENT_PATH`` and ``HIVE_DEFINITIONS_PATH`` in your ``zoo_package.json`` or add it to
    the Hive user component paths in the Zoo preferences.
    """
    for variable in ("HIVE_COMPONENT_PATH", "HIVE_DEFINITIONS_PATH"):
        paths = [i for i in os.environ.get(variable, "").split(os.pathsep) if i]
        if folder not in paths:
            os.environ[variable] = os.pathsep.join(paths + [folder])
    registry = api.Configuration().componentRegistry()
    registry.refresh()
    return registry

Warning

The component folder needs an __init__.py because Hive imports the components as python packages. If your folder is itself on sys.path the components are imported twice under two names and aren’t registered, keep the parent of the folder on the path instead.

To register a folder for every session add it to the environment block of a zoo_package.json:

{
    "environment": {
        "HIVE_COMPONENT_PATH": ["{self}/hive/components"],
        "HIVE_DEFINITIONS_PATH": ["{self}/hive/components"]
    }
}

Or add the folder to the Hive user component paths in the Zoo preferences.

Step 4, Use It

from zoo.libs.hive import api

rig = api.commands.createRig(name="Car")
godnode = rig.createComponent("godnodecomponent", "godnode", "M")
wheel = rig.createComponent("wheelcomponent", "wheelFL", "L")
rig.buildGuides()
wheel.setParent(godnode, godnode.guideLayer().guide("godnode"))
rig.buildRigs()

# drive the wheel
godnode.rigLayer().control("godnode").translateZ.set(100.0)

Try It, The Finished Scene

buildwheelscene.py is a mayapy script which loads Maya and Zoo Tools, creates a wheel cylinder with bolts sized as a small car wheel, creates the component, places the guides, builds the skeleton and rig, polishes and skins the cylinder to the wheel joint, then saves wheelrig.ma.

def build(path=SCENE_PATH, radius=WHEEL_RADIUS, width=WHEEL_WIDTH):
    """Builds the wheel scene and saves it.

    :param path: The maya scene to write.
    :param radius: The wheel radius.
    :param width: The wheel width.
    :return: The saved path.
    :rtype: str
    """
    from maya import cmds
    from zoo.libs.hive import api
    from zoo.libs.maya import zapi

    # mayapy puts the folder of the script on sys.path. Hive imports components by their dotted path, with the
    # folder as a root the wheel is imported twice under two names and is never registered.
    sys.path[:] = [i for i in sys.path if os.path.normpath(i) != os.path.normpath(FOLDER)]
    register = _loadSibling("registerwheel")
    register.register(FOLDER)

    cmds.file(new=True, force=True)
    cylinder = createWheelGeometry(radius, width)

    rig = api.commands.createRig(name="wheelRig")
    wheel = rig.createComponent("wheelcomponent", "wheel", "M")
    # guide settings are read when the rig is built, set them before the guides are made
    wheel.definition.guideLayer.guideSetting("radius").value = radius
    rig.buildGuides()

    # place the guides, the root sits on the ground and the hub guide at the center of the cylinder.
    guideLayer = wheel.guideLayer()
    rootGuide, hubGuide = guideLayer.findGuides("root", "wheel")
    rootGuide.setWorldMatrix(zapi.Matrix())
    hubMatrix = zapi.TransformationMatrix()
    hubMatrix.setTranslation(zapi.Vector(0.0, radius, 0.0), zapi.kWorldSpace)
    hubGuide.setWorldMatrix(hubMatrix.asMatrix())
    # size the guide shape, and the control it becomes, to match the wheel. The wheel spins around x so the
    # guide keeps its identity rotation.
    hubGuide.setScale(zapi.Vector(radius, radius, radius))

    rig.buildDeform()
    rig.buildRigs()
    rig.polish()

    joint = wheel.deformLayer().joint("wheel")
    cmds.skinCluster(joint.fullPathName(), cylinder, toSelectedBones=True, name="wheel_skin")

    cmds.file(rename=path.replace("\\", "/"))
    cmds.file(save=True, type="mayaAscii", force=True)
    return path

Open wheelrig.ma and move the wheel control along z. The axle is x, change spinAxis in the guide settings for a wheel with another axle. It rolls with the bolts turning, set rollAxis to X for a wheel which travels along x and autoRoll to 0 to switch the roll off. Space switch it with wheelSpace.

Testing A Component

Component tests are ordinary Maya unit tests. Register the folder, build every stage and check the scene, tests/libs/hive/test_customcomponentexample.py tests this component:

  • Every stage builds.

  • The control panel attributes and the space switch exist.

  • The roll matches the distance travelled, along both axes and with the multiplier and switch.

  • The scene script saves a rigged scene.

Checklist For Your Own Component

  1. Give every guide, input, output, joint and control the ids Hive should map, and keep them forever.

  2. Build the definition with the API, don’t hand edit.

  3. Create nodes in setupRig, bind in postSetupRig.

  4. Hand every utility node to addExtraNodes.

  5. Use only plain Maya nodes, no script jobs, custom nodes or plugins.

  6. Put anything an animator changes on the control panel, keyable ones in the channel box.

  7. Ship the space switches animators need in the definition, protect the built in choices.

  8. Write a test which builds every stage.