Skip to content
Richard Katz
  • Home
  • Tech
  • Art
  • About
October 18, 2026 by katz3d

Component Library – Part 3

Component Library – Part 3
October 18, 2026 by katz3d

Modules referenced in this chapter:

CATS.components.twist
CATS.classes.twistbase

Twist

The Twist component started simple, until I realized its limitations, and then it rapidly grew much more complicated.

It has four main features:

  1. An adjustable twist “ratio” – the amount of twist between the start and end nodes of the twist. So a twist joint 2/3 of the way between the shoulder and elbow would have a 0.67 twist value. This is a keyable value, and can be adjusted by the animator for a specific look, or set to 0.0 to turn off twist entirely.
  2. The twist goes through a keyable control for additional fine-tuning of the twist if needed.
  3. In the event of the twist flipping 180 degrees, there’s a keyable twistAdjust attribute that adds or subtracts 180 degrees from the twist result, so the animators can push the limbs beyond their designed limits.
  4. The twist joints also automatically maintain their spacing between the start and end nodes if the limb stretches.

The data in the DG goes through two main pathways:

  1. An orientation path that calculates the twist and adds it to the local rotation of the output
  2. A translation path that maintains the output’s spacing between start and end nodes

Since we’re using matrices and quaternions to do the math, and not peeking at adjacent frames, the twist is limited to 180 degrees. Once the twist passes 180 degrees, it will take the shortest path to the result, which will cause a flip. I tried using the aimMatrix node to simulate the “cheat” that existed in previous Maya versions, where you could set an aimConstraint or ik with an up vector of [0,0,0] and then add a second constraint that blended between that twist and the start, which allowed you to extract twist values up to 360. It didn’t initially work, but maybe I was setting it up incorrectly. Maybe I’ll experiment with that approach again in the future.

As with other components, Twist subclasses from ComponentBase and re-implements _component_name(), _component_description(), and build().

Most of what the component does is offloaded to the TwistBase class. We call TwistBase‘s create() classmethod to return an instance of TwistBase while creating a set of shared nodes in the scene that we’ll use for each of the twist joints in this twist system. 

For example, for an upper arm twist, we’ll set the Twist component’s start parameter to the skeleton’s shoulder, and the end parameter to the skeleton’s elbow. The nodes parameter would include the twist joints that are expected to twist based on the axial twist of the elbow relative to the shoulder, but actually when the upper arm is rotated in around the axis that aims toward the elbow.

class Twist(ComponentBase):
    def __init__(self):
        super().__init__()
        self.register_parameter("start", type_=str)
        self.register_parameter("end", type_=str)
        self.register_parameter("nodes", type_=list)
        self.register_parameter("parent", type_=str)
        self.register_parameter("ctrl", type_=str)
        self.register_parameter("hub", type_=str)
        self.register_parameter("reverse", type_=bool)

        self.register_output("controls", type_=list)

    @property
    def _component_name(self) -> str:
        """Return User-facing name of the component"""
        return "Twist"

    @property
    def _component_description(self) -> str:
        """Return User-facing information of the component"""
        return "twist component - creates deformation helper nodes \
                that gradually blend their rotation along an axis"

    def _build(self, *args, **kwargs) -> None:
        """run component"""
        twist = TwistBase.create(start=self.get_value('start'),
                                end=self.get_value('end'),
                                parent=self.get_value('parent'),
                                hub=self.get_value('hub'),
                                reverse=self.get_value('reverse'))

        for node in self.get_value('nodes'):
            twist.add_twist(node=node)

TwistBase

The TwistBase class takes a set of arguments that look similar to the parameters for the Twist component.

class TwistBase(object):
    """twist component - creates and drives nodes between start and end that
    gradually blend their rotation along an axis"""
    def __init__(self,
                node: str = None,
                start: str = None,
                end: str = None,
                parent: str = None,
                reverse: bool = None,
                hub: (str | Hub) = None,
                axis: (str | int) | list[float] = None):

        self.start: str = start
        self.end: str = end
        self.parent: (str | None) = parent
        self.reverse: bool = reverse

        self.hub: (str | Hub) = Hub(hub) if Hub.is_hub(hub) else hub
        self.axis: list[float] = Axis(axis).to_list() if axis else None

        self.aim: (str | None) = None
        self.mmx: (str | None) = None
        self.group: (str | None) = None
        self.dec_start: (str | None) = None
        self.pma_vector: (str | None) = None

        self.twist_nodes: list[str] = []

        if node:
            self.get_twist_nodes(node)

        if self.axis is None:
            self.axis = self.get_axis()

If the node argument is supplied and the twist exists in the scene, it should populate the class with a reference to that node’s twist system. I haven’t tested it, I haven’t found a use for it, and there’s currently no functionality that takes advantage of it, but this is the design intent behind the classes in the CATS.classes sub-package. The get_twist_nodes() method collects the twist system related to the node argument.

   def get_twist_nodes(self, node: str):
        """Collect existing scene nodes in this twist component"""
        all_connected = cmds.listHistory(node, allConnections=True) + 
                        cmds.listHistory(node, future=True, allFuture=True)
        for connected in all_connected:
            if cmds.objectType(connected, isType='aimMatrix') and 
               cmds.attributeQuery('_twist', node=connected, exists=True):
                self.aim = connected
                break

        if self.aim:
            twist_nodes = cmds.listConnections(f'{self.aim}._twist',
                          source=True, destination=False)
            for twist_node in twist_nodes:
                if cmds.objectType(twist_node, isType='quatToEuler'):
                    targets = cmds.listConnections(
                              f'{twist_node}.outputRotateX', 
                              source=False, 
                              destination=True) or []
                    if len(targets) and 
                       cmds.attributeQuery(TWIST_VALUE_ATTR,
                       node=twist_node, exists=True):
                        self.twist_nodes.append(targets[0])

The get_axis() method is another version of some methods that now live in the CATS.core.axis.Axis class. I should migrate this method over there or merge it into one of the existing variations.

It returns the local axis, in list form, of start that points at end. For the skeleton I’m using to test, it returns [1, 0, 0] (X axis) for the left arm and [-1, 0, 0] (negative X) for the right arm.

   def get_axis(self) -> list[float]:
        """get primary vector between start and end"""
        src_mat = DagNode(self.start).transform
        src_axes = [om2.MVector(list(src_mat)[0:3]), 
                    om2.MVector(list(src_mat)[4:7]),
                    om2.MVector(list(src_mat)[8:11])]

        src_pos = DagNode(self.start).world_position
        end_pos = DagNode(self.end).world_position

        dir_vec = (om2.MVector(end_pos) - om2.MVector(src_pos)).normal()
        axes = [(dir_vec * v) for v in src_axes]
        abs_axes = [abs(a) for a in axes]
        idx = abs_axes.index(max(abs_axes))

        axis_names = ['x', 'y', 'z']
        sign = "-" if axes[idx] < 0 else ""

        return Axis(sign+axis_names[idx]).to_list()

The create() classmethod is short and readable. It creates a class instance and runs the private _create() method if the twist system doesn’t already exist in the scene.

    @classmethod
    def create(cls,
               start: str, 
               end: str, 
               parent: str|None = None,
               hub: str = None, 
               reverse: bool = False) -> Self:
        """create twist component"""
        twist_inst = cls(start=start, 
                         end=end, 
                         parent=parent, 
                         hub=hub, 
                         reverse=reverse)
        if not twist_inst.get_twist_nodes(start):
            twist_inst._create()
        return twist_inst

Now let’s create some nodes. _create() builds a few nodes in the scene that will be shared by any subsequent twist joints we set up. So if there’s two twist joints between the shoulder and the elbow, they will share some of the nodes that _create() builds.

Let’s start by creating a base name using the Name class from the start node, and creating an empty group node under the Hub that we’ll add any scene nodes to.

   def _create(self) -> None:
        """private create twist component"""
        base_name = Name(self.start)
        self.group = cmds.createNode('transform',
                     name=base_name.change(node_type='grp',
                          base=base_name.base+"TwistGrp",
                          iterator=None).build(), 
                     parent=pathname(self.hub.node))

We’re going to use the aimMatrix node to calculate the difference in twist rotation between the start and end nodes. This section creates the utility nodes we’ll use for the rotation part of the twist system. The decomposeMatrix in this part is a matrix in local space.

        # aim utilities
        self.aim = cmds.createNode('aimMatrix',
                                   name=base_name.change(node_type='aim',                  
                                        base=base_name.base+"Twist",
                                        iterator=None).build())
        self.ref = cmds.createNode('multMatrix',
                                   name=base_name.change(
                                        node_type='mmx',
                                        base=base_name.base+"TwistPrntSpc"
                                        ).build())
        afm = cmds.createNode('axisFromMatrix',
                              name=base_name.change(node_type='afm',
                                   base=base_name.base+"Twist"
                                   ).build())
        mmx_aim_spc = cmds.createNode('multMatrix',
                                      name=base_name.change(node_type='mmx',
                                           base=base_name.base+"TwistAimSpc"
                                           ).build())
        dec = cmds.createNode('decomposeMatrix',
                              name=base_name.change(node_type='dec',
                                   base=base_name.base+"Twist").build())
        self.qte = cmds.createNode('quatToEuler',
                                   name=base_name.change(node_type='qte',
                                        base=base_name.base+"Twist").build())

The next section creates the utility nodes for the Translation part of the twist system. We’re using Maya’s new translationFromMatrix nodes to extract world positions from a node’s worldMatrix, and using a plusMinusAverage node to subtract the translations to get the vector between them.

        # translation utilities
        self.dec_start = cmds.createNode('decomposeMatrix',
                                         name=base_name.change(node_type='dec', 
                                              base=base_name.base+"Start"
                                              ).build())
        tfm_start = cmds.createNode('translationFromMatrix',
                                    name=base_name.change(node_type='tfm',
                                         base=base_name.base+"Start").build())
        tfm_end = cmds.createNode('translationFromMatrix',
                                  name=base_name.change(node_type='tfm',
                                       base=base_name.base+"End").build())
        self.pma_vector = cmds.createNode('plusMinusAverage',
                                          name=base_name.change(node_type='pma',
                                               base=base_name.base+"Vector"
                                               ).build())

We’re using Maya’s data-less message attributes to connect all of the nodes involved in this shared collection so that we can easily find them later.

        # add message attrs for gathering twist nodes
        cmds.addAttr(f'{self.aim}', 
                     longName='_twist', 
                     attributeType='message', 
                     multi=True, 
                     indexMatters=False)

        cmds.connectAttr(f'{self.ref}.message', 
                         f'{self.aim}._twist', 
                         nextAvailable=True)
        cmds.connectAttr(f'{afm}.message',
                         F'{self.aim}._twist',
                         nextAvailable=True)
        cmds.connectAttr(f'{mmx_aim_spc}.message',
                         f'{self.aim}._twist', 
                         nextAvailable=True)
        cmds.connectAttr(f'{dec}.message', 
                         f'{self.aim}._twist', 
                         nextAvailable=True)
        cmds.connectAttr(f'{self.qte}.message', 
                         f'{self.aim}._twist', 
                         nextAvailable=True)

        cmds.connectAttr(f'{self.dec_start}.message', 
                         f'{self.aim}._twist', 
                         nextAvailable=True)
        cmds.connectAttr(f'{tfm_start}.message', 
                         f'{self.aim}._twist', 
                         nextAvailable=True)
        cmds.connectAttr(f'{tfm_end}.message', 
                         f'{self.aim}._twist', 
                         nextAvailable=True)
        cmds.connectAttr(f'{self.pma_vector}.message', 
                         f'{self.aim}._twist', 
                         nextAvailable=True)

        primary_axis = Axis(self.axis).to_list()
        secondary_axis = [0,1,0] if abs(primary_axis[0]) > abs(primary_axis[1]) else [1,0,0]

“Reverse Mode” tells the twist component that the twisting will occur from the start to the end rather than from the end to the start. 

For an upper arm twist, we want the twisting to be “inverted” so that as the shoulder rotates on its aim axis, a reverse twist will be applied to the joints at the top of the segment to prevent the shoulder deformation from following the shoulder rotation. 

For a lower arm, we want the twist to be driven by the wrist joint, so it starts at the elbow (0% twist) and ends at the wrist (100% twist).

        # reverse mode
        start_node = self.end if self.reverse else self.start
        end_node = self.start if self.reverse else self.end

        # set up parent/reference space
        start_ws = DagNode(start_node).transform
        parent_space = DagNode(self.parent).transform
        cmds.setAttr(f'{self.ref}.matrixIn[0]', 
                     *list(start_ws * parent_space.inverse()), 
                     type="matrix")

        cmds.connectAttr(f'{self.parent}.worldMatrix', 
                         f'{self.ref}.matrixIn[1]', 
                         force=True)

Here we’re setting up Maya’s aimMatrix node. 

        # set up aimMatrix
        cmds.connectAttr(f'{self.ref}.matrixSum', f'{afm}.input', force=True)
        cmds.setAttr(f'{afm}.axis', Axis(secondary_axis).to_int())
        cmds.connectAttr(f'{afm}.output', 
                         f'{self.aim}.secondaryTargetVector', 
                         force=True)

        cmds.connectAttr(f'{start_node}.worldMatrix', 
                         f'{self.aim}.inputMatrix')
        cmds.connectAttr(f'{end_node}.worldMatrix', 
                         f'{self.aim}.primaryTargetMatrix')
        cmds.setAttr(f"{self.aim}.primaryMode", 0)
        cmds.setAttr(f"{self.aim}.primaryInputAxis", *primary_axis)
        cmds.setAttr(f"{self.aim}.secondaryMode", 2)
        cmds.setAttr(f"{self.aim}.secondaryInputAxis", *secondary_axis)

        # get rotation from aimMatrix
        cmds.connectAttr(f"{self.aim}.outputMatrix", 
                         f'{mmx_aim_spc}.matrixIn[0]', 
                         force=True)
        cmds.connectAttr(f"{start_node}.worldInverseMatrix",
                         f'{mmx_aim_spc}.matrixIn[1]', 
                         force=True)
        cmds.connectAttr(f'{mmx_aim_spc}.matrixSum', 
                         f'{dec}.inputMatrix', 
                         force=True)
        cmds.connectAttr(f'{dec}.outputQuat', 
                         f'{self.qte}.inputQuat', 
                         force=True)

        # set up start transform and vector
        cmds.connectAttr(f'{self.start}.worldMatrix',
                         f'{self.dec_start}.inputMatrix')
        cmds.connectAttr(f'{self.start}.worldMatrix', f'{tfm_start}.input')
        cmds.connectAttr(f'{self.end}.worldMatrix', f'{tfm_end}.input')
        cmds.connectAttr(f'{tfm_end}.output', f'{self.pma_vector}.input3D[0]')
        cmds.connectAttr(f'{tfm_start}.output', f'{self.pma_vector}.input3D[1]')
        cmds.setAttr(f'{self.pma_vector}.operation', 2) # subtract

This get_default_distance_ratio() method returns the vector length of the node relative to the vector of self.start to self.end.

   def get_default_distance_ratio(self, node: str) -> float:
        """get normalized location of node along twist"""
        start_pos = om2.MVector(DagNode(self.start).world_position)
        end_pos = om2.MVector(DagNode(self.end).world_position)
        node_pos = om2.MVector(DagNode(node).world_position)
        return (start_pos - node_pos).length() / (start_pos - end_pos).length()

As we saw in the Twist component, we loop through the twist joints and call TwistBase.add_twist() to add each to the twist system.

   def add_twist(self, node: (str | om2.MObject), twist_value: float = None) -> None:
        """Add a single twist node to the twist system"""
        node_name = pathname(node)
        base_name = Name(node_name)

I could have omitted this parent group of the twist control and merged the twist rotation into a single value that gets plugged into the control’s offsetParentMatrix, but this way it’s much easier to read and more importantly easier to debug.

        # create an empty transform node to apply the calculated matrix 
        # plus the twist offset
        ctrl_grp = cmds.createNode('transform',
                                   name=base_name.change(node_type='grp',
                                        base=base_name.base+"Zero").build(),
                                   parent=self.group)
        align(ctrl_grp, node)
        freeze(ctrl_grp)

We’re also going to create an output joint that is connected to the control, so that for consistency there is a “layer” of joints that the deformation skeleton is attached to.

        # create output control and attach joint.
        twist_jx = Joint.create(name=base_name.change(node_type='jx',
                                     base=base_name.base), 
                                parent=self.group,
                                transform=world_matrix(mobject(node)))
        twist_ctrl = Control.from_joint(joint=twist_jx,
                                        name=base_name.change(node_type='ctrl'),
                                        parent=ctrl_grp,
                                        hub=self.hub,
                                        shape=DefaultShape.circle_dir,
                                        attach=True)
        twist_ctrl.orient_shape(self.end)
        twist_ctrl.rotate_angle_axis(90, [1,0,0], local=True)
        twist_ctrl.scale_shape([1,6,6])

        if node_name in self.twist_nodes:
            raise RuntimeError(f'twist {node_name} already exists')

        if twist_value is None:
            twist_value = self.get_default_distance_ratio(node_name)

As I mentioned before, the actual twisting can be start to end or end to start.

        # reverse: forearms are reversed, they get ascending negative rotation    
        # toward end when wrist rotates. 
        # UpperArm gets positive descending rotation toward end when itself rotates
        if self.reverse:
            rot_twist_value = -1.0 * twist_value
        else:
            rot_twist_value = 1.0 - twist_value

        # use Axis class to get the axis as a x/y/z value and strip negative sign
        axis_char = Axis(self.axis).to_char().strip('-').upper()

        # result multiplies the rotation by the TWIST_VALUE percentage
        md = cmds.createNode('multiplyDivide', 
                             name=base_name.change(node_type='md',
                                  base=base_name.base+"TwistResult").build())

        cmds.addAttr(f'{pathname(twist_ctrl)}', 
                     longName=TWIST_VALUE_ATTR, 
                     attributeType='float',
                     keyable=True)
        cmds.setAttr(f"{pathname(twist_ctrl)}.{TWIST_VALUE_ATTR}", rot_twist_value)
        cmds.connectAttr(f'{pathname(twist_ctrl)}.{TWIST_VALUE_ATTR}', 
                         f'{md}.input2{axis_char}', force=True)
        cmds.connectAttr(f'{self.qte}.outputRotate{axis_char}',
                         f'{md}.input1{axis_char}', force=True)

Assemble the parts back into a matrix.

        # convert back into matrix
        md_vector_pct = cmds.createNode('multiplyDivide',
                                        name=base_name.change(node_type='md', 
                                        base=base_name.base+"VectorPct").build())
        pma_add_vector = cmds.createNode('plusMinusAverage',
                                         name=base_name.change(node_type='pma',
                                              base=base_name.base+"AddVector"
                                              ).build())
        cmp_mat = cmds.createNode('composeMatrix',
                                  name=base_name.change(node_type='cmp').build())
        hold_offset = cmds.createNode('holdMatrix',
                                      name=base_name.change(node_type='hold',
                                           base=base_name.base+"Offset").build())
        mmx_offset = cmds.createNode('multMatrix',
                                     name=base_name.change(node_type='mmx',
                                          base=base_name.base+"Offset").build())

        # multiply vector by twist_value percent
        cmds.connectAttr(f'{self.pma_vector}.output3D', f'{md_vector_pct}.input1')

        for vector_axis in ['X', 'Y', 'Z']:
            cmds.setAttr(f"{md_vector_pct}.input2{vector_axis}", twist_value)

        cmds.connectAttr(f'{self.dec_start}.outputTranslate',
                         f'{pma_add_vector}.input3D[0]')
        cmds.connectAttr(f'{md_vector_pct}.output', 
                         f'{pma_add_vector}.input3D[1]')

        cmds.connectAttr(f'{pma_add_vector}.output3D', 
                         f'{cmp_mat}.inputTranslate')
        cmds.connectAttr(f'{self.dec_start}.outputRotate',
                         f'{cmp_mat}.inputRotate')
        cmds.connectAttr(f'{self.dec_start}.outputScale', 
                         f'{cmp_mat}.inputScale')

The “offset” here is in the event that the twist joint that we’re going to drive is not exact lined up with the location we calculate for its location along the start-to-end vector.

        # get any offset from node
        twist_ws = world_matrix(mobject(node))
        inverse_cmp = om2.MMatrix(cmds.getAttr(f'{cmp_mat}.outputMatrix')
                                 ).inverse()
        offset_value = twist_ws * inverse_cmp
        cmds.setAttr(f'{hold_offset}.inMatrix', *list(offset_value), type='matrix')

        # add offset and composed matrix
        cmds.connectAttr(f'{hold_offset}.outMatrix', f'{mmx_offset}.matrixIn[0]')
        cmds.connectAttr(f'{cmp_mat}.outputMatrix', f'{mmx_offset}.matrixIn[1]')

        # plug final non-twist value into ctrls's parent group offsetParentMatrix
        cmds.connectAttr(f'{mmx_offset}.matrixSum',
                         f'{ctrl_grp}.offsetParentMatrix', 
                         force=True)

        # add simple twist rotation to ctrl_grp
        cmds.connectAttr(f'{md}.output{axis_char}',
                         f'{ctrl_grp}.rotate{axis_char}')
        connect(node_name, twist_jx.node, keep_offset=True)

        # add twist adjust to control
        self.add_twist_adjust(node=md, 
                              control=pathname(twist_ctrl),
                              attr_name=TWIST_ADJUST_ATTR)

        self.twist_nodes.append(node_name)

The twist adjust adds a keyable attribute to the control that allows the animator to fix unwanted twist flips. It sort of hacks into the nodes created by add_twist() and rewires them to insert some additional nodes. We could make this an optional parameter on the Twist component if it’s something we decide doesn’t work well. 

   def add_twist_adjust(self, 
                        node: (str | om2.MObject), 
                        control: (str | om2.MObject), 
                        attr_name: str = 'twistAdjust') -> None:
        """ the Twist Adjust attr allows the animator to \
            key +/- 180 degree values in the event of a twist flip"""
        control_name = Name(control)
        axis_char = Axis(self.axis).to_char().strip('-').upper()

        cmds.addAttr(control,
                     longName=attr_name, 
                     attributeType='enum', 
                     enumName="noAdjust=0:plus180=1:minus180=2", 
                     keyable=True)
        # create condition nodes to apply enum selection to twist value
        cond_plus = cmds.createNode('condition',
                                    name=control_name.change(node_type='cond', 
                                         base=control_name.base+"TwistPlus"
                                         ).build())
        cond_minus = cmds.createNode('condition',
                                     name=control_name.change(node_type='cond',
                                          base=control_name.base+"TwistMinus"
                                          ).build())
        # plusMinusAverage node adds condition results and original value to target
        pma = cmds.createNode('plusMinusAverage',
                              name=control_name.change(node_type='pma',
                                   base=control_name.base+"TwistAdjust").build())

        # if condition.firstTerm is 1, add 180 to twist
        cmds.connectAttr(f'{control}.{attr_name}', 
                         f'{cond_plus}.firstTerm', 
                         force=True)
        cmds.setAttr(f'{cond_plus}.secondTerm', 1)
        cmds.setAttr(f'{cond_plus}.colorIfTrueR', 180.0)
        cmds.setAttr(f'{cond_plus}.colorIfFalseR', 0.0)
        # if condition.firstTerm is 2, subtract 180 from twist
        cmds.connectAttr(f'{control}.{attr_name}', 
                         f'{cond_minus}.firstTerm', 
                         force=True)
        cmds.setAttr(f'{cond_minus}.secondTerm', 2)
        cmds.setAttr(f'{cond_minus}.colorIfTrueR', -180.0)
        cmds.setAttr(f'{cond_minus}.colorIfFalseR', 0.0)

        # add original value plus output of condition nodes
        cmds.connectAttr(f'{node}.output{axis_char}',
                         f'{pma}.input1D[0]',
                         force=True)
        cmds.connectAttr(f'{cond_plus}.outColorR', 
                         f'{pma}.input1D[1]', 
                         force=True)
        cmds.connectAttr(f'{cond_minus}.outColorR', 
                         f'{pma}.input1D[2]',
                         force=True)

        node_output = cmds.listConnections(f'{node}.output{axis_char}',
                                           source=False, 
                                           destination=True,
                                           plugs=True,
                                           skipConversionNodes=True)
        if node_output:
            cmds.connectAttr(f'{pma}.output1D', node_output[0], force=True)

Summary

There’s a lot of work I’d like to do on this current iteration of the Twist component. I’d like to ensure that it’s stable, and increase the twist range to be able to rotate a full 360 degrees without breaking. To get there, it needs animators to bang away at it and put it through its paces. 

In the next chapter, I’ll discuss the approach I took for the Spine and Head components.

Previous articleComponent Library - Part 2Next article Component Library - Part 4
  • November 2026
  • October 2026
  • September 2026
  • August 2026
  • July 2026
  • June 2021
  • March 2021