def __init__(self, name, parent=None, flags=None, metaData=None): super(Object3D, self).__init__(name, parent=parent, metaData=metaData) self._children = [] self._flags = {} self._attributeGroups = [] self._constraints = [] self._xfo = Xfo() self._ro = RotationOrder() self._color = None self._implicitAttrGrp = AttributeGroup("implicitAttrGrp", self) self._visibility = BoolAttribute('visibility', True, self._implicitAttrGrp) self._shapeVisibility = BoolAttribute('ShapeVisibility', True, self._implicitAttrGrp) if parent is not None: parent.addChild(self) if flags is not None: assert type( flags ) is str, "Flags argument must be a comma separated string." for flag in flags.replace(' ', '').split(','): if not re.match("[\w]*$", flag): msg = "{} '{}' {} ({}: {}) {}\n".format( "Invalid flag", flag, "set on", self.getName(), self.getPath(), ". Alphanumeric and underscores only!") logger.warn(msg) continue self.setFlag(flag)
def __init__(self, name='hand', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct Hand Guide Component:" + name) super(HandComponentGuide, self).__init__(name, parent, *args, **kwargs) # ========= # Controls # ========= # Guide Controls self.guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.digitNamesAttr = StringAttribute( 'digitNames', value="thumb,index,middle,ring,pinky", parent=self.guideSettingsAttrGrp) self.digitNamesAttr.setValueChangeCallback(self.updateFingers) self.numJointsAttr = IntegerAttribute('numJoints', value=4, minValue=2, maxValue=20, parent=self.guideSettingsAttrGrp) self.numJointsAttr.setValueChangeCallback(self.resizeDigits) self.fingers = OrderedDict() self.handCtrl = Control('hand', parent=self.ctrlCmpGrp, shape="square") self.handCtrl.rotatePoints(0.0, 0.0, 90.0) self.handCtrl.scalePoints(Vec3(1.0, 0.75, 1.0)) self.handCtrl.setColor('yellow') self.handGuideSettingsAttrGrp = AttributeGroup("Settings", parent=self.handCtrl) self.ctrlShapeToggle = BoolAttribute( 'ctrlShape_vis', value=False, parent=self.handGuideSettingsAttrGrp) self.handDebugInputAttr = BoolAttribute( 'drawDebug', value=False, parent=self.handGuideSettingsAttrGrp) self.drawDebugInputAttr.connect(self.handDebugInputAttr) self.guideCtrlHrcGrp = HierarchyGroup('controlShapes', parent=self.ctrlCmpGrp) self.default_data = { "name": name, "location": "L", "handXfo": Xfo(Vec3(7.1886, 12.2819, 0.4906)), "digitNames": self.digitNamesAttr.getValue(), "numJoints": self.numJointsAttr.getValue(), "fingers": self.fingers } self.loadData(self.default_data) Profiler.getInstance().pop()
def createOutput(self, name, dataType, **kwargs): """Creates an output object and also a connected target object that matches the data type that is passed. Args: name (str): Name of the output to create. dataType (str): Data type of the output. Returns: Object: The connected target object for the output. """ componentOutputPort = self.addOutput(name, dataType) if dataType.endswith('[]'): newOutputTgt = [] else: # Create object if dataType.startswith('Xfo'): newOutputTgt = ComponentOutput(name) elif dataType.startswith('Boolean'): newOutputTgt = BoolAttribute(name) elif dataType.startswith('Float'): newOutputTgt = ScalarAttribute(name) elif dataType.startswith('Integer'): newOutputTgt = IntegerAttribute(name) elif dataType.startswith('String'): newOutputTgt = StringAttribute(name) # Handle keyword arguments for k, v in kwargs.iteritems(): if k == 'value': newOutputTgt.setValue(v) elif k == 'minValue': newOutputTgt.setMin(v) elif k == 'maxValue': newOutputTgt.setMax(v) elif k == 'parent': if isinstance(newOutputTgt, list): raise Exception( "Array outputs cannot be assigned to a parent. Each element in the array must be parented individually: " + name + ".") if dataType.startswith('Xfo'): v.addChild(newOutputTgt) else: v.addAttribute(newOutputTgt) else: logger.warning( "Keyword '%s' is not supported with createOutput method!" % k) componentOutputPort.setTarget(newOutputTgt) return componentOutputPort
def __init__(self, name='leg', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct Leg Guide Component:" + name) super(LegComponentGuide, self).__init__(name, parent, *args, **kwargs) # ========= # Controls # ========= guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) # Guide Controls self.femurCtrl = Control('femur', parent=self.ctrlCmpGrp, shape="sphere") self.kneeCtrl = Control('knee', parent=self.ctrlCmpGrp, shape="sphere") self.ankleCtrl = Control('ankle', parent=self.ctrlCmpGrp, shape="sphere") armGuideSettingsAttrGrp = AttributeGroup("DisplayInfo_ArmSettings", parent=self.femurCtrl) self.armGuideDebugAttr = BoolAttribute('drawDebug', value=True, parent=armGuideSettingsAttrGrp) self.guideOpHost = Transform('guideOpHost', self.ctrlCmpGrp) # Guide Operator self.legGuideKLOp = KLOperator('guide', 'TwoBoneIKGuideSolver', 'Kraken') self.addOperator(self.legGuideKLOp) # Add Att Inputs self.legGuideKLOp.setInput('drawDebug', self.armGuideDebugAttr) self.legGuideKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Source Inputs self.legGuideKLOp.setInput('root', self.femurCtrl) self.legGuideKLOp.setInput('mid', self.kneeCtrl) self.legGuideKLOp.setInput('end', self.ankleCtrl) # Add Target Outputs self.legGuideKLOp.setOutput('guideOpHost', self.guideOpHost) self.default_data = { "name": name, "location": "L", "createIKHandle": False, "femurXfo": Xfo(Vec3(1.0, 9.75, -0.5)), "kneeXfo": Xfo(Vec3(1.5, 5.5, -0.5)), "ankleXfo": Xfo(Vec3(1.75, 1.15, -1.25)) } self.loadData(self.default_data) Profiler.getInstance().pop()
def __init__(self, name, parent=None): super(Object3D, self).__init__(name, parent) self._children = [] self._flags = {} self._attributeGroups = [] self._constraints = [] self._xfo = Xfo() self._ro = RotationOrder() self._color = None self._implicitAttrGrp = AttributeGroup("implicitAttrGrp", self) self._visibility = BoolAttribute('visibility', True, self._implicitAttrGrp) self._shapeVisibility = BoolAttribute('ShapeVisibility', True, self._implicitAttrGrp) if parent is not None: parent.addChild(self)
def createInput(self, name, dataType, **kwargs): """Creates an input object and also a connected target object that matches the data type that is passed. Args: name (str): Name of the input to create. dataType (str): Data type of the input. Returns: Object: The connected target object for the input. """ componentInputPort = self.addInput(name, dataType) # Create object if dataType.startswith('Xfo'): newInputTgt = ComponentInput(name) elif dataType.startswith('Boolean'): newInputTgt = BoolAttribute(name) elif dataType.startswith('Float'): newInputTgt = ScalarAttribute(name) elif dataType.startswith('Integer'): newInputTgt = IntegerAttribute(name) elif dataType.startswith('String'): newInputTgt = StringAttribute(name) # Handle keyword arguments for k, v in kwargs.iteritems(): if k == 'value': newInputTgt.setValue(v) elif k == 'minValue': newInputTgt.setMin(v) newInputTgt.setUIMin(v) elif k == 'maxValue': newInputTgt.setMax(v) newInputTgt.setUIMax(v) elif k == 'parent': if dataType.startswith('Xfo'): v.addChild(newInputTgt) else: v.addAttribute(newInputTgt) else: logger.warning( "Keyword '%s' is not supported with createInput method!" % k) componentInputPort.setTarget(newInputTgt) return componentInputPort
def __init__(self, name='clavicle', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct Clavicle Guide Component:" + name) super(ClavicleComponentGuide, self).__init__(name, parent, *args, **kwargs) # ========= # Controls # ========= # Guide Controls guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.clavicleCtrl = Control('clavicle', parent=self.ctrlCmpGrp, shape="circle") self.clavicleCtrl.scalePoints(Vec3(0.75, 0.75, 0.75)) self.clavicleCtrl.rotatePoints(0.0, 0.0, 90.0) self.clavicleGuideSettingsAttrGrp = AttributeGroup("Settings", parent=self.clavicleCtrl) self.handDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=self.clavicleGuideSettingsAttrGrp) self.drawDebugInputAttr.connect(self.handDebugInputAttr) self.clavicleUpVCtrl = Control('clavicleUpV', parent=self.clavicleCtrl, shape="triangle") self.clavicleUpVCtrl.setColor('red') self.clavicleUpVCtrl.rotatePoints(-90.0, 0.0, 0.0) self.clavicleUpVCtrl.rotatePoints(0.0, 90.0, 0.0) self.clavicleUpVCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) self.clavicleEndCtrl = Control('clavicleEnd', parent=self.ctrlCmpGrp, shape="cube") self.clavicleEndCtrl.scalePoints(Vec3(0.25, 0.25, 0.25)) self.default_data = { "name": name, "location": "L", "clavicleXfo": Xfo(Vec3(0.15, 15.5, -0.5)), "clavicleUpVXfo": Xfo(Vec3(0.15, 16.5, -0.5)), "clavicleEndXfo": Xfo(Vec3(2.25, 15.5, -0.75)) } self.loadData(self.default_data) Profiler.getInstance().pop()
def __init__(self, name='arm', parent=None, *args, **kwargs): Profiler.getInstance().push("Construct Arm Guide Component:" + name) super(ArmComponentGuide, self).__init__(name, parent, *args, **kwargs) # =========== # Attributes # =========== # Add Component Params to IK control guideSettingsAttrGrp = AttributeGroup("GuideSettings", parent=self) self.bicepFKCtrlSizeInputAttr = ScalarAttribute( 'bicepFKCtrlSize', value=1.75, minValue=0.0, maxValue=10.0, parent=guideSettingsAttrGrp) self.forearmFKCtrlSizeInputAttr = ScalarAttribute( 'forearmFKCtrlSize', value=1.5, minValue=0.0, maxValue=10.0, parent=guideSettingsAttrGrp) # ========= # Controls # ========= # Guide Controls self.bicepCtrl = Control('bicep', parent=self.ctrlCmpGrp, shape="sphere") self.bicepCtrl.setColor('blue') self.forearmCtrl = Control('forearm', parent=self.ctrlCmpGrp, shape="sphere") self.forearmCtrl.setColor('blue') self.wristCtrl = Control('wrist', parent=self.ctrlCmpGrp, shape="sphere") self.wristCtrl.setColor('blue') armGuideSettingsAttrGrp = AttributeGroup("DisplayInfo_ArmSettings", parent=self.bicepCtrl) self.armGuideDebugAttr = BoolAttribute('drawDebug', value=True, parent=armGuideSettingsAttrGrp) self.guideOpHost = Transform('guideOpHost', self.ctrlCmpGrp) # Guide Operator self.armGuideKLOp = KLOperator('guide', 'TwoBoneIKGuideSolver', 'Kraken') self.addOperator(self.armGuideKLOp) # Add Att Inputs self.armGuideKLOp.setInput('drawDebug', self.armGuideDebugAttr) self.armGuideKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Source Inputs self.armGuideKLOp.setInput('root', self.bicepCtrl) self.armGuideKLOp.setInput('mid', self.forearmCtrl) self.armGuideKLOp.setInput('end', self.wristCtrl) # Add Target Outputs self.armGuideKLOp.setOutput('guideOpHost', self.guideOpHost) self.default_data = { "name": name, "location": "L", "bicepXfo": Xfo(Vec3(2.275, 15.3, -0.75)), "forearmXfo": Xfo(Vec3(5.0, 13.5, -0.75)), "wristXfo": Xfo(Vec3(7.2, 12.25, 0.5)), "bicepFKCtrlSize": self.bicepFKCtrlSizeInputAttr.getValue(), "forearmFKCtrlSize": self.forearmFKCtrlSizeInputAttr.getValue() } self.loadData(self.default_data) Profiler.getInstance().pop()
def __init__(self, name='arm', parent=None): Profiler.getInstance().push("Construct Arm Rig Component:" + name) super(ArmComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Bicep self.bicepFKCtrlSpace = CtrlSpace('bicepFK', parent=self.ctrlCmpGrp) self.bicepFKCtrl = Control('bicepFK', parent=self.bicepFKCtrlSpace, shape="cube") self.bicepFKCtrl.alignOnXAxis() self.bicepFKCtrl.lockScale(True, True, True) self.bicepFKCtrl.lockTranslation(True, True, True) # Forearm self.forearmFKCtrlSpace = CtrlSpace('forearmFK', parent=self.bicepFKCtrl) self.forearmFKCtrl = Control('forearmFK', parent=self.forearmFKCtrlSpace, shape="cube") self.forearmFKCtrl.alignOnXAxis() self.forearmFKCtrl.lockScale(True, True, True) self.forearmFKCtrl.lockTranslation(True, True, True) # Arm IK self.armIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.armIKCtrl = Control('IK', parent=self.armIKCtrlSpace, shape="jack") self.armIKCtrl.scalePoints(Vec3(2.0, 2.0, 2.0)) self.armIKCtrl.lockScale(True, True, True) # Add Params to IK control armSettingsAttrGrp = AttributeGroup("DisplayInfo_ArmSettings", parent=self.armIKCtrl) self.armDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=armSettingsAttrGrp) self.armBone0LenInputAttr = ScalarAttribute('bone1Len', value=0.0, parent=armSettingsAttrGrp) self.armBone1LenInputAttr = ScalarAttribute('bone2Len', value=0.0, parent=armSettingsAttrGrp) self.armIKBlendInputAttr = ScalarAttribute('fkik', value=0.0, minValue=0.0, maxValue=1.0, parent=armSettingsAttrGrp) # Util Objects self.ikRootPosition = Transform("ikPosition", parent=self.ctrlCmpGrp) # Connect Input Attrs self.drawDebugInputAttr.connect(self.armDebugInputAttr) # Connect Output Attrs self.drawDebugOutputAttr.connect(self.armDebugInputAttr) self.ikBlendOutputAttr.connect(self.armIKBlendInputAttr) # UpV self.armUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.armUpVCtrl = Control('UpV', parent=self.armUpVCtrlSpace, shape="triangle") self.armUpVCtrl.alignOnZAxis() self.armUpVCtrl.rotatePoints(180, 0, 0) self.armIKCtrl.lockScale(True, True, True) self.armIKCtrl.lockRotation(True, True, True) # ========== # Deformers # ========== self.deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=self.deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.bicepDef = Joint('bicep', parent=self.defCmpGrp) self.bicepDef.setComponent(self) self.elbowDef = Joint('elbow', parent=self.defCmpGrp) self.elbowDef.setComponent(self) self.forearmDef = Joint('forearm', parent=self.defCmpGrp) self.forearmDef.setComponent(self) self.wristDef = Joint('wrist', parent=self.defCmpGrp) self.wristDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.armIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.armIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.armIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.armIKCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.armIKCtrlSpace.addConstraint(self.armIKCtrlSpaceInputConstraint) self.armUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.armUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.armUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.armUpVCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.armUpVCtrlSpace.addConstraint(self.armUpVCtrlSpaceInputConstraint) self.armRootInputConstraint = PoseConstraint('_'.join([ self.bicepFKCtrlSpace.getName(), 'To', self.rootInputTgt.getName() ])) self.armRootInputConstraint.setMaintainOffset(True) self.armRootInputConstraint.addConstrainer(self.rootInputTgt) self.bicepFKCtrlSpace.addConstraint(self.armRootInputConstraint) self.ikPosInputConstraint = PoseConstraint('_'.join( [self.ikRootPosition.getName(), 'To', self.rootInputTgt.getName()])) self.ikPosInputConstraint.setMaintainOffset(True) self.ikPosInputConstraint.addConstrainer(self.rootInputTgt) self.ikRootPosition.addConstraint(self.ikPosInputConstraint) # Constraint outputs # =============== # Add Splice Ops # =============== # Add Splice Op self.armSolverKLOperator = KLOperator('ikSolver', 'TwoBoneIKSolver', 'Kraken') self.addOperator(self.armSolverKLOperator) # Add Att Inputs self.armSolverKLOperator.setInput('drawDebug', self.drawDebugInputAttr) self.armSolverKLOperator.setInput('rigScale', self.rigScaleInputAttr) self.armSolverKLOperator.setInput('bone0Len', self.armBone0LenInputAttr) self.armSolverKLOperator.setInput('bone1Len', self.armBone1LenInputAttr) self.armSolverKLOperator.setInput('ikblend', self.armIKBlendInputAttr) self.armSolverKLOperator.setInput('rightSide', self.rightSideInputAttr) # Add Xfo Inputs self.armSolverKLOperator.setInput('root', self.ikRootPosition) self.armSolverKLOperator.setInput('bone0FK', self.bicepFKCtrl) self.armSolverKLOperator.setInput('bone1FK', self.forearmFKCtrl) self.armSolverKLOperator.setInput('ikHandle', self.armIKCtrl) self.armSolverKLOperator.setInput('upV', self.armUpVCtrl) # Add Xfo Outputs self.armSolverKLOperator.setOutput('bone0Out', self.bicepOutputTgt) self.armSolverKLOperator.setOutput('bone1Out', self.forearmOutputTgt) self.armSolverKLOperator.setOutput('bone2Out', self.wristOutputTgt) self.armSolverKLOperator.setOutput('midJointOut', self.elbowOutputTgt) # Add Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('defConstraint', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [ self.bicepOutputTgt, self.elbowOutputTgt, self.forearmOutputTgt, self.wristOutputTgt ]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput( 'constrainees', [self.bicepDef, self.elbowDef, self.forearmDef, self.wristDef]) Profiler.getInstance().pop()
def __init__(self, name, parent=None, location='M'): super(HandComponent, self).__init__(name, parent, location) # ========= # Controls # ========= # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values if location == 'R': ctrlColor = "red" handPosition = Vec3(-7.1886, 12.2819, 0.4906) handUpV = Vec3(-7.7463, 13.1746, 0.4477) handEndPosition = Vec3(-7.945, 11.8321, 0.9655) else: ctrlColor = "greenBright" handPosition = Vec3(7.1886, 12.2819, 0.4906) handUpV = Vec3(7.7463, 13.1746, 0.4477) handEndPosition = Vec3(7.945, 11.8321, 0.9655) # Calculate Clavicle Xfo rootToEnd = handEndPosition.subtract(handPosition).unit() rootToUpV = handUpV.subtract(handPosition).unit() bone1ZAxis = rootToEnd.cross(rootToUpV).unit() bone1Normal = rootToEnd.cross(bone1ZAxis).unit() handXfo = Xfo() if location == "R": handQuat = Quat(Vec3(-0.2301, -0.0865, -0.9331), 0.2623) handPos = Vec3(-7.1886, 12.2819, 0.4906) else: handQuat = Quat(Vec3(-0.0865, -0.2301, -0.2623), 0.9331) handPos = Vec3(7.1886, 12.2819, 0.4906) handXfo.rot = handQuat.clone() handXfo.tr.copy(handPos) # Add Controls handCtrlSrtBuffer = SrtBuffer('hand', parent=self) handCtrlSrtBuffer.xfo.copy(handXfo) handCtrl = CubeControl('hand', parent=handCtrlSrtBuffer) handCtrl.alignOnXAxis() handCtrl.scalePoints(Vec3(2.0, 0.75, 1.25)) handCtrl.xfo.copy(handCtrlSrtBuffer.xfo) handCtrl.setColor(ctrlColor) # Rig Ref objects handRefSrt = Locator('handRef', parent=self) handRefSrt.xfo.copy(handCtrlSrtBuffer.xfo) # Add Component Params to IK control handDebugInputAttr = BoolAttribute('debug', True) handLinkToWorldInputAttr = FloatAttribute('linkToWorld', 0.0, 0.0, 1.0) handSettingsAttrGrp = AttributeGroup("DisplayInfo_HandSettings") handCtrl.addAttributeGroup(handSettingsAttrGrp) handSettingsAttrGrp.addAttribute(handDebugInputAttr) handSettingsAttrGrp.addAttribute(handLinkToWorldInputAttr) # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') handDef = Joint('hand') handDef.setComponent(self) deformersLayer.addChild(handDef) # ===================== # Create Component I/O # ===================== # Setup Component Xfo I/O's armEndXfoInput = Locator('armEndXfo') armEndXfoInput.xfo.copy(handCtrlSrtBuffer.xfo) armEndPosInput = Locator('armEndPos') armEndPosInput.xfo.copy(handCtrlSrtBuffer.xfo) handEndOutput = Locator('handEnd') handEndOutput.xfo.copy(handCtrlSrtBuffer.xfo) handOutput = Locator('hand') handOutput.xfo.copy(handCtrlSrtBuffer.xfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') linkToWorldInputAttr = FloatAttribute('linkToWorld', 0.0, 0.0, 1.0) # Connect attrs to control attrs debugInputAttr.connect(handDebugInputAttr) linkToWorldInputAttr.connect(handLinkToWorldInputAttr) # ============== # Constrain I/O # ============== # Constraint inputs # Constraint outputs handConstraint = PoseConstraint('_'.join([handOutput.getName(), 'To', handCtrl.getName()])) handConstraint.addConstrainer(handCtrl) handOutput.addConstraint(handConstraint) handEndConstraint = PoseConstraint('_'.join([handEndOutput.getName(), 'To', handCtrl.getName()])) handEndConstraint.addConstrainer(handCtrl) handEndOutput.addConstraint(handEndConstraint) # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(armEndXfoInput) self.addInput(armEndPosInput) self.addOutput(handOutput) self.addOutput(handEndOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(rightSideInputAttr) self.addInput(linkToWorldInputAttr)
class Object3D(SceneItem): """Kraken base object type for any 3D object.""" def __init__(self, name, parent=None, flags=None, metaData=None): super(Object3D, self).__init__(name, parent=parent, metaData=metaData) self._children = [] self._flags = {} self._attributeGroups = [] self._constraints = [] self._xfo = Xfo() self._ro = RotationOrder() self._color = None self._implicitAttrGrp = AttributeGroup("implicitAttrGrp", self) self._visibility = BoolAttribute('visibility', True, self._implicitAttrGrp) self._shapeVisibility = BoolAttribute('ShapeVisibility', True, self._implicitAttrGrp) if parent is not None: parent.addChild(self) if flags is not None: assert type( flags ) is str, "Flags argument must be a comma separated string." for flag in flags.replace(' ', '').split(','): if not re.match("[\w]*$", flag): msg = "{} '{}' {} ({}: {}) {}\n".format( "Invalid flag", flag, "set on", self.getName(), self.getPath(), ". Alphanumeric and underscores only!") logger.warn(msg) continue self.setFlag(flag) # ================== # Property Methods # ================== @property def xfo(self): """Gets xfo property of this Object3D. Returns: Xfo: Xfo property of this Object3D. """ return self._xfo @xfo.setter def xfo(self, value): """Sets xfo of this Object3D. Note: In Python, objects are always referenced, meaning to get a unique instance, an explicit clone is required. In KL, structs are passed by value, meaning that every assignment of a struct causes a clone. This means that in KL it is impossible for 2 objects to reference the same KL math object. This is an important performance feature of KL. The members of the KL Math objects have this property. 2 Xfos cannot share the same tr value. Here we implcitly clone the math object to ensure the same behavior as in KL. Args: value (Xfo): Vector to set the xfo by. Returns: bool: True if successful. """ self._xfo = value.clone() return True @property def ro(self): """Gets Rotation Order property of this Object3D. Returns: RotationOrder: Rotation Order property of this Object3D. """ return self._ro @ro.setter def ro(self, value): """Sets Rotation Order of this Object3D. Note: In Python, objects are always referenced, meaning to get a unique instance, an explicit clone is required. In KL, structs are passed by value, meaning that every assignment of a struct causes a clone. This means that in KL it is impossible for 2 objects to reference the same KL math object. This is an important performance feature of KL. The members of the KL Math objects have this property. 2 Xfos cannot share the same tr value. Here we implcitly clone the math object to ensure the same behavior as in KL. Args: value (RotationOrder): New rotation order. Returns: bool: True if successful. """ self._ro = value.clone() return True @property def localXfo(self): """Gets local transform of this Object3D Returns: Xfo: Local Xfo of the object. """ globalXfo = self.globalXfo parent = self.getParent() if not isinstance(parent, SceneItem): return globalXfo parentXfo = parent.globalXfo return parentXfo.inverse().multiply(globalXfo) @property def globalXfo(self): """Gets global transform of this Object3D Returns: Xfo: Global Xfo """ for source in self.getSources(): if isinstance(source, Object3D): continue if isinstance(source, Constraint): return source.compute() if isinstance(source, Operator): source.evaluate() break return self._xfo # ============= # Name Methods # ============= def getBuildName(self): """Returns the build name for the object. Returns: str: Name to be used in the DCC. """ typeNameHierarchy = self.getTypeHierarchyNames() config = Config.getInstance() # If flag is set on object to use explicit name, return it. if config.getExplicitNaming() is True or \ self.testFlag('EXPLICIT_NAME'): return self.getName() nameTemplate = config.getNameTemplate() # Get the token list for this type of object format = None for typeName in nameTemplate['formats'].keys(): if typeName in typeNameHierarchy: format = nameTemplate['formats'][typeName] break if format is None: format = nameTemplate['formats']['default'] objectType = None for eachType in typeNameHierarchy: if eachType in nameTemplate['types'].keys(): objectType = eachType break if objectType is None: objectType = 'default' # Generate a name by concatenating the resolved tokens together. builtName = "" skipSep = False for token in format: if token is 'sep': if not skipSep: builtName += nameTemplate['separator'] elif token is 'location': if self.isTypeOf('Component'): location = self.getLocation() else: component = self.getComponent() if component is None: raise ValueError( "object [%s] does not have a component." % self.getName()) location = component.getLocation() altLocation = self.getMetaDataItem("altLocation") if altLocation is not None and altLocation in nameTemplate[ 'locations']: location = altLocation if location not in nameTemplate['locations']: msg = "Invalid location on '{}'. Location: {}. Valid locations: {}".format( self.getPath(), location, nameTemplate['locations']) raise ValueError(msg) builtName += location elif token is 'type': if objectType == 'Locator' and self.testFlag('inputObject'): objectType = 'ComponentInput' elif objectType == 'Locator' and self.testFlag('outputObject'): objectType = 'ComponentOutput' altType = self.getMetaDataItem("altType") if altType is not None and nameTemplate['types'].get( altType, None) is not None: objectType = altType builtName += nameTemplate['types'][objectType] elif token is 'name': builtName += self.getName() elif token is 'component': if self.getComponent() is None: skipSep = True continue builtName += self.getComponent().getName() elif token is 'container': if self.getContainer() is None: skipSep = True continue builtName += self.getContainer().getName() else: raise ValueError("Unresolvabled token '" + token + "' used on: " + self.getPath()) return builtName def setName(self, name): """Sets the name of the object with a string. Args: name (str): The new name for the item. Returns: bool: True if successful. """ # check for name collision and adjust the name if they exist if self.getParent() is not None: # Increment name if it already exists initName = name suffix = 1 collision = True while collision: child = self.getParent().getChildByDecoratedName( name + self.getNameDecoration()) collision = child is not None and child is not self if not collision: break result = re.split(r"(\d+)$", initName, 1) if len(result) > 1: initName = result[0] suffix = int(result[1]) name = initName + str(suffix).zfill(2) suffix += 1 super(Object3D, self).setName(name) return True # ================== # Hierarchy Methods # ================== def getContainer(self): """Returns the Container the object belongs to. Returns: Object: Container. """ parent = self.getParent() while (parent is not None and 'Container' not in parent.getTypeHierarchyNames()): parent = parent.getParent() return parent def getLayer(self): """Returns the Layer the object belongs to. Returns: Object: Layer this object belongs to. """ parent = self.getParent() while (parent is not None and not parent.isTypeOf('Layer')): parent = parent.getParent() return parent # ============== # Child Methods # ============== def hasChild(self, child): """Checks the supplied item is a child Args: child (Object): Object to check if is is a child of this object. """ for i, eachChild in enumerate(self.getChildren()): if eachChild == child: return True return False def _checkChildIndex(self, index): """Checks the supplied index is valid. Args: index (int): Child index to check. """ if index > len(self.getChildren()): raise IndexError("'" + str(index) + "' is out of the range of the 'children' array.") return True def addChild(self, child): """Adds a child to this object. Note: We allow for duplicate child names as long as the types differ. Args: child (Object): Object that will be a child of this object. Returns: bool: True if successful. """ SceneItem.setParent(child, self) if child.getParent() is not None: parent = child.getParent() if child in parent.getChildren(): parent.getChildren().remove(child) child.setName(child.getName()) self.getChildren().append(child) # Assign the child the same component. if self._component is not None: child.setComponent(self._component) return True def setParent(self, parent): """Sets the parent of this object. Arguments: parent (Object): Object that is the parent of this one. Returns: bool: True if successful. """ if parent: parent.addChild(self) else: if self._parent is not None: parent.removeChild(self) SceneItem.setParent(self, None) return True def removeChildByIndex(self, index): """Removes a child from this object by index. Args: index (int): Index of child to remove. Returns: bool: True if successful. """ if self._checkChildIndex(index) is not True: return False self.removeChild(self.getChildren()[index]) return True def removeChildByName(self, name): """Removes a child from this object by name. Args: name (str): Name of child to remove. Returns: bool: True if successful. """ removeIndex = None for i, eachChild in enumerate(self.getChildren()): if eachChild.getName() == name: removeIndex = i if removeIndex is None: raise ValueError("'" + name + "' is not a valid child of this object.") self.removeChildByIndex(removeIndex) return True def removeChild(self, child): """Removed the child as an child item of this object. Returns: bool: True if successful. """ try: self._children.remove(child) except: names = [] for c in self._children: names.append(c.getName()) raise Exception("Object '" + self.getPath() + "' does not have child:" + child.getPath() + ". it does have:" + str(names)) SceneItem.setParent(child, None) # Un-assign the child the component. if self._component is not None: child.setComponent(None) return True def getDescendents(self, nodeList=None, classType=None, inheritedClass=False): """Gets the children of this object. Args: nodeList: (list): optional list to append children to classType (str): Name of the type of class to limit the search to inheritedClass (bool): Match nodes that is a sub-class of type. Returns: list: Child objects. """ if nodeList is None: nodeList = [] for child in self._children: if classType is not None: if inheritedClass is not None and child.isTypeOf(classType): nodeList.append(child) elif child.getTypeName() == classType: nodeList.append(child) else: nodeList.append(child) child.getDescendents(classType=classType, nodeList=nodeList, inheritedClass=inheritedClass) return nodeList def getChildren(self): """Gets the children of this object. Returns: list: Child objects. """ return self._children def getNumChildren(self): """Returns the number of children this object has. Returns: int: Number of children of this object. """ return len(self.getChildren()) def getChildByIndex(self, index): """Returns the child object at specified index. Args: index (int): Index of the child to find. Returns: Object: Child object at specified index. """ if self._checkChildIndex(index) is not True: return False return self.getChildren()[index] def getChildByName(self, name): """Returns the child object with the specified name. Args: name (str): Name of the child to return. Returns: Object: Object if found. """ for eachChild in self.getChildren(): if eachChild.getName() == name: return eachChild return None def getChildByDecoratedName(self, decoratedName): """Returns the child object with the specified name. Args: decoratedName (str): Decorated name of the child to find. Returns: Object: Object if found. """ for eachChild in self.getChildren(): if eachChild.getDecoratedName() == decoratedName: return eachChild return None def getChildrenByType(self, childType): """Returns all children that are of the specified type. Args: childType (str): Type of children to find. Returns: list: Array of child objects of the specified type. """ childrenOfType = [] for eachChild in self.getChildren(): if eachChild.isTypeOf(childType): childrenOfType.append(eachChild) return childrenOfType # ======================== # Attribute Group Methods # ======================== def _checkAttributeGroupIndex(self, index): """Checks the supplied index is valid. Args: index (int): Attribute index to check. Returns: bool: True if successful. """ if index > len(self._attributeGroups): raise IndexError( "'" + str(index) + "' is out of the range of 'attributeGroups' array.") return True def addAttributeGroup(self, attributeGroup): """Adds an attributeGroup to this object. Args: attributeGroup (Object): Attribute Group object to add to this object. Returns: bool: True if successful. """ if attributeGroup.getName() in [ x.getName() for x in self._attributeGroups ]: raise IndexError("Child with " + attributeGroup.getName() + " already exists as a attributeGroup.") self._attributeGroups.append(attributeGroup) attributeGroup.setParent(self) return True def removeAttributeGroupByIndex(self, index): """Removes attribute at specified index. Args: index (int): Index of attribute to remove. Returns: bool: True if successful. """ if self._checkAttributeGroupIndex(index) is not True: return False del self._attributeGroups[index] return True def removeAttributeGroupByName(self, name): """Removes the attribute with the specified name. Args: name (str): Name of the attribute to remove. Returns: bool: True if successful. """ removeIndex = None for i, eachAttributeGroup in enumerate(self._attributeGroups): if eachAttributeGroup.getName() == name: removeIndex = i if removeIndex is None: return False self.removeAttributeGroupByIndex(removeIndex) return True def getNumAttributeGroups(self): """Returns the number of attributeGroups as an integer. Returns: int: Number of attributeGroups on this object. """ return len(self._attributeGroups) def getAttributeGroupByIndex(self, index): """Returns the attribute at the specified index. Args: index (int): Index of the attribute to return. Returns: AttributeGroup: Attribute Group at the specified index. """ if self._checkAttributeGroupIndex(index) is not True: return False return self._attributeGroups[index] def getAttributeGroupByName(self, name): """Return the attribute group with the specified name. Args: name (str): Name of the attribute group to return. Returns: Attribute: Attribute with the specified name. """ for eachAttributeGroup in self._attributeGroups: if eachAttributeGroup.getName() == name: return eachAttributeGroup return None # =================== # Constraint Methods # =================== def checkConstraintIndex(self, index): """Checks the supplied index is valid. Args: index (int): Constraint index to check. Returns: bool: True if successful. """ if index > len(self._constraints): raise IndexError("'" + str(index) + "' is out of the range of 'constraints' array.") return True def constrainTo(self, constrainers, constraintType="Pose", maintainOffset=False, name=None): """Adds an constraint to this object. Args: constrainers (Object or Object list): Constraint object to add to this object or objects. constraintType (str): String name of the constraint type. maintainOffset (bool): Sets the constraint to maintain offset when creating the constraint. name (str): Name of the constraint. If set to None, a name is automatically generated. Returns: string: Constraint object """ if name is None: constraintName = "" if hasattr(constrainers, '__iter__'): constraintName = '_'.join([ self.getName(), 'To', constrainers[0].getName(), constraintType + 'Constraint' ]) else: constraintName = '_'.join([ self.getName(), 'To', constrainers.getName(), constraintType + 'Constraint' ]) else: constraintName = name constraint = None if constraintType == "Orientation": constraint = OrientationConstraint(constraintName) elif constraintType == "Pose": constraint = PoseConstraint(constraintName) elif constraintType == "Position": constraint = PositionConstraint(constraintName) elif constraintType == "Scale": constraint = ScaleConstraint(constraintName) else: raise ValueError( "'" + constraintType + "' is not a valid constraint type. Valid types are Orientation, Pose, Position, or Scale" ) # Accept a single object or a list of objects if hasattr(constrainers, '__iter__'): pass else: constrainers = [constrainers] for constrainer in constrainers: constraint.addConstrainer(constrainer) constraint.setMaintainOffset(maintainOffset) self.addConstraint(constraint) return constraint def addConstraint(self, constraint): """Adds an constraint to this object. Args: constraint (Object): Constraint object to add to this object. Returns: bool: True if successful. """ if constraint.getName() in [x.getName() for x in self._constraints]: raise IndexError("Constraint with name '" + constraint.getName() + "'' already exists as a constraint.") for x in self._constraints: if x.isTypeOf(constraint.getTypeName()): raise IndexError("Constraint with type '" + constraint.getTypeName() + "'' already exists on object.") self._constraints.append(constraint) constraint.setParent(self) constraint.setConstrainee(self) return True def removeConstraintByIndex(self, index): """Removes constraint at specified index. Args: index (int): Index of constraint to remove. Returns: bool: True if successful. """ if self.checkConstraintIndex(index) is not True: return False sourceIndex = self._sources.index(self._constraints[index]) del self._sources[sourceIndex] del self._constraints[index] return True def removeConstraintByName(self, name): """Removes the constraint with the specified name. Args: name (str): Name of the constraint to remove. Returns: bool: True if successful. """ removeIndex = None for i, eachConstraint in enumerate(self._constraints): if eachConstraint.getName() == name: removeIndex = i if removeIndex is None: return False self.removeConstraintByIndex(removeIndex) return True def removeAllConstraints(self): """Removes all of the constraints for this object. Returns: bool: True if successful. """ while len(self._constraints) > 0: self.removeConstraintByIndex(0) return True def getNumConstraints(self): """Returns the number of constraints as an integer. Returns: int: Number of constraints on this object. """ return len(self._constraints) def getConstraintByIndex(self, index): """Returns the constraint at the specified index. Args: index (int): Index of the constraint to return. Returns: Constraint: Constraint at the specified index. """ if self.checkConstraintIndex(index) is not True: return False return self._constraints[index] def getConstraintByName(self, name): """Return the constraint group with the specified name. Args: name (str): Name of the constraint group to return. Returns: Attribute: Attribute with the specified name. """ for eachConstraint in self._constraints: if eachConstraint.getName() == name: return eachConstraint return None # =================== # Visibility Methods # =================== def getVisibilityAttr(self): """Returns the Visibility attribute object. Returns: BoolAttribute: Attribute that holds the value of the visibility. """ return self._visibility def getVisibility(self): """Returns the visibility status of the scene item. Returns: bool: Visible or not. """ return self._visibility.getValue() def setVisibility(self, value): """Sets the visibility of the scene object. Args: value (bool): value of the visibility of the object. Returns: bool: True if successful. """ self._visibility.setValue(value) return True def getShapeVisibilityAttr(self): """Returns the Shape Visibility attribute object. Returns: BoolAttribute: Attribute that holds the value of the shape visibility. """ return self._shapeVisibility def getShapeVisibility(self): """Returns the shape visibility status of the scene item. Returns: bool: Visible or not. """ return self._shapeVisibility.getValue() def setShapeVisibility(self, value): """Sets the shape visibility of the scene object. Args: value (bool): Value of the visibility of the object. Returns: bool: True if successful. """ self._shapeVisibility.setValue(value) return True # ================ # Display Methods # ================ def setColor(self, color): """Sets the color of this object. Args: color (str, Color): Name of the color from the Config or a Color() object. Returns: bool: True if successful. """ assert type(color).__name__ in ('str', 'Color'), self.getPath() + \ ".setColor(), 'color' argument type is not of type 'str' or 'Color'." self._color = color return True def getColor(self): """Returns the color of the object. Returns: str: Color of the object. """ return self._color # ========================== # Parameter Locking Methods # ========================== def lockRotation(self, x=False, y=False, z=False): """Sets flags for locking rotation parameters. Args: x (bool): Lock x axis. y (bool): Lock y axis. z (bool): Lock z axis. Returns: bool: True if successful. """ if x is True: self.setFlag("lockXRotation") if y is True: self.setFlag("lockYRotation") if z is True: self.setFlag("lockZRotation") return True def lockScale(self, x=False, y=False, z=False): """Sets flags for locking scale parameters. Args: x (bool): Lock x axis. y (bool): Lock y axis. z (bool): Lock z axis. Returns: bool: True if successful. """ if x is True: self.setFlag("lockXScale") if y is True: self.setFlag("lockYScale") if z is True: self.setFlag("lockZScale") return True def lockTranslation(self, x=False, y=False, z=False): """Sets flags for locking translation parameters. Args: x (bool): Lock x axis. y (bool): Lock x axis. z (bool): Lock x axis. Returns: bool: True if successful. """ if x is True: self.setFlag("lockXTranslation") if y is True: self.setFlag("lockYTranslation") if z is True: self.setFlag("lockZTranslation") return True # ==================== # Persistence Methods # ==================== def jsonEncode(self, saver): """Encodes the object to a JSON structure. Args: saver (Object): saver object. Returns: Dict: A JSON structure containing the data for this SceneItem. """ classHierarchy = self.getTypeHierarchyNames() jsonData = { '__typeHierarchy__': classHierarchy, 'name': self.getName(), 'parent': None, 'children': [], 'flags': self._flags, 'attributeGroups': [], 'constraints': [], 'xfo': self.xfo.jsonEncode(), 'color': self.getColor(), 'visibility': self._visibility, 'shapeVisibility': self._shapeVisibility, } if self.getParent() is not None: jsonData['parent'] = self.getParent().getName() if self.getColor() is not None: jsonData['color'] = saver.encodeValue(self.getColor()) for child in self.getChildren(): jsonData['children'].append(child.jsonEncode(saver)) for attrGroup in self._attributeGroups: jsonData['attributeGroups'].append(attrGroup.jsonEncode(saver)) for constr in self._constraints: jsonData['constraints'].append(constr.jsonEncode(saver)) return jsonData def jsonDecode(self, loader, jsonData): """Returns the color of the object.. Args: loader (Object): Loader object. jsonData (Dict): JSON object structure. Returns: bool: True if successful. """ self._flags = jsonData['flags'] self.xfo = loader.decodeValue(jsonData['xfo']) if 'color' in jsonData and jsonData['color'] is not None: self.setColor(loader.decodeValue(jsonData['color'])) self._visibility = jsonData['visibility'] self._shapeVisibility = jsonData['shapeVisibility'] for child in jsonData['children']: self.addChild(loader.construct(child)) for attrGroup in jsonData['attributeGroups']: # There is one default attribute group assigned to each scene item. # Load data into the existing item instead of constructing a new # one. if attrGroup['name'] == '': loader.registerItem(self._attributeGroups[0]) self._attributeGroups[0].jsonDecode(loader, attrGroup) else: self.addAttributeGroup(loader.construct(attrGroup)) for constr in jsonData['constraints']: self.addConstraint(loader.construct(constr)) return True
def __init__(self, name='InsectLeg', parent=None): Profiler.getInstance().push("Construct InsectLeg Rig Component:" + name) super(InsectLegComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Chain Base self.chainBase = Locator('ChainBase', parent=self.ctrlCmpGrp) self.chainBase.setShapeVisibility(False) # FK self.fkCtrlSpaces = [] self.fkCtrls = [] self.setNumControls(4) # IK Control self.legIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.legIKCtrl = Control('IK', parent=self.legIKCtrlSpace, shape="pin") if self.getLocation() == 'R': self.legIKCtrl.rotatePoints(0, 90, 0) self.legIKCtrl.translatePoints(Vec3(-1.0, 0.0, 0.0)) else: self.legIKCtrl.rotatePoints(0, -90, 0) self.legIKCtrl.translatePoints(Vec3(1.0, 0.0, 0.0)) # Add Component Params to IK control legSettingsAttrGrp = AttributeGroup("DisplayInfo_LegSettings", parent=self.legIKCtrl) legdrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=legSettingsAttrGrp) legUseInitPoseInputAttr = BoolAttribute('useInitPose', value=True, parent=legSettingsAttrGrp) self.rootIndexInputAttr = IntegerAttribute('rootIndex', value=0, parent=legSettingsAttrGrp) legFkikInputAttr = ScalarAttribute('fkik', value=1.0, minValue=0.0, maxValue=1.0, parent=legSettingsAttrGrp) # Connect IO to controls self.drawDebugInputAttr.connect(legdrawDebugInputAttr) # UpV self.legUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.legUpVCtrl = Control('UpV', parent=self.legUpVCtrlSpace, shape="triangle") self.legUpVCtrl.alignOnZAxis() self.legUpVCtrl.rotatePoints(0, 90, 0) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.deformerJoints = [] self.boneOutputsTgt = [] self.setNumDeformers(4) # ===================== # Create Component I/O # ===================== # Set IO Targets self.boneOutputs.setTarget(self.boneOutputsTgt) # ============== # Constrain I/O # ============== # Constraint inputs legRootInputConstraint = PoseConstraint('_'.join([ self.fkCtrlSpaces[0].getName(), 'To', self.rootInputTgt.getName() ])) legRootInputConstraint.setMaintainOffset(True) legRootInputConstraint.addConstrainer(self.rootInputTgt) self.fkCtrlSpaces[0].addConstraint(legRootInputConstraint) chainBaseInputConstraint = PoseConstraint('_'.join( [self.chainBase.getName(), 'To', self.rootInputTgt.getName()])) chainBaseInputConstraint.setMaintainOffset(True) chainBaseInputConstraint.addConstrainer(self.rootInputTgt) self.chainBase.addConstraint(chainBaseInputConstraint) # =============== # Add Canvas Ops # =============== # Add Canvas Op self.nBoneSolverKLOp = KLOperator('leg', 'NBoneIKSolver', 'Kraken') self.addOperator(self.nBoneSolverKLOp) # # Add Att Inputs self.nBoneSolverKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.nBoneSolverKLOp.setInput('rigScale', self.rigScaleInputAttr) self.nBoneSolverKLOp.setInput('useInitPose', legUseInitPoseInputAttr) self.nBoneSolverKLOp.setInput('ikblend', legFkikInputAttr) self.nBoneSolverKLOp.setInput('rootIndex', self.rootIndexInputAttr) self.nBoneSolverKLOp.setInput('tipBoneLen', self.tipBoneLenInputAttr) # Add Xfo Inputs self.nBoneSolverKLOp.setInput('chainBase', self.chainBase) self.nBoneSolverKLOp.setInput('ikgoal', self.legIKCtrl) self.nBoneSolverKLOp.setInput('upVector', self.legUpVCtrl) self.nBoneSolverKLOp.setInput('fkcontrols', self.fkCtrls) # Add Xfo Outputs self.nBoneSolverKLOp.setOutput('pose', self.boneOutputsTgt) self.nBoneSolverKLOp.setOutput('legEnd', self.legEndPosOutputTgt) # Add Deformer Canvas Op self.outputsToDeformersKLOp = KLOperator('defConstraint', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', self.boneOutputsTgt) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', self.deformerJoints) Profiler.getInstance().pop()
class StretchyLimbComponentRig(StretchyLimbComponent): """StretchyLimb Component""" def __init__(self, name='limb', parent=None): Profiler.getInstance().push("Construct StretchyLimb Rig Component:" + name) super(StretchyLimbComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Upper (FK) self.upperFKCtrlSpace = CtrlSpace('upperFK', parent=self.ctrlCmpGrp) self.upperFKCtrl = Control('upperFK', parent=self.upperFKCtrlSpace, shape="cube") self.upperFKCtrl.alignOnXAxis() # Lower (FK) self.lowerFKCtrlSpace = CtrlSpace('lowerFK', parent=self.upperFKCtrl) self.lowerFKCtrl = Control('lowerFK', parent=self.lowerFKCtrlSpace, shape="cube") self.lowerFKCtrl.alignOnXAxis() # End (IK) self.limbIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.limbIKCtrl = Control('IK', parent=self.limbIKCtrlSpace, shape="pin") # Add Component Params to IK control # TODO: Move these separate control limbSettingsAttrGrp = AttributeGroup("DisplayInfo_StretchyLimbSettings", parent=self.limbIKCtrl) limbDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=limbSettingsAttrGrp) self.limbBone0LenInputAttr = ScalarAttribute('bone0Len', value=1.0, parent=limbSettingsAttrGrp) self.limbBone1LenInputAttr = ScalarAttribute('bone1Len', value=1.0, parent=limbSettingsAttrGrp) limbIKBlendInputAttr = ScalarAttribute('ikblend', value=1.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSoftIKInputAttr = BoolAttribute('softIK', value=True, parent=limbSettingsAttrGrp) limbSoftRatioInputAttr = ScalarAttribute('softRatio', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbStretchInputAttr = BoolAttribute('stretch', value=True, parent=limbSettingsAttrGrp) limbStretchBlendInputAttr = ScalarAttribute('stretchBlend', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSlideInputAttr = ScalarAttribute('slide', value=0.0, minValue=-1.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbPinInputAttr = ScalarAttribute('pin', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) self.rightSideInputAttr = BoolAttribute('rightSide', value=False, parent=limbSettingsAttrGrp) self.drawDebugInputAttr.connect(limbDrawDebugInputAttr) # UpV (IK Pole Vector) self.limbUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.limbUpVCtrl = Control('UpV', parent=self.limbUpVCtrlSpace, shape="triangle") self.limbUpVCtrl.alignOnZAxis() # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) upperDef = Joint('upper', parent=self.defCmpGrp) upperDef.setComponent(self) lowerDef = Joint('lower', parent=self.defCmpGrp) lowerDef.setComponent(self) endDef = Joint('end', parent=self.defCmpGrp) endDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.limbIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.limbIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.limbIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbIKCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.limbIKCtrlSpace.addConstraint(self.limbIKCtrlSpaceInputConstraint) self.limbUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.limbUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.limbUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbUpVCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.limbUpVCtrlSpace.addConstraint(self.limbUpVCtrlSpaceInputConstraint) self.limbRootInputConstraint = PoseConstraint('_'.join([self.limbIKCtrl.getName(), 'To', self.limbParentInputTgt.getName()])) self.limbRootInputConstraint.setMaintainOffset(True) self.limbRootInputConstraint.addConstrainer(self.limbParentInputTgt) self.upperFKCtrlSpace.addConstraint(self.limbRootInputConstraint) # =============== # Add Splice Ops # =============== # Add StretchyLimb Splice Op self.limbIKKLOp = KLOperator('limbKLOp', 'TwoBoneStretchyIKSolver', 'Kraken') self.addOperator(self.limbIKKLOp) # Add Att Inputs self.limbIKKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.limbIKKLOp.setInput('rigScale', self.rigScaleInputAttr) self.limbIKKLOp.setInput('bone0Len', self.limbBone0LenInputAttr) self.limbIKKLOp.setInput('bone1Len', self.limbBone1LenInputAttr) self.limbIKKLOp.setInput('ikblend', limbIKBlendInputAttr) self.limbIKKLOp.setInput('softIK', limbSoftIKInputAttr) self.limbIKKLOp.setInput('softRatio', limbSoftRatioInputAttr) self.limbIKKLOp.setInput('stretch', limbStretchInputAttr) self.limbIKKLOp.setInput('stretchBlend', limbStretchBlendInputAttr) self.limbIKKLOp.setInput('slide', limbSlideInputAttr) self.limbIKKLOp.setInput('pin', limbPinInputAttr) self.limbIKKLOp.setInput('rightSide', self.rightSideInputAttr) # Add Xfo Inputs self.limbIKKLOp.setInput('root', self.limbParentInputTgt) self.limbIKKLOp.setInput('bone0FK', self.upperFKCtrl) self.limbIKKLOp.setInput('bone1FK', self.lowerFKCtrl) self.limbIKKLOp.setInput('ikHandle', self.limbIKCtrl) self.limbIKKLOp.setInput('upV', self.limbUpVCtrl) # Add Xfo Outputs self.limbIKKLOp.setOutput('bone0Out', self.limbUpperOutputTgt) self.limbIKKLOp.setOutput('bone1Out', self.limbLowerOutputTgt) self.limbIKKLOp.setOutput('bone2Out', self.limbEndOutputTgt) # ===================== # Connect the deformers # ===================== # Add StretchyLimb Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('limbDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [self.limbUpperOutputTgt, self.limbLowerOutputTgt, self.limbEndOutputTgt]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [upperDef, lowerDef, endDef]) Profiler.getInstance().pop() # ============= # Data Methods # ============= def loadData(self, data=None): """Load a saved guide representation from persisted data. Arguments: data -- object, The JSON data object. Return: True if successful. """ super(StretchyLimbComponentRig, self).loadData(data) upperXfo = data.get('upperXfo') upperLen = data.get('upperLen') lowerXfo = data.get('lowerXfo') lowerLen = data.get('lowerLen') endXfo = data.get('endXfo') upVXfo = data.get('upVXfo') self.upperFKCtrlSpace.xfo = upperXfo self.upperFKCtrl.xfo = upperXfo self.upperFKCtrl.scalePoints(Vec3(upperLen, 1.75, 1.75)) self.limbUpperOutputTgt.xfo = upperXfo self.limbLowerOutputTgt.xfo = lowerXfo self.lowerFKCtrlSpace.xfo = lowerXfo self.lowerFKCtrl.xfo = lowerXfo self.lowerFKCtrl.scalePoints(Vec3(lowerLen, 1.5, 1.5)) self.limbIKCtrlSpace.xfo.tr = endXfo.tr self.limbIKCtrl.xfo.tr = endXfo.tr if self.getLocation() == "R": self.limbIKCtrl.rotatePoints(0, 90, 0) self.limbIKCtrl.translatePoints(Vec3(-1.0, 0.0, 0.0)) else: self.limbIKCtrl.rotatePoints(0, -90, 0) self.limbIKCtrl.translatePoints(Vec3(1.0, 0.0, 0.0)) self.limbUpVCtrlSpace.xfo = upVXfo self.limbUpVCtrl.xfo = upVXfo self.limbBone0LenInputAttr.setMin(0.0) self.limbBone0LenInputAttr.setMax(upperLen * 3.0) self.limbBone0LenInputAttr.setValue(upperLen) self.limbBone1LenInputAttr.setMin(0.0) self.limbBone1LenInputAttr.setMax(lowerLen * 3.0) self.limbBone1LenInputAttr.setValue(lowerLen) self.limbParentInputTgt.xfo = upperXfo # Set Attrs self.rightSideInputAttr.setValue(self.getLocation() is 'R') # Eval Constraints self.limbIKCtrlSpaceInputConstraint.evaluate() self.limbUpVCtrlSpaceInputConstraint.evaluate() self.limbRootInputConstraint.evaluate() # Eval Operators self.limbIKKLOp.evaluate() self.outputsToDeformersKLOp.evaluate()
class LegComponentRig(LegComponent): """Leg Component""" def __init__(self, name='leg', parent=None): Profiler.getInstance().push("Construct Leg Rig Component:" + name) super(LegComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Femur self.femurFKCtrlSpace = CtrlSpace('femurFK', parent=self.ctrlCmpGrp) self.femurFKCtrl = Control('femurFK', parent=self.femurFKCtrlSpace, shape="cube") self.femurFKCtrl.alignOnXAxis() self.femurFKCtrl.lockTranslation(True, True, True) self.femurFKCtrl.lockScale(True, True, True) # Shin self.shinFKCtrlSpace = CtrlSpace('shinFK', parent=self.femurFKCtrl) self.shinFKCtrl = Control('shinFK', parent=self.shinFKCtrlSpace, shape="cube") self.shinFKCtrl.alignOnXAxis() self.shinFKCtrl.lockTranslation(True, True, True) self.shinFKCtrl.lockScale(True, True, True) # IK Handle self.legIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.legIKCtrl = Control('IK', parent=self.legIKCtrlSpace, shape="pin") self.legIKCtrl.lockScale(True, True, True) # Add Component Params to IK control legSettingsAttrGrp = AttributeGroup("DisplayInfo_LegSettings", parent=self.legIKCtrl) legDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=legSettingsAttrGrp) self.legRightSideInputAttr = BoolAttribute('rightSide', value=False, parent=legSettingsAttrGrp) self.legBone0LenInputAttr = ScalarAttribute('bone0Len', value=1.0, parent=legSettingsAttrGrp) self.legBone1LenInputAttr = ScalarAttribute('bone1Len', value=1.0, parent=legSettingsAttrGrp) legIKBlendInputAttr = ScalarAttribute('ikblend', value=1.0, minValue=0.0, maxValue=1.0, parent=legSettingsAttrGrp) # Util Objects self.ikRootPosition = Transform("ikRootPosition", parent=self.ctrlCmpGrp) # Connect Input Attrs self.drawDebugInputAttr.connect(legDrawDebugInputAttr) # Connect Output Attrs self.drawDebugOutputAttr.connect(legDrawDebugInputAttr) self.ikBlendOutputAttr.connect(legIKBlendInputAttr) # UpV self.legUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.legUpVCtrl = Control('UpV', parent=self.legUpVCtrlSpace, shape="triangle") self.legUpVCtrl.alignOnZAxis() self.legUpVCtrl.lockRotation(True, True, True) self.legUpVCtrl.lockScale(True, True, True) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) femurDef = Joint('femur', parent=self.defCmpGrp) femurDef.setComponent(self) kneeDef = Joint('knee', parent=self.defCmpGrp) kneeDef.setComponent(self) shinDef = Joint('shin', parent=self.defCmpGrp) shinDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.legIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.legIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.legIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.legIKCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.legIKCtrlSpace.addConstraint(self.legIKCtrlSpaceInputConstraint) self.legUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.legUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.legUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.legUpVCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.legUpVCtrlSpace.addConstraint(self.legUpVCtrlSpaceInputConstraint) self.legRootInputConstraint = PoseConstraint('_'.join([self.femurFKCtrlSpace.getName(), 'To', self.legPelvisInputTgt.getName()])) self.legRootInputConstraint.setMaintainOffset(True) self.legRootInputConstraint.addConstrainer(self.legPelvisInputTgt) self.femurFKCtrlSpace.addConstraint(self.legRootInputConstraint) self.ikRootPosInputConstraint = PoseConstraint('_'.join([self.ikRootPosition.getName(), 'To', self.legPelvisInputTgt.getName()])) self.ikRootPosInputConstraint.setMaintainOffset(True) self.ikRootPosInputConstraint.addConstrainer(self.legPelvisInputTgt) self.ikRootPosition.addConstraint(self.ikRootPosInputConstraint) # Constraint outputs self.legEndFKOutputConstraint = PoseConstraint('_'.join([self.legEndFKOutputTgt.getName(), 'To', self.shinFKCtrl.getName()])) self.legEndFKOutputConstraint.setMaintainOffset(True) self.legEndFKOutputConstraint.addConstrainer(self.shinFKCtrl) self.legEndFKOutputTgt.addConstraint(self.legEndFKOutputConstraint) self.ikHandleOutputConstraint = PoseConstraint('_'.join([self.ikHandleOutputTgt.getName(), 'To', self.legIKCtrl.getName()])) self.ikHandleOutputConstraint.setMaintainOffset(True) self.ikHandleOutputConstraint.addConstrainer(self.legIKCtrl) self.ikHandleOutputTgt.addConstraint(self.ikHandleOutputConstraint) # =============== # Add Splice Ops # =============== # Add Leg Splice Op self.legIKKLOp = KLOperator('legKLOp', 'TwoBoneIKSolver', 'Kraken') self.addOperator(self.legIKKLOp) # Add Att Inputs self.legIKKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.legIKKLOp.setInput('rigScale', self.rigScaleInputAttr) self.legIKKLOp.setInput('bone0Len', self.legBone0LenInputAttr) self.legIKKLOp.setInput('bone1Len', self.legBone1LenInputAttr) self.legIKKLOp.setInput('ikblend', legIKBlendInputAttr) self.legIKKLOp.setInput('rightSide', self.legRightSideInputAttr) # Add Xfo Inputs self.legIKKLOp.setInput('root', self.ikRootPosition) self.legIKKLOp.setInput('bone0FK', self.femurFKCtrl) self.legIKKLOp.setInput('bone1FK', self.shinFKCtrl) self.legIKKLOp.setInput('ikHandle', self.legIKTargetInputTgt) self.legIKKLOp.setInput('upV', self.legUpVCtrl) # Add Xfo Outputs self.legIKKLOp.setOutput('bone0Out', self.femurOutputTgt) self.legIKKLOp.setOutput('bone1Out', self.shinOutputTgt) self.legIKKLOp.setOutput('bone2Out', self.legEndOutputTgt) self.legIKKLOp.setOutput('midJointOut', self.kneeOutputTgt) # Add Leg Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('legDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [self.femurOutputTgt, self.kneeOutputTgt, self.shinOutputTgt]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [femurDef, kneeDef, shinDef]) Profiler.getInstance().pop() # ============= # Data Methods # ============= def loadData(self, data=None): """Load a saved guide representation from persisted data. Arguments: data -- object, The JSON data object. Return: True if successful. """ super(LegComponentRig, self).loadData( data ) createIKHandle = data.get('createIKHandle') femurXfo = data.get('femurXfo') kneeXfo = data.get('kneeXfo') handleXfo = data.get('handleXfo') upVXfo = data.get('upVXfo') femurLen = data.get('femurLen') shinLen = data.get('shinLen') self.femurFKCtrlSpace.xfo = femurXfo self.femurFKCtrl.xfo = femurXfo self.femurFKCtrl.scalePoints(Vec3(femurLen, 1.75, 1.75)) self.femurOutputTgt.xfo = femurXfo self.shinOutputTgt.xfo = kneeXfo self.shinFKCtrlSpace.xfo = kneeXfo self.shinFKCtrl.xfo = kneeXfo self.shinFKCtrl.scalePoints(Vec3(shinLen, 1.5, 1.5)) self.legEndFKOutputTgt.xfo.tr = handleXfo.tr self.legEndFKOutputTgt.xfo.ori = kneeXfo.ori self.ikHandleOutputTgt.xfo = handleXfo self.ikRootPosition.xfo = femurXfo self.legIKCtrlSpace.xfo = handleXfo self.legIKCtrl.xfo = handleXfo if self.getLocation() == 'R': self.legIKCtrl.rotatePoints(0, 90, 0) self.legIKCtrl.translatePoints(Vec3(-1.0, 0.0, 0.0)) else: self.legIKCtrl.rotatePoints(0, -90, 0) self.legIKCtrl.translatePoints(Vec3(1.0, 0.0, 0.0)) self.legUpVCtrlSpace.xfo.tr = upVXfo.tr self.legUpVCtrl.xfo.tr = upVXfo.tr self.legRightSideInputAttr.setValue(self.getLocation() is 'R') self.legBone0LenInputAttr.setMin(0.0) self.legBone0LenInputAttr.setMax(femurLen * 3.0) self.legBone0LenInputAttr.setValue(femurLen) self.legBone1LenInputAttr.setMin(0.0) self.legBone1LenInputAttr.setMax(shinLen * 3.0) self.legBone1LenInputAttr.setValue(shinLen) self.legPelvisInputTgt.xfo = femurXfo self.legIKTargetInputTgt.xfo = handleXfo # TODO: We need the Rig class to be modified to handle the ability to # query if the ports are connected during loadData. Currently just a # place holder until that happens. # If IK Target input is not connected, switch to legIKCtrl # ikTargetInput = self.getInputByName('ikTarget') # if not ikTargetInput.isConnected(): # self.legIKKLOp.setInput('ikHandle', self.legIKCtrl) # Eval Input Constraints self.ikRootPosInputConstraint.evaluate() self.legIKCtrlSpaceInputConstraint.evaluate() self.legUpVCtrlSpaceInputConstraint.evaluate() self.legRootInputConstraint.evaluate() # Eval Operators self.legIKKLOp.evaluate() self.outputsToDeformersKLOp.evaluate() # Eval Output Constraints self.legEndFKOutputConstraint.evaluate() self.ikHandleOutputConstraint.evaluate()
def __init__(self, name='leg', parent=None): Profiler.getInstance().push("Construct Leg Rig Component:" + name) super(LegComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Femur self.femurFKCtrlSpace = CtrlSpace('femurFK', parent=self.ctrlCmpGrp) self.femurFKCtrl = Control('femurFK', parent=self.femurFKCtrlSpace, shape="cube") self.femurFKCtrl.alignOnXAxis() # Shin self.shinFKCtrlSpace = CtrlSpace('shinFK', parent=self.femurFKCtrl) self.shinFKCtrl = Control('shinFK', parent=self.shinFKCtrlSpace, shape="cube") self.shinFKCtrl.alignOnXAxis() # Ankle self.legIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.legIKCtrl = Control('IK', parent=self.legIKCtrlSpace, shape="pin") # FK Foot self.footCtrlSpace = CtrlSpace('foot', parent=self.ctrlCmpGrp) self.footCtrl = Control('foot', parent=self.footCtrlSpace, shape="cube") self.footCtrl.alignOnXAxis() # FK Toe self.toeCtrlSpace = CtrlSpace('toe', parent=self.footCtrl) self.toeCtrl = Control('toe', parent=self.toeCtrlSpace, shape="cube") self.toeCtrl.alignOnXAxis() # Rig Ref objects self.footRefSrt = Locator('footRef', parent=self.ctrlCmpGrp) # Add Component Params to IK control footSettingsAttrGrp = AttributeGroup("DisplayInfo_FootSettings", parent=self.footCtrl) footLinkToWorldInputAttr = ScalarAttribute('linkToWorld', 1.0, maxValue=1.0, parent=footSettingsAttrGrp) # Add Component Params to IK control legSettingsAttrGrp = AttributeGroup("DisplayInfo_LegSettings", parent=self.legIKCtrl) legDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=legSettingsAttrGrp) self.legBone0LenInputAttr = ScalarAttribute('bone0Len', value=1.0, parent=legSettingsAttrGrp) self.legBone1LenInputAttr = ScalarAttribute('bone1Len', value=1.0, parent=legSettingsAttrGrp) legIKBlendInputAttr = ScalarAttribute('ikblend', value=1.0, minValue=0.0, maxValue=1.0, parent=legSettingsAttrGrp) legSoftIKInputAttr = BoolAttribute('softIK', value=True, parent=legSettingsAttrGrp) legSoftDistInputAttr = ScalarAttribute('softDist', value=0.0, minValue=0.0, parent=legSettingsAttrGrp) legStretchInputAttr = BoolAttribute('stretch', value=True, parent=legSettingsAttrGrp) legStretchBlendInputAttr = ScalarAttribute('stretchBlend', value=0.0, minValue=0.0, maxValue=1.0, parent=legSettingsAttrGrp) self.drawDebugInputAttr.connect(legDrawDebugInputAttr) # UpV self.legUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.legUpVCtrl = Control('UpV', parent=self.legUpVCtrlSpace, shape="triangle") self.legUpVCtrl.alignOnZAxis() # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) femurDef = Joint('femur', parent=self.defCmpGrp) femurDef.setComponent(self) shinDef = Joint('shin', parent=self.defCmpGrp) shinDef.setComponent(self) ankleDef = Joint('ankle', parent=self.defCmpGrp) ankleDef.setComponent(self) self.footDef = Joint('foot', parent=self.defCmpGrp) self.footDef.setComponent(self) self.toeDef = Joint('toe', parent=self.defCmpGrp) self.toeDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.legIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.legIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.legIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.legIKCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.legIKCtrlSpace.addConstraint(self.legIKCtrlSpaceInputConstraint) self.legUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.legUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.legUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.legUpVCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.legUpVCtrlSpace.addConstraint(self.legUpVCtrlSpaceInputConstraint) self.legRootInputConstraint = PoseConstraint('_'.join([self.legIKCtrl.getName(), 'To', self.legPelvisInputTgt.getName()])) self.legRootInputConstraint.setMaintainOffset(True) self.legRootInputConstraint.addConstrainer(self.legPelvisInputTgt) self.femurFKCtrlSpace.addConstraint(self.legRootInputConstraint) # Constraint outputs self.footOutputConstraint = PoseConstraint('_'.join([self.footOutputTgt.getName(), 'To', self.footCtrl.getName()])) self.footOutputConstraint.addConstrainer(self.footCtrl) self.footOutputTgt.addConstraint(self.footOutputConstraint) self.toeOutputConstraint = PoseConstraint('_'.join([self.toeOutputTgt.getName(), 'To', self.toeCtrl.getName()])) self.toeOutputConstraint.addConstrainer(self.toeCtrl) self.toeOutputTgt.addConstraint(self.toeOutputConstraint) # =============== # Add Splice Ops # =============== # Add Leg Splice Op self.legIKSpliceOp = SpliceOperator('legSpliceOp', 'TwoBoneIKSolver', 'Kraken') self.addOperator(self.legIKSpliceOp) # Add Att Inputs self.legIKSpliceOp.setInput('drawDebug', self.drawDebugInputAttr) self.legIKSpliceOp.setInput('rigScale', self.rigScaleInputAttr) self.legIKSpliceOp.setInput('bone0Len', self.legBone0LenInputAttr) self.legIKSpliceOp.setInput('bone1Len', self.legBone1LenInputAttr) self.legIKSpliceOp.setInput('ikblend', legIKBlendInputAttr) self.legIKSpliceOp.setInput('softIK', legSoftIKInputAttr) self.legIKSpliceOp.setInput('softDist', legSoftDistInputAttr) self.legIKSpliceOp.setInput('stretch', legStretchInputAttr) self.legIKSpliceOp.setInput('stretchBlend', legStretchBlendInputAttr) self.legIKSpliceOp.setInput('rightSide', self.rightSideInputAttr) # Add Xfo Inputs self.legIKSpliceOp.setInput('root', self.legPelvisInputTgt) self.legIKSpliceOp.setInput('bone0FK', self.femurFKCtrl) self.legIKSpliceOp.setInput('bone1FK', self.shinFKCtrl) self.legIKSpliceOp.setInput('ikHandle', self.legIKCtrl) self.legIKSpliceOp.setInput('upV', self.legUpVCtrl) # Add Xfo Outputs self.legIKSpliceOp.setOutput('bone0Out', self.femurOutputTgt) self.legIKSpliceOp.setOutput('bone1Out', self.shinOutputTgt) self.legIKSpliceOp.setOutput('bone2Out', self.legEndXfoOutputTgt) # Add Leg Deformer Splice Op self.outputsToDeformersSpliceOp = SpliceOperator('legDeformerSpliceOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersSpliceOp) # Add Att Inputs self.outputsToDeformersSpliceOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersSpliceOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersSpliceOp.setInput('constrainers', [self.femurOutputTgt, self.shinOutputTgt, self.legEndXfoOutputTgt]) # Add Xfo Outputs self.outputsToDeformersSpliceOp.setOutput('constrainees', [femurDef, shinDef, ankleDef]) # Add Foot Deformer Splice Op self.footDefSpliceOp = SpliceOperator('footDeformerSpliceOp', 'PoseConstraintSolver', 'Kraken') self.addOperator(self.footDefSpliceOp) # Add Att Inputs self.footDefSpliceOp.setInput('drawDebug', self.drawDebugInputAttr) self.footDefSpliceOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs) self.footDefSpliceOp.setInput('constrainer', self.footOutputTgt) # Add Xfo Outputs self.footDefSpliceOp.setOutput('constrainee', self.footDef) # Add Toe Deformer Splice Op self.toeDefSpliceOp = SpliceOperator('toeDeformerSpliceOp', 'PoseConstraintSolver', 'Kraken') self.addOperator(self.toeDefSpliceOp) # Add Att Inputs self.toeDefSpliceOp.setInput('drawDebug', self.drawDebugInputAttr) self.toeDefSpliceOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.toeDefSpliceOp.setInput('constrainer', self.toeOutputTgt) # Add Xfo Outputs self.toeDefSpliceOp.setOutput('constrainee', self.toeDef) Profiler.getInstance().pop()
class Object3D(SceneItem): """Kraken base object type for any 3D object.""" def __init__(self, name, parent=None): super(Object3D, self).__init__(name, parent) self._children = [] self._flags = {} self._attributeGroups = [] self._constraints = [] self._xfo = Xfo() self._ro = RotationOrder() self._color = None self._implicitAttrGrp = AttributeGroup("implicitAttrGrp", self) self._visibility = BoolAttribute('visibility', True, self._implicitAttrGrp) self._shapeVisibility = BoolAttribute('ShapeVisibility', True, self._implicitAttrGrp) if parent is not None: parent.addChild(self) # ================== # Property Methods # ================== @property def xfo(self): """Gets xfo property of this Object3D. Returns: Xfo: Xfo property of this Object3D. """ return self._xfo @xfo.setter def xfo(self, value): """Sets xfo of this Object3D. Note: In Python, objects are always referenced, meaning to get a unique instance, an explicit clone is required. In KL, structs are passed by value, meaning that every assignment of a struct causes a clone. This means that in KL it is impossible for 2 objects to reference the same KL math object. This is an important performance feature of KL. The members of the KL Math objects have this property. 2 Xfos cannot share the same tr value. Here we implcitly clone the math object to ensure the same behavior as in KL. Args: value (Xfo): Vector to set the xfo by. Returns: bool: True if successful. """ self._xfo = value.clone() return True @property def ro(self): """Gets Rotation Order property of this Object3D. Returns: RotationOrder: Rotation Order property of this Object3D. """ return self._ro @ro.setter def ro(self, value): """Sets Rotation Order of this Object3D. Note: In Python, objects are always referenced, meaning to get a unique instance, an explicit clone is required. In KL, structs are passed by value, meaning that every assignment of a struct causes a clone. This means that in KL it is impossible for 2 objects to reference the same KL math object. This is an important performance feature of KL. The members of the KL Math objects have this property. 2 Xfos cannot share the same tr value. Here we implcitly clone the math object to ensure the same behavior as in KL. Args: value (RotationOrder): New rotation order. Returns: bool: True if successful. """ self._ro = value.clone() return True @property def localXfo(self): """Gets local transform of this Object3D Returns: Xfo: Local Xfo of the object. """ globalXfo = self.globalXfo parent = self.getParent() if not isinstance(parent, SceneItem): return globalXfo parentXfo = parent.globalXfo return parentXfo.inverse().multiply(globalXfo) @property def globalXfo(self): """Gets global transform of this Object3D Returns: Xfo: Global Xfo """ for source in self.getSources(): if isinstance(source, Object3D): continue if isinstance(source, Constraint): return source.compute() if isinstance(source, Operator): source.evaluate() break return self._xfo # ============= # Name Methods # ============= def getBuildName(self): """Returns the build name for the object. Returns: str: Name to be used in the DCC. """ typeNameHierarchy = self.getTypeHierarchyNames() config = Config.getInstance() # If flag is set on object to use explicit name, return it. if config.getExplicitNaming() is True or \ self.testFlag('EXPLICIT_NAME'): return self.getName() nameTemplate = config.getNameTemplate() # Get the token list for this type of object format = None for typeName in nameTemplate['formats'].keys(): if typeName in typeNameHierarchy: format = nameTemplate['formats'][typeName] break if format is None: format = nameTemplate['formats']['default'] objectType = None for eachType in typeNameHierarchy: if eachType in nameTemplate['types'].keys(): objectType = eachType break if objectType is None: objectType = 'default' # Generate a name by concatenating the resolved tokens together. builtName = "" skipSep = False for token in format: if token is 'sep': if not skipSep: builtName += nameTemplate['separator'] elif token is 'location': if self.isTypeOf('Component'): location = self.getLocation() else: location = self.getComponent().getLocation() if location not in nameTemplate['locations']: raise ValueError("Invalid location on: " + self.getPath()) builtName += location elif token is 'type': if objectType == 'Locator' and self.testFlag('inputObject'): objectType = 'ComponentInput' elif objectType == 'Locator' and self.testFlag('outputObject'): objectType = 'ComponentOutput' builtName += nameTemplate['types'][objectType] elif token is 'name': builtName += self.getName() elif token is 'component': if self.getComponent() is None: skipSep = True continue builtName += self.getComponent().getName() elif token is 'container': if self.getContainer() is None: skipSep = True continue builtName += self.getContainer().getName() else: raise ValueError("Unresolvabled token '" + token + "' used on: " + self.getPath()) return builtName def setName(self, name): """Sets the name of the object with a string. Args: name (str): The new name for the item. Returns: bool: True if successful. """ # check for name collision and adjust the name if they exist if self.getParent() is not None: # Increment name if it already exists initName = name suffix = 1 collision = True while collision: child = self.getParent().getChildByDecoratedName(name + self.getNameDecoration()) collision = child is not None and child is not self if not collision: break result = re.split(r"(\d+)$", initName, 1) if len(result) > 1: initName = result[0] suffix = int(result[1]) name = initName + str(suffix).zfill(2) suffix += 1 super(Object3D, self).setName(name) return True # ================== # Hierarchy Methods # ================== def getContainer(self): """Returns the Container the object belongs to. Returns: Object: Container. """ parent = self.getParent() while (parent is not None and 'Container' not in parent.getTypeHierarchyNames()): parent = parent.getParent() return parent def getLayer(self): """Returns the Layer the object belongs to. Returns: Object: Layer this object belongs to. """ parent = self.getParent() while (parent is not None and not parent.isTypeOf('Layer')): parent = parent.getParent() return parent # ============== # Child Methods # ============== def hasChild(self, child): """Checks the supplied item is a child Args: child (Object): Object to check if is is a child of this object. """ for i, eachChild in enumerate(self.getChildren()): if eachChild == child: return True return False def _checkChildIndex(self, index): """Checks the supplied index is valid. Args: index (int): Child index to check. """ if index > len(self.getChildren()): raise IndexError("'" + str(index) + "' is out of the range of the 'children' array.") return True def addChild(self, child): """Adds a child to this object. Note: We allow for duplicate child names as long as the types differ. Args: child (Object): Object that will be a child of this object. Returns: bool: True if successful. """ if child.getParent() is not None: parent = child.getParent() if child in parent.getChildren(): parent.getChildren().remove(child) # check for name collision and adjust the name if they exist # Increment name if it already exists initName = child.getName() name = initName suffix = 1 while self.getChildByDecoratedName(name + child.getNameDecoration()) is not None: name = initName + str(suffix).zfill(2) suffix += 1 if initName != name: child.setName(name) self.getChildren().append(child) child.setParent(self) # Assign the child the same component. if self._component is not None: child.setComponent(self._component) return True def removeChildByIndex(self, index): """Removes a child from this object by index. Args: index (int): Index of child to remove. Returns: bool: True if successful. """ if self._checkChildIndex(index) is not True: return False del self.getChildren()[index] return True def removeChildByName(self, name): """Removes a child from this object by name. Args: name (str): Name of child to remove. Returns: bool: True if successful. """ removeIndex = None for i, eachChild in enumerate(self.getChildren()): if eachChild.getName() == name: removeIndex = i if removeIndex is None: raise ValueError("'" + name + "' is not a valid child of this object.") self.removeChildByIndex(removeIndex) return True def removeChild(self, child): """Removed the child as an child item of this object. Returns: bool: True if successful. """ try: self._children.remove(child) except: names = [] for c in self._children: names.append(c.getName()) raise Exception("Object '" + self.getPath() + "' does not have child:" + child.getPath() + ". it does have:" + str(names)) child.setParent(None) # Un-assign the child the component. if self._component is not None: child.setComponent(None) return True def getDescendents(self, nodeList=None, classType=None, inheritedClass=False): """Gets the children of this object. Args: nodeList: (list): optional list to append children to classType (str): Name of the type of class to limit the search to inheritedClass (bool): Match nodes that is a sub-class of type. Returns: list: Child objects. """ if nodeList is None: nodeList = [] for child in self._children: if classType is not None: if inheritedClass is not None and child.isTypeOf(classType): nodeList.append(child) elif child.getTypeName() == classType: nodeList.append(child) else: nodeList.append(child) child.getDescendents(classType=classType, nodeList=nodeList, inheritedClass=inheritedClass) return nodeList def getChildren(self): """Gets the children of this object. Returns: list: Child objects. """ return self._children def getNumChildren(self): """Returns the number of children this object has. Returns: int: Number of children of this object. """ return len(self.getChildren()) def getChildByIndex(self, index): """Returns the child object at specified index. Args: index (int): Index of the child to find. Returns: Object: Child object at specified index. """ if self._checkChildIndex(index) is not True: return False return self.getChildren()[index] def getChildByName(self, name): """Returns the child object with the specified name. Args: name (str): Name of the child to return. Returns: Object: Object if found. """ for eachChild in self.getChildren(): if eachChild.getName() == name: return eachChild return None def getChildByDecoratedName(self, decoratedName): """Returns the child object with the specified name. Args: decoratedName (str): Decorated name of the child to find. Returns: Object: Object if found. """ for eachChild in self.getChildren(): if eachChild.getDecoratedName() == decoratedName: return eachChild return None def getChildrenByType(self, childType): """Returns all children that are of the specified type. Args: childType (str): Type of children to find. Returns: list: Array of child objects of the specified type. """ childrenOfType = [] for eachChild in self.getChildren(): if eachChild.isTypeOf(childType): childrenOfType.append(eachChild) return childrenOfType # ============= # Flag Methods # ============= def setFlag(self, name): """Sets the flag of the specified name. Returns: bool: True if successful. """ self._flags[name] = True return True def testFlag(self, name): """Tests if the specified flag is set. Args: name (str): Name of the flag to test. Returns: bool: True if flag is set. """ return name in self._flags def clearFlag(self, name): """Clears the flag of the specified name. Args: name (str): Name of the flag to clear. Returns: bool: True if successful. """ if name in self._flags: del self._flags[name] return True return False # ======================== # Attribute Group Methods # ======================== def _checkAttributeGroupIndex(self, index): """Checks the supplied index is valid. Args: index (int): Attribute index to check. Returns: bool: True if successful. """ if index > len(self._attributeGroups): raise IndexError("'" + str(index) + "' is out of the range of 'attributeGroups' array.") return True def addAttributeGroup(self, attributeGroup): """Adds an attributeGroup to this object. Args: attributeGroup (Object): Attribute Group object to add to this object. Returns: bool: True if successful. """ if attributeGroup.getName() in [x.getName() for x in self._attributeGroups]: raise IndexError("Child with " + attributeGroup.getName() + " already exists as a attributeGroup.") self._attributeGroups.append(attributeGroup) attributeGroup.setParent(self) return True def removeAttributeGroupByIndex(self, index): """Removes attribute at specified index. Args: index (int): Index of attribute to remove. Returns: bool: True if successful. """ if self._checkAttributeGroupIndex(index) is not True: return False del self._attributeGroups[index] return True def removeAttributeGroupByName(self, name): """Removes the attribute with the specified name. Args: name (str): Name of the attribute to remove. Returns: bool: True if successful. """ removeIndex = None for i, eachAttributeGroup in enumerate(self._attributeGroups): if eachAttributeGroup.getName() == name: removeIndex = i if removeIndex is None: return False self.removeAttributeGroupByIndex(removeIndex) return True def getNumAttributeGroups(self): """Returns the number of attributeGroups as an integer. Returns: int: Number of attributeGroups on this object. """ return len(self._attributeGroups) def getAttributeGroupByIndex(self, index): """Returns the attribute at the specified index. Args: index (int): Index of the attribute to return. Returns: AttributeGroup: Attribute Group at the specified index. """ if self._checkAttributeGroupIndex(index) is not True: return False return self._attributeGroups[index] def getAttributeGroupByName(self, name): """Return the attribute group with the specified name. Args: name (str): Name of the attribute group to return. Returns: Attribute: Attribute with the specified name. """ for eachAttributeGroup in self._attributeGroups: if eachAttributeGroup.getName() == name: return eachAttributeGroup return None # =================== # Constraint Methods # =================== def checkConstraintIndex(self, index): """Checks the supplied index is valid. Args: index (int): Constraint index to check. Returns: bool: True if successful. """ if index > len(self._constraints): raise IndexError("'" + str(index) + "' is out of the range of 'constraints' array.") return True def constrainTo(self, constrainers, constraintType="Pose", maintainOffset=False, name=None): """Adds an constraint to this object. Args: constrainers (Object or Object list): Constraint object to add to this object or objects. constraintType (str): String name of the constraint type. maintainOffset (bool): Sets the constraint to maintain offset when creating the constraint. name (str): Name of the constraint. If set to None, a name is automatically generated. Returns: string: Constraint object """ if name is None: constraintName = "" if hasattr(constrainers, '__iter__'): constraintName = '_'.join([self.getName(), 'To', constrainers[0].getName(), constraintType + 'Constraint']) else: constraintName = '_'.join([self.getName(), 'To', constrainers.getName(), constraintType + 'Constraint']) else: constraintName = name constraint = None if constraintType == "Orientation": constraint = OrientationConstraint(constraintName) elif constraintType == "Pose": constraint = PoseConstraint(constraintName) elif constraintType == "Position": constraint = PositionConstraint(constraintName) elif constraintType == "Scale": constraint = ScaleConstraint(constraintName) else: raise ValueError("'" + constraintType + "' is not a valid constraint type. Valid types are Orientation, Pose, Position, or Scale") # Accept a single object or a list of objects if hasattr(constrainers, '__iter__'): pass else: constrainers = [constrainers] for constrainer in constrainers: constraint.addConstrainer(constrainer) constraint.setMaintainOffset(maintainOffset) self.addConstraint(constraint) return constraint def addConstraint(self, constraint): """Adds an constraint to this object. Args: constraint (Object): Constraint object to add to this object. Returns: bool: True if successful. """ if constraint.getName() in [x.getName() for x in self._constraints]: raise IndexError("Constraint with name '" + constraint.getName() + "'' already exists as a constraint.") self._constraints.append(constraint) constraint.setParent(self) constraint.setConstrainee(self) return True def removeConstraintByIndex(self, index): """Removes constraint at specified index. Args: index (int): Index of constraint to remove. Returns: bool: True if successful. """ if self.checkConstraintIndex(index) is not True: return False del self._constraints[index] return True def removeConstraintByName(self, name): """Removes the constraint with the specified name. Args: name (str): Name of the constraint to remove. Returns: bool: True if successful. """ removeIndex = None for i, eachConstraint in enumerate(self._constraints): if eachConstraint.getName() == name: removeIndex = i if removeIndex is None: return False self.removeConstraintByIndex(removeIndex) return True def removeAllConstraints(self): """Removes all of the constraints for this object. Returns: bool: True if successful. """ del self._constraints[:] return True def getNumConstraints(self): """Returns the number of constraints as an integer. Returns: int: Number of constraints on this object. """ return len(self._constraints) def getConstraintByIndex(self, index): """Returns the constraint at the specified index. Args: index (int): Index of the constraint to return. Returns: Constraint: Constraint at the specified index. """ if self.checkConstraintIndex(index) is not True: return False return self._constraints[index] def getConstraintByName(self, name): """Return the constraint group with the specified name. Args: name (str): Name of the constraint group to return. Returns: Attribute: Attribute with the specified name. """ for eachConstraint in self._constraints: if eachConstraint.getName() == name: return eachConstraint return None # =================== # Visibility Methods # =================== def getVisibilityAttr(self): """Returns the Visibility attribute object. Returns: BoolAttribute: Attribute that holds the value of the visibility. """ return self._visibility def getVisibility(self): """Returns the visibility status of the scene item. Returns: bool: Visible or not. """ return self._visibility.getValue() def setVisibility(self, value): """Sets the visibility of the scene object. Args: value (bool): value of the visibility of the object. Returns: bool: True if successful. """ self._visibility.setValue(value) return True def getShapeVisibilityAttr(self): """Returns the Shape Visibility attribute object. Returns: BoolAttribute: Attribute that holds the value of the shape visibility. """ return self._shapeVisibility def getShapeVisibility(self): """Returns the shape visibility status of the scene item. Returns: bool: Visible or not. """ return self._shapeVisibility.getValue() def setShapeVisibility(self, value): """Sets the shape visibility of the scene object. Args: value (bool): Value of the visibility of the object. Returns: bool: True if successful. """ self._shapeVisibility.setValue(value) return True # ================ # Display Methods # ================ def setColor(self, color): """Sets the color of this object. Args: color (str): Name of the color you wish to set. Returns: bool: True if successful. """ self._color = color return True def getColor(self): """Returns the color of the object. Returns: str: Color of the object. """ return self._color # ========================== # Parameter Locking Methods # ========================== def lockRotation(self, x=False, y=False, z=False): """Sets flags for locking rotation parameters. Args: x (bool): Lock x axis. y (bool): Lock y axis. z (bool): Lock z axis. Returns: bool: True if successful. """ if x is True: self.setFlag("lockXRotation") if y is True: self.setFlag("lockYRotation") if z is True: self.setFlag("lockZRotation") return True def lockScale(self, x=False, y=False, z=False): """Sets flags for locking scale parameters. Args: x (bool): Lock x axis. y (bool): Lock y axis. z (bool): Lock z axis. Returns: bool: True if successful. """ if x is True: self.setFlag("lockXScale") if y is True: self.setFlag("lockYScale") if z is True: self.setFlag("lockZScale") return True def lockTranslation(self, x=False, y=False, z=False): """Sets flags for locking translation parameters. Args: x (bool): Lock x axis. y (bool): Lock x axis. z (bool): Lock x axis. Returns: bool: True if successful. """ if x is True: self.setFlag("lockXTranslation") if y is True: self.setFlag("lockYTranslation") if z is True: self.setFlag("lockZTranslation") return True # ==================== # Persistence Methods # ==================== def jsonEncode(self, saver): """Encodes the object to a JSON structure. Args: saver (Object): saver object. Returns: Dict: A JSON structure containing the data for this SceneItem. """ classHierarchy = self.getTypeHierarchyNames() jsonData = { '__typeHierarchy__': classHierarchy, 'name': self.getName(), 'parent': None, 'children': [], 'flags': self._flags, 'attributeGroups': [], 'constraints': [], 'xfo': self.xfo.jsonEncode(), 'color': self.getColor(), 'visibility': self._visibility, 'shapeVisibility': self._shapeVisibility, } if self.getParent() is not None: jsonData['parent'] = self.getParent().getName() if self.getColor() is not None: jsonData['color'] = saver.encodeValue(self.getColor()) for child in self.getChildren(): jsonData['children'].append(child.jsonEncode(saver)) for attrGroup in self._attributeGroups: jsonData['attributeGroups'].append(attrGroup.jsonEncode(saver)) for constr in self._constraints: jsonData['constraints'].append(constr.jsonEncode(saver)) return jsonData def jsonDecode(self, loader, jsonData): """Returns the color of the object.. Args: loader (Object): Loader object. jsonData (Dict): JSON object structure. Returns: bool: True if successful. """ self._flags = jsonData['flags'] self.xfo = loader.decodeValue(jsonData['xfo']) if 'color' in jsonData and jsonData['color'] is not None: self.setColor(loader.decodeValue(jsonData['color'])) self._visibility = jsonData['visibility'] self._shapeVisibility = jsonData['shapeVisibility'] for child in jsonData['children']: self.addChild(loader.construct(child)) for attrGroup in jsonData['attributeGroups']: # There is one default attribute group assigned to each scene item. # Load data into the existing item instead of constructing a new # one. if attrGroup['name'] == '': loader.registerItem(self._attributeGroups[0]) self._attributeGroups[0].jsonDecode(loader, attrGroup) else: self.addAttributeGroup(loader.construct(attrGroup)) for constr in jsonData['constraints']: self.addConstraint(loader.construct(constr)) return True
class StretchyLimbComponentRig(StretchyLimbComponent): """StretchyLimb Component""" def __init__(self, name='limb', parent=None): Profiler.getInstance().push("Construct StretchyLimb Rig Component:" + name) super(StretchyLimbComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Upper (FK) self.upperFKCtrlSpace = CtrlSpace('upperFK', parent=self.ctrlCmpGrp) self.upperFKCtrl = Control('upperFK', parent=self.upperFKCtrlSpace, shape="cube") self.upperFKCtrl.alignOnXAxis() # Lower (FK) self.lowerFKCtrlSpace = CtrlSpace('lowerFK', parent=self.upperFKCtrl) self.lowerFKCtrl = Control('lowerFK', parent=self.lowerFKCtrlSpace, shape="cube") self.lowerFKCtrl.alignOnXAxis() # End (IK) self.limbIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.limbIKCtrl = Control('IK', parent=self.limbIKCtrlSpace, shape="pin") # Add Component Params to IK control # TODO: Move these separate control limbSettingsAttrGrp = AttributeGroup( "DisplayInfo_StretchyLimbSettings", parent=self.limbIKCtrl) limbDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=limbSettingsAttrGrp) self.limbBone0LenInputAttr = ScalarAttribute( 'bone0Len', value=1.0, parent=limbSettingsAttrGrp) self.limbBone1LenInputAttr = ScalarAttribute( 'bone1Len', value=1.0, parent=limbSettingsAttrGrp) limbIKBlendInputAttr = ScalarAttribute('ikblend', value=1.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSoftIKInputAttr = BoolAttribute('softIK', value=True, parent=limbSettingsAttrGrp) limbSoftRatioInputAttr = ScalarAttribute('softRatio', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbStretchInputAttr = BoolAttribute('stretch', value=True, parent=limbSettingsAttrGrp) limbStretchBlendInputAttr = ScalarAttribute('stretchBlend', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSlideInputAttr = ScalarAttribute('slide', value=0.0, minValue=-1.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbPinInputAttr = ScalarAttribute('pin', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) self.rightSideInputAttr = BoolAttribute('rightSide', value=False, parent=limbSettingsAttrGrp) self.drawDebugInputAttr.connect(limbDrawDebugInputAttr) # UpV (IK Pole Vector) self.limbUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.limbUpVCtrl = Control('UpV', parent=self.limbUpVCtrlSpace, shape="triangle") self.limbUpVCtrl.alignOnZAxis() # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) upperDef = Joint('upper', parent=self.defCmpGrp) upperDef.setComponent(self) lowerDef = Joint('lower', parent=self.defCmpGrp) lowerDef.setComponent(self) endDef = Joint('end', parent=self.defCmpGrp) endDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.limbIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.limbIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.limbIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbIKCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.limbIKCtrlSpace.addConstraint(self.limbIKCtrlSpaceInputConstraint) self.limbUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.limbUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.limbUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbUpVCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.limbUpVCtrlSpace.addConstraint( self.limbUpVCtrlSpaceInputConstraint) self.limbRootInputConstraint = PoseConstraint('_'.join([ self.limbIKCtrl.getName(), 'To', self.limbParentInputTgt.getName() ])) self.limbRootInputConstraint.setMaintainOffset(True) self.limbRootInputConstraint.addConstrainer(self.limbParentInputTgt) self.upperFKCtrlSpace.addConstraint(self.limbRootInputConstraint) # =============== # Add Splice Ops # =============== # Add StretchyLimb Splice Op self.limbIKKLOp = KLOperator('limbKLOp', 'TwoBoneStretchyIKSolver', 'Kraken') self.addOperator(self.limbIKKLOp) # Add Att Inputs self.limbIKKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.limbIKKLOp.setInput('rigScale', self.rigScaleInputAttr) self.limbIKKLOp.setInput('bone0Len', self.limbBone0LenInputAttr) self.limbIKKLOp.setInput('bone1Len', self.limbBone1LenInputAttr) self.limbIKKLOp.setInput('ikblend', limbIKBlendInputAttr) self.limbIKKLOp.setInput('softIK', limbSoftIKInputAttr) self.limbIKKLOp.setInput('softRatio', limbSoftRatioInputAttr) self.limbIKKLOp.setInput('stretch', limbStretchInputAttr) self.limbIKKLOp.setInput('stretchBlend', limbStretchBlendInputAttr) self.limbIKKLOp.setInput('slide', limbSlideInputAttr) self.limbIKKLOp.setInput('pin', limbPinInputAttr) self.limbIKKLOp.setInput('rightSide', self.rightSideInputAttr) # Add Xfo Inputs self.limbIKKLOp.setInput('root', self.limbParentInputTgt) self.limbIKKLOp.setInput('bone0FK', self.upperFKCtrl) self.limbIKKLOp.setInput('bone1FK', self.lowerFKCtrl) self.limbIKKLOp.setInput('ikHandle', self.limbIKCtrl) self.limbIKKLOp.setInput('upV', self.limbUpVCtrl) # Add Xfo Outputs self.limbIKKLOp.setOutput('bone0Out', self.limbUpperOutputTgt) self.limbIKKLOp.setOutput('bone1Out', self.limbLowerOutputTgt) self.limbIKKLOp.setOutput('bone2Out', self.limbEndOutputTgt) # ===================== # Connect the deformers # ===================== # Add StretchyLimb Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('limbDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [ self.limbUpperOutputTgt, self.limbLowerOutputTgt, self.limbEndOutputTgt ]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [upperDef, lowerDef, endDef]) Profiler.getInstance().pop() # ============= # Data Methods # ============= def loadData(self, data=None): """Load a saved guide representation from persisted data. Arguments: data -- object, The JSON data object. Return: True if successful. """ super(StretchyLimbComponentRig, self).loadData(data) upperXfo = data.get('upperXfo') upperLen = data.get('upperLen') lowerXfo = data.get('lowerXfo') lowerLen = data.get('lowerLen') endXfo = data.get('endXfo') upVXfo = data.get('upVXfo') self.upperFKCtrlSpace.xfo = upperXfo self.upperFKCtrl.xfo = upperXfo self.upperFKCtrl.scalePoints(Vec3(upperLen, 1.75, 1.75)) self.limbUpperOutputTgt.xfo = upperXfo self.limbLowerOutputTgt.xfo = lowerXfo self.lowerFKCtrlSpace.xfo = lowerXfo self.lowerFKCtrl.xfo = lowerXfo self.lowerFKCtrl.scalePoints(Vec3(lowerLen, 1.5, 1.5)) self.limbIKCtrlSpace.xfo.tr = endXfo.tr self.limbIKCtrl.xfo.tr = endXfo.tr if self.getLocation() == "R": self.limbIKCtrl.rotatePoints(0, 90, 0) self.limbIKCtrl.translatePoints(Vec3(-1.0, 0.0, 0.0)) else: self.limbIKCtrl.rotatePoints(0, -90, 0) self.limbIKCtrl.translatePoints(Vec3(1.0, 0.0, 0.0)) self.limbUpVCtrlSpace.xfo = upVXfo self.limbUpVCtrl.xfo = upVXfo self.limbBone0LenInputAttr.setMin(0.0) self.limbBone0LenInputAttr.setMax(upperLen * 3.0) self.limbBone0LenInputAttr.setValue(upperLen) self.limbBone1LenInputAttr.setMin(0.0) self.limbBone1LenInputAttr.setMax(lowerLen * 3.0) self.limbBone1LenInputAttr.setValue(lowerLen) self.limbParentInputTgt.xfo = upperXfo # Set Attrs self.rightSideInputAttr.setValue(self.getLocation() is 'R') # Eval Constraints self.limbIKCtrlSpaceInputConstraint.evaluate() self.limbUpVCtrlSpaceInputConstraint.evaluate() self.limbRootInputConstraint.evaluate() # Eval Operators self.limbIKKLOp.evaluate() self.outputsToDeformersKLOp.evaluate()
class FootComponentRig(FootComponent): """Foot Component""" def __init__(self, name="foot", parent=None): Profiler.getInstance().push("Construct Neck Rig Component:" + name) super(FootComponentRig, self).__init__(name, parent) # ========= # Controls # ========= self.ankleLenInputAttr = ScalarAttribute('ankleLen', 1.0, maxValue=1.0, parent=self.cmpInputAttrGrp) self.toeLenInputAttr = ScalarAttribute('toeLen', 1.0, maxValue=1.0, parent=self.cmpInputAttrGrp) self.rightSideInputAttr = BoolAttribute('rightSide', False, parent=self.cmpInputAttrGrp) self.footAll = Locator('footAll', parent=self.ctrlCmpGrp) self.footAll.setShapeVisibility(False) self.ankleIKCtrlSpace = CtrlSpace('ankleIK', parent=self.footAll) self.ankleIKCtrl = Control('ankleIK', parent=self.ankleIKCtrlSpace, shape="square") self.ankleIKCtrl.alignOnXAxis(negative=True) self.ankleIKCtrl.lockTranslation(True, True, True) self.ankleIKCtrl.lockScale(True, True, True) self.toeIKCtrlSpace = CtrlSpace('toeIK', parent=self.footAll) self.toeIKCtrl = Control('toeIK', parent=self.toeIKCtrlSpace, shape="square") self.toeIKCtrl.alignOnXAxis() self.toeIKCtrl.lockTranslation(True, True, True) self.toeIKCtrl.lockScale(True, True, True) self.ankleFKCtrlSpace = CtrlSpace('ankleFK', parent=self.ctrlCmpGrp) self.ankleFKCtrl = Control('ankleFK', parent=self.ankleFKCtrlSpace, shape="cube") self.ankleFKCtrl.alignOnXAxis() self.ankleFKCtrl.lockTranslation(True, True, True) self.ankleFKCtrl.lockScale(True, True, True) self.toeFKCtrlSpace = CtrlSpace('toeFK', parent=self.ankleFKCtrl) self.toeFKCtrl = Control('toeFK', parent=self.toeFKCtrlSpace, shape="cube") self.toeFKCtrl.alignOnXAxis() self.toeFKCtrl.lockTranslation(True, True, True) self.toeFKCtrl.lockScale(True, True, True) self.footSettingsAttrGrp = AttributeGroup("DisplayInfo_FootSettings", parent=self.ankleIKCtrl) self.footDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=self.footSettingsAttrGrp) self.footRockInputAttr = ScalarAttribute('footRock', value=0.0, minValue=-1.0, maxValue=1.0, parent=self.footSettingsAttrGrp) self.footBankInputAttr = ScalarAttribute('footBank', value=0.0, minValue=-1.0, maxValue=1.0, parent=self.footSettingsAttrGrp) self.drawDebugInputAttr.connect(self.footDebugInputAttr) self.pivotAll = Locator('pivotAll', parent=self.ctrlCmpGrp) self.pivotAll.setShapeVisibility(False) self.backPivotCtrl = Control('backPivot', parent=self.pivotAll, shape="axesHalfTarget") self.backPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) self.backPivotCtrl.lockScale(True, True, True) self.backPivotCtrlSpace = self.backPivotCtrl.insertCtrlSpace() self.frontPivotCtrl = Control('frontPivot', parent=self.pivotAll, shape="axesHalfTarget") self.frontPivotCtrl.rotatePoints(0.0, 180.0, 0.0) self.frontPivotCtrl.lockScale(True, True, True) self.frontPivotCtrlSpace = self.frontPivotCtrl.insertCtrlSpace() self.frontPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) self.outerPivotCtrl = Control('outerPivot', parent=self.pivotAll, shape="axesHalfTarget") self.outerPivotCtrl.rotatePoints(0.0, -90.0, 0.0) self.outerPivotCtrl.lockScale(True, True, True) self.outerPivotCtrlSpace = self.outerPivotCtrl.insertCtrlSpace() self.outerPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) self.innerPivotCtrl = Control('innerPivot', parent=self.pivotAll, shape="axesHalfTarget") self.innerPivotCtrl.rotatePoints(0.0, 90.0, 0.0) self.innerPivotCtrl.lockScale(True, True, True) self.innerPivotCtrlSpace = self.innerPivotCtrl.insertCtrlSpace() self.innerPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.ankleDef = Joint('ankle', parent=self.defCmpGrp) self.ankleDef.setComponent(self) self.toeDef = Joint('toe', parent=self.defCmpGrp) self.toeDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint to inputs self.pivotAllInputConstraint = PoseConstraint('_'.join([self.pivotAll.getName(), 'To', self.ikHandleInputTgt.getName()])) self.pivotAllInputConstraint.setMaintainOffset(True) self.pivotAllInputConstraint.addConstrainer(self.ikHandleInputTgt) self.pivotAll.addConstraint(self.pivotAllInputConstraint) self.ankleFKInputConstraint = PoseConstraint('_'.join([self.ankleFKCtrlSpace.getName(), 'To', self.legEndFKInputTgt.getName()])) self.ankleFKInputConstraint.setMaintainOffset(True) self.ankleFKInputConstraint.addConstrainer(self.legEndFKInputTgt) self.ankleFKCtrlSpace.addConstraint(self.ankleFKInputConstraint) # Constraint outputs self.ikTargetOutputConstraint = PoseConstraint('_'.join([self.ikTargetOutputTgt.getName(), 'To', self.ankleIKCtrl.getName()])) self.ikTargetOutputConstraint.setMaintainOffset(True) self.ikTargetOutputConstraint.addConstrainer(self.ankleIKCtrl) self.ikTargetOutputTgt.addConstraint(self.ikTargetOutputConstraint) # ========================= # Add Foot Pivot Canvas Op # ========================= # self.footPivotCanvasOp = CanvasOperator('footPivotCanvasOp', 'Kraken.Solvers.Biped.BipedFootPivotSolver') self.footPivotCanvasOp = KLOperator('footPivotKLOp', 'BipedFootPivotSolver', 'Kraken') self.addOperator(self.footPivotCanvasOp) # Add Att Inputs self.footPivotCanvasOp.setInput('drawDebug', self.drawDebugInputAttr) self.footPivotCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.footPivotCanvasOp.setInput('rightSide', self.rightSideInputAttr) self.footPivotCanvasOp.setInput('footRock', self.footRockInputAttr) self.footPivotCanvasOp.setInput('footBank', self.footBankInputAttr) # Add Xfo Inputs self.footPivotCanvasOp.setInput('pivotAll', self.pivotAll) self.footPivotCanvasOp.setInput('backPivot', self.backPivotCtrl) self.footPivotCanvasOp.setInput('frontPivot', self.frontPivotCtrl) self.footPivotCanvasOp.setInput('outerPivot', self.outerPivotCtrl) self.footPivotCanvasOp.setInput('innerPivot', self.innerPivotCtrl) # Add Xfo Outputs self.footPivotCanvasOp.setOutput('result', self.footAll) # ========================= # Add Foot Solver Canvas Op # ========================= # self.footSolverCanvasOp = CanvasOperator('footSolverCanvasOp', 'Kraken.Solvers.Biped.BipedFootSolver') self.footSolverCanvasOp = KLOperator('footSolverKLOp', 'BipedFootSolver', 'Kraken') self.addOperator(self.footSolverCanvasOp) # Add Att Inputs self.footSolverCanvasOp.setInput('drawDebug', self.drawDebugInputAttr) self.footSolverCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.footSolverCanvasOp.setInput('ikBlend', self.ikBlendInputAttr) self.footSolverCanvasOp.setInput('ankleLen', self.ankleLenInputAttr) self.footSolverCanvasOp.setInput('toeLen', self.toeLenInputAttr) # Add Xfo Inputs self.footSolverCanvasOp.setInput('legEnd', self.legEndInputTgt) self.footSolverCanvasOp.setInput('ankleIK', self.ankleIKCtrl) self.footSolverCanvasOp.setInput('toeIK', self.toeIKCtrl) self.footSolverCanvasOp.setInput('ankleFK', self.ankleFKCtrl) self.footSolverCanvasOp.setInput('toeFK', self.toeFKCtrl) # Add Xfo Outputs self.footSolverCanvasOp.setOutput('ankle_result', self.ankleOutputTgt) self.footSolverCanvasOp.setOutput('toe_result', self.toeOutputTgt) # =================== # Add Deformer KL Op # =================== self.outputsToDeformersKLOp = KLOperator('foot' + self.getLocation() + 'DeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [self.ankleOutputTgt, self.toeOutputTgt]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [self.ankleDef, self.toeDef]) Profiler.getInstance().pop() def loadData(self, data=None): """Load a saved guide representation from persisted data. Arguments: data -- object, The JSON data object. Return: True if successful. """ super(FootComponentRig, self).loadData( data ) footXfo = data.get('footXfo') ankleXfo = data.get('ankleXfo') toeXfo = data.get('toeXfo') ankleFKXfo = data.get('ankleFKXfo') toeFKXfo = data.get('toeFKXfo') ankleLen = data.get('ankleLen') toeLen = data.get('toeLen') backPivotXfo = data.get('backPivotXfo') frontPivotXfo = data.get('frontPivotXfo') outerPivotXfo = data.get('outerPivotXfo') innerPivotXfo = data.get('innerPivotXfo') self.footAll.xfo = footXfo self.ankleIKCtrlSpace.xfo = ankleXfo self.ankleIKCtrl.xfo = ankleXfo self.toeIKCtrlSpace.xfo = toeXfo self.toeIKCtrl.xfo = toeXfo self.ankleFKCtrl.scalePoints(Vec3(ankleLen, 1.0, 1.0)) self.toeFKCtrl.scalePoints(Vec3(toeLen, 1.0, 1.0)) self.ankleFKCtrlSpace.xfo.tr = footXfo.tr self.ankleFKCtrlSpace.xfo.ori = ankleFKXfo.ori self.ankleFKCtrl.xfo.tr = footXfo.tr self.ankleFKCtrl.xfo.ori = ankleFKXfo.ori self.toeFKCtrlSpace.xfo = toeFKXfo self.toeFKCtrl.xfo = toeFKXfo self.pivotAll.xfo = footXfo self.backPivotCtrlSpace.xfo = backPivotXfo self.backPivotCtrl.xfo = backPivotXfo self.frontPivotCtrlSpace.xfo = frontPivotXfo self.frontPivotCtrl.xfo = frontPivotXfo self.outerPivotCtrlSpace.xfo = outerPivotXfo self.outerPivotCtrl.xfo = outerPivotXfo self.innerPivotCtrlSpace.xfo = innerPivotXfo self.innerPivotCtrl.xfo = innerPivotXfo if self.getLocation() == 'R': self.outerPivotCtrl.rotatePoints(0.0, 180.0, 0.0) self.innerPivotCtrl.rotatePoints(0.0, 180.0, 0.0) self.ankleIKCtrl.scalePoints(Vec3(ankleLen, 1.0, 1.5)) self.toeIKCtrl.scalePoints(Vec3(toeLen, 1.0, 1.5)) # Set Attribute Values self.rightSideInputAttr.setValue(self.getLocation() is 'R') self.ankleLenInputAttr.setValue(ankleLen) self.ankleLenInputAttr.setMax(ankleLen * 3.0) self.toeLenInputAttr.setValue(toeLen) self.toeLenInputAttr.setMax(toeLen * 3.0) # Set IO Xfos self.ikHandleInputTgt.xfo = footXfo self.legEndInputTgt.xfo.tr = footXfo.tr self.legEndInputTgt.xfo.ori = ankleXfo.ori self.legEndFKInputTgt.xfo.tr = footXfo.tr self.legEndFKInputTgt.xfo.ori = ankleXfo.ori self.ikTargetOutputTgt.xfo.tr = footXfo.tr self.ikTargetOutputTgt.xfo.ori = ankleXfo.ori # Eval Canvas Ops self.footPivotCanvasOp.evaluate() self.footSolverCanvasOp.evaluate() # Eval Constraints self.ikTargetOutputConstraint.evaluate() self.ankleFKInputConstraint.evaluate()
def __init__(self, name='FKChain', parent=None): Profiler.getInstance().push("Construct FK Chain Rig Component:" + name) super(DyanmicChainComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # FK self.fkCtrlSpaces = [] self.fkCtrls = [] self.setNumControls(4) # Add Component Params to FK control chainSettingsAttrGrp = AttributeGroup("DisplayInfo_ChainSettings", parent=self.fkCtrls[0]) chainDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=chainSettingsAttrGrp) self.simulateInputAttr = BoolAttribute('simulate', value=False, parent=chainSettingsAttrGrp) self.resetframeInputAttr = ScalarAttribute('resetframe', value=1, parent=chainSettingsAttrGrp) self.frameInputAttr = ScalarAttribute('frame', value=0, parent=chainSettingsAttrGrp) self.simBlendStartInputAttr = ScalarAttribute( 'simBlendStart', value=0.7, minValue=0.0, maxValue=1.0, parent=chainSettingsAttrGrp) self.simBlendEndInputAttr = ScalarAttribute( 'simBlendEnd', value=1.0, minValue=0.0, maxValue=1.0, parent=chainSettingsAttrGrp) self.dampeningInputAttr = ScalarAttribute('dampening', value=0.3, minValue=0.0, maxValue=1.0, parent=chainSettingsAttrGrp) self.gravityInputAttr = ScalarAttribute('gravity', value=-9.8, parent=chainSettingsAttrGrp) self.massStartInputAttr = ScalarAttribute('massStart', value=0.35, minValue=0.0, maxValue=10.0, parent=chainSettingsAttrGrp) self.massEndInputAttr = ScalarAttribute('massEnd', value=1.0, minValue=0.0, maxValue=10.0, parent=chainSettingsAttrGrp) # Connect IO to controls self.drawDebugInputAttr.connect(chainDrawDebugInputAttr) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.deformerJoints = [] self.boneOutputsTgt = [] self.setNumDeformers(4) # ===================== # Create Component I/O # ===================== # Set IO Targets self.boneOutputs.setTarget(self.boneOutputsTgt) # ============== # Constrain I/O # ============== # Constraint inputs self.rootInputConstraint = PoseConstraint('_'.join([ self.fkCtrlSpaces[0].getName(), 'To', self.rootInputTgt.getName() ])) self.rootInputConstraint.setMaintainOffset(True) self.rootInputConstraint.addConstrainer(self.rootInputTgt) self.fkCtrlSpaces[0].addConstraint(self.rootInputConstraint) # =============== # Add Splice Ops # =============== # Add Output Splice Op self.dynamicChainKLOp = KLOperator('dynamicChainKLOp', 'DynamicChainSolver', 'Kraken') self.addOperator(self.dynamicChainKLOp) # Add Att Inputs self.dynamicChainKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.dynamicChainKLOp.setInput('rigScale', self.rigScaleInputAttr) self.dynamicChainKLOp.setInput('simulate', self.simulateInputAttr) self.dynamicChainKLOp.setInput('resetframe', self.resetframeInputAttr) self.dynamicChainKLOp.setInput('frame', self.frameInputAttr) self.dynamicChainKLOp.setInput('simBlendStart', self.simBlendStartInputAttr) self.dynamicChainKLOp.setInput('simBlendEnd', self.simBlendEndInputAttr) self.dynamicChainKLOp.setInput('dampening', self.dampeningInputAttr) self.dynamicChainKLOp.setInput('gravity', self.gravityInputAttr) self.dynamicChainKLOp.setInput('massStart', self.massStartInputAttr) self.dynamicChainKLOp.setInput('massEnd', self.massEndInputAttr) # Add Xfo Inputs self.dynamicChainKLOp.setInput('fkPose', self.fkCtrls) # Add Xfo Outputs self.dynamicChainKLOp.setOutput('animPose', self.boneOutputsTgt) # Add Deformer Splice Op self.deformersToOutputsKLOp = KLOperator('fkChainDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.deformersToOutputsKLOp) # Add Att Inputs self.deformersToOutputsKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.deformersToOutputsKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.deformersToOutputsKLOp.setInput('constrainers', self.boneOutputsTgt) # Add Xfo Outputs self.deformersToOutputsKLOp.setOutput('constrainees', self.deformerJoints) Profiler.getInstance().pop()
def __init__(self, name='limb', parent=None): Profiler.getInstance().push("Construct StretchyLimb Rig Component:" + name) super(StretchyLimbComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Upper (FK) self.upperFKCtrlSpace = CtrlSpace('upperFK', parent=self.ctrlCmpGrp) self.upperFKCtrl = Control('upperFK', parent=self.upperFKCtrlSpace, shape="cube") self.upperFKCtrl.alignOnXAxis() # Lower (FK) self.lowerFKCtrlSpace = CtrlSpace('lowerFK', parent=self.upperFKCtrl) self.lowerFKCtrl = Control('lowerFK', parent=self.lowerFKCtrlSpace, shape="cube") self.lowerFKCtrl.alignOnXAxis() # End (IK) self.limbIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.limbIKCtrl = Control('IK', parent=self.limbIKCtrlSpace, shape="pin") # Add Component Params to IK control # TODO: Move these separate control limbSettingsAttrGrp = AttributeGroup("DisplayInfo_StretchyLimbSettings", parent=self.limbIKCtrl) limbDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=limbSettingsAttrGrp) self.limbBone0LenInputAttr = ScalarAttribute('bone0Len', value=1.0, parent=limbSettingsAttrGrp) self.limbBone1LenInputAttr = ScalarAttribute('bone1Len', value=1.0, parent=limbSettingsAttrGrp) limbIKBlendInputAttr = ScalarAttribute('ikblend', value=1.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSoftIKInputAttr = BoolAttribute('softIK', value=True, parent=limbSettingsAttrGrp) limbSoftRatioInputAttr = ScalarAttribute('softRatio', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbStretchInputAttr = BoolAttribute('stretch', value=True, parent=limbSettingsAttrGrp) limbStretchBlendInputAttr = ScalarAttribute('stretchBlend', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSlideInputAttr = ScalarAttribute('slide', value=0.0, minValue=-1.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbPinInputAttr = ScalarAttribute('pin', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) self.rightSideInputAttr = BoolAttribute('rightSide', value=False, parent=limbSettingsAttrGrp) self.drawDebugInputAttr.connect(limbDrawDebugInputAttr) # UpV (IK Pole Vector) self.limbUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.limbUpVCtrl = Control('UpV', parent=self.limbUpVCtrlSpace, shape="triangle") self.limbUpVCtrl.alignOnZAxis() # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) upperDef = Joint('upper', parent=self.defCmpGrp) upperDef.setComponent(self) lowerDef = Joint('lower', parent=self.defCmpGrp) lowerDef.setComponent(self) endDef = Joint('end', parent=self.defCmpGrp) endDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.limbIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.limbIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.limbIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbIKCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.limbIKCtrlSpace.addConstraint(self.limbIKCtrlSpaceInputConstraint) self.limbUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.limbUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.limbUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbUpVCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.limbUpVCtrlSpace.addConstraint(self.limbUpVCtrlSpaceInputConstraint) self.limbRootInputConstraint = PoseConstraint('_'.join([self.limbIKCtrl.getName(), 'To', self.limbParentInputTgt.getName()])) self.limbRootInputConstraint.setMaintainOffset(True) self.limbRootInputConstraint.addConstrainer(self.limbParentInputTgt) self.upperFKCtrlSpace.addConstraint(self.limbRootInputConstraint) # =============== # Add Splice Ops # =============== # Add StretchyLimb Splice Op self.limbIKKLOp = KLOperator('limbKLOp', 'TwoBoneStretchyIKSolver', 'Kraken') self.addOperator(self.limbIKKLOp) # Add Att Inputs self.limbIKKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.limbIKKLOp.setInput('rigScale', self.rigScaleInputAttr) self.limbIKKLOp.setInput('bone0Len', self.limbBone0LenInputAttr) self.limbIKKLOp.setInput('bone1Len', self.limbBone1LenInputAttr) self.limbIKKLOp.setInput('ikblend', limbIKBlendInputAttr) self.limbIKKLOp.setInput('softIK', limbSoftIKInputAttr) self.limbIKKLOp.setInput('softRatio', limbSoftRatioInputAttr) self.limbIKKLOp.setInput('stretch', limbStretchInputAttr) self.limbIKKLOp.setInput('stretchBlend', limbStretchBlendInputAttr) self.limbIKKLOp.setInput('slide', limbSlideInputAttr) self.limbIKKLOp.setInput('pin', limbPinInputAttr) self.limbIKKLOp.setInput('rightSide', self.rightSideInputAttr) # Add Xfo Inputs self.limbIKKLOp.setInput('root', self.limbParentInputTgt) self.limbIKKLOp.setInput('bone0FK', self.upperFKCtrl) self.limbIKKLOp.setInput('bone1FK', self.lowerFKCtrl) self.limbIKKLOp.setInput('ikHandle', self.limbIKCtrl) self.limbIKKLOp.setInput('upV', self.limbUpVCtrl) # Add Xfo Outputs self.limbIKKLOp.setOutput('bone0Out', self.limbUpperOutputTgt) self.limbIKKLOp.setOutput('bone1Out', self.limbLowerOutputTgt) self.limbIKKLOp.setOutput('bone2Out', self.limbEndOutputTgt) # ===================== # Connect the deformers # ===================== # Add StretchyLimb Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('limbDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [self.limbUpperOutputTgt, self.limbLowerOutputTgt, self.limbEndOutputTgt]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [upperDef, lowerDef, endDef]) Profiler.getInstance().pop()
def __init__(self, name='MultiSpring', parent=None): Profiler.getInstance().push("Construct Multi Spring Rig Component:" + name) super(MultiSpringComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Spring Ctrls self.mainSpringCtrl = Control('springSettings', parent=self.ctrlCmpGrp, shape='pin') self.springCtrlSpaces = [] self.springCtrls = [] self.setNumControls(1) # Add Component Params to FK control springSettingsAttrGrp = AttributeGroup("DisplayInfo_SpringSettings", parent=self.mainSpringCtrl) self.springDrawDebugInputAttr = BoolAttribute( 'drawDebug', value=False, parent=springSettingsAttrGrp) self.springtargetOffsetXInputAttr = ScalarAttribute( 'targetOffset_X', value=3.0, minValue=0.0, maxValue=10.0, parent=springSettingsAttrGrp) self.springtargetOffsetYInputAttr = ScalarAttribute( 'targetOffset_Y', value=0.0, minValue=0.0, maxValue=10.0, parent=springSettingsAttrGrp) self.springtargetOffsetZInputAttr = ScalarAttribute( 'targetOffset_Z', value=0.0, minValue=0.0, maxValue=10.0, parent=springSettingsAttrGrp) self.springFrameInputAttr = IntegerAttribute( 'frame', value=1, parent=springSettingsAttrGrp) self.springResetFrameInputAttr = IntegerAttribute( 'reset_frame', value=1, parent=springSettingsAttrGrp) self.springMassInputAttr = ScalarAttribute( 'mass', value=0.5, minValue=0.0, maxValue=20.0, parent=springSettingsAttrGrp) self.springSpringStrengthInputAttr = ScalarAttribute( 'springStrength', value=6.0, minValue=0.0, maxValue=20.0, parent=springSettingsAttrGrp) self.springDampingInputAttr = ScalarAttribute( 'damping', value=0.125, minValue=0.0, maxValue=5.0, parent=springSettingsAttrGrp) # Connect IO to controls self.drawDebugInputAttr.connect(self.springDrawDebugInputAttr) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.deformerJoints = [] self.boneOutputsTgt = [] self.setNumDeformers(4) # ===================== # Create Component I/O # ===================== # Set IO Targets self.boneOutputs.setTarget(self.boneOutputsTgt) # ============== # Constrain I/O # ============== # Constraint inputs self.rootInputConstraint = PoseConstraint('_'.join([ self.springCtrlSpaces[0].getName(), 'To', self.rootInputTgt.getName() ])) self.rootInputConstraint.setMaintainOffset(True) self.rootInputConstraint.addConstrainer(self.rootInputTgt) self.springCtrlSpaces[0].addConstraint(self.rootInputConstraint) # =============== # Add Splice Ops # =============== # Add Solver Canvas Op self.springOp = CanvasOperator('springSolverOp', 'Kraken.Solvers.SpringOffsetSolver') self.addOperator(self.springOp) # Add Att Inputs self.springOp.setInput('drawDebug', self.drawDebugInputAttr) self.springOp.setInput('rigScale', self.rigScaleInputAttr) self.springOp.setInput('targetOffset_X', self.springtargetOffsetXInputAttr) self.springOp.setInput('targetOffset_Y', self.springtargetOffsetYInputAttr) self.springOp.setInput('targetOffset_Z', self.springtargetOffsetZInputAttr) self.springOp.setInput('frame', self.springFrameInputAttr) self.springOp.setInput('reset_frame', self.springResetFrameInputAttr) self.springOp.setInput('mass', self.springMassInputAttr) self.springOp.setInput('spring_strength', self.springSpringStrengthInputAttr) self.springOp.setInput('damping', self.springDampingInputAttr) # Add Xfo Inputs self.springOp.setInput('inputs', self.springCtrls) # Add Xfo Outputs self.springOp.setOutput('outputs', self.boneOutputsTgt) # Add Deformer Splice Op self.deformersToOutputsKLOp = KLOperator('springDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.deformersToOutputsKLOp) # Add Att Inputs self.deformersToOutputsKLOp.setInput('drawDebug', False) self.deformersToOutputsKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.deformersToOutputsKLOp.setInput('constrainers', self.boneOutputsTgt) # Add Xfo Outputs self.deformersToOutputsKLOp.setOutput('constrainees', self.deformerJoints) Profiler.getInstance().pop()
def __init__(self, name, parent=None, location='M'): super(ArmComponent, self).__init__(name, parent, location) # ========= # Controls # ========= # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values if self.getLocation() == "R": ctrlColor = "red" bicepPosition = Vec3(-2.27, 15.295, -0.753) forearmPosition = Vec3(-5.039, 13.56, -0.859) wristPosition = Vec3(-7.1886, 12.2819, 0.4906) else: ctrlColor = "greenBright" bicepPosition = Vec3(2.27, 15.295, -0.753) forearmPosition = Vec3(5.039, 13.56, -0.859) wristPosition = Vec3(7.1886, 12.2819, 0.4906) # Calculate Bicep Xfo rootToWrist = wristPosition.subtract(bicepPosition).unit() rootToElbow = forearmPosition.subtract(bicepPosition).unit() bone1Normal = rootToWrist.cross(rootToElbow).unit() bone1ZAxis = rootToElbow.cross(bone1Normal).unit() bicepXfo = Xfo() bicepXfo.setFromVectors(rootToElbow, bone1Normal, bone1ZAxis, bicepPosition) # Calculate Forearm Xfo elbowToWrist = wristPosition.subtract(forearmPosition).unit() elbowToRoot = bicepPosition.subtract(forearmPosition).unit() bone2Normal = elbowToRoot.cross(elbowToWrist).unit() bone2ZAxis = elbowToWrist.cross(bone2Normal).unit() forearmXfo = Xfo() forearmXfo.setFromVectors(elbowToWrist, bone2Normal, bone2ZAxis, forearmPosition) # Bicep bicepFKCtrl = CubeControl('bicepFK') bicepFKCtrl.alignOnXAxis() bicepLen = bicepPosition.subtract(forearmPosition).length() bicepFKCtrl.scalePoints(Vec3(bicepLen, 1.75, 1.75)) bicepFKCtrl.setColor(ctrlColor) bicepFKCtrl.xfo.copy(bicepXfo) bicepFKCtrlSrtBuffer = SrtBuffer('bicepFK') self.addChild(bicepFKCtrlSrtBuffer) bicepFKCtrlSrtBuffer.xfo.copy(bicepFKCtrl.xfo) bicepFKCtrlSrtBuffer.addChild(bicepFKCtrl) # Forearm forearmFKCtrl = CubeControl('forearmFK') forearmFKCtrl.alignOnXAxis() forearmLen = forearmPosition.subtract(wristPosition).length() forearmFKCtrl.scalePoints(Vec3(forearmLen, 1.5, 1.5)) forearmFKCtrl.setColor(ctrlColor) forearmFKCtrl.xfo.copy(forearmXfo) forearmFKCtrlSrtBuffer = SrtBuffer('forearmFK') bicepFKCtrl.addChild(forearmFKCtrlSrtBuffer) forearmFKCtrlSrtBuffer.xfo.copy(forearmFKCtrl.xfo) forearmFKCtrlSrtBuffer.addChild(forearmFKCtrl) # Arm IK armIKCtrlSrtBuffer = SrtBuffer('IK', parent=self) armIKCtrlSrtBuffer.xfo.tr.copy(wristPosition) armIKCtrl = PinControl('IK', parent=armIKCtrlSrtBuffer) armIKCtrl.xfo.copy(armIKCtrlSrtBuffer.xfo) armIKCtrl.setColor(ctrlColor) if self.getLocation() == "R": armIKCtrl.rotatePoints(0, 90, 0) else: armIKCtrl.rotatePoints(0, -90, 0) # Add Component Params to IK control armDebugInputAttr = BoolAttribute('debug', True) armBone1LenInputAttr = FloatAttribute('bone1Len', bicepLen, 0.0, 100.0) armBone2LenInputAttr = FloatAttribute('bone2Len', forearmLen, 0.0, 100.0) armFkikInputAttr = FloatAttribute('fkik', 0.0, 0.0, 1.0) armSoftIKInputAttr = BoolAttribute('softIK', True) armSoftDistInputAttr = FloatAttribute('softDist', 0.0, 0.0, 1.0) armStretchInputAttr = BoolAttribute('stretch', True) armStretchBlendInputAttr = FloatAttribute('stretchBlend', 0.0, 0.0, 1.0) armSettingsAttrGrp = AttributeGroup("DisplayInfo_ArmSettings") armIKCtrl.addAttributeGroup(armSettingsAttrGrp) armSettingsAttrGrp.addAttribute(armDebugInputAttr) armSettingsAttrGrp.addAttribute(armBone1LenInputAttr) armSettingsAttrGrp.addAttribute(armBone2LenInputAttr) armSettingsAttrGrp.addAttribute(armFkikInputAttr) armSettingsAttrGrp.addAttribute(armSoftIKInputAttr) armSettingsAttrGrp.addAttribute(armSoftDistInputAttr) armSettingsAttrGrp.addAttribute(armStretchInputAttr) armSettingsAttrGrp.addAttribute(armStretchBlendInputAttr) # UpV upVXfo = xfoFromDirAndUpV(bicepPosition, wristPosition, forearmPosition) upVXfo.tr.copy(forearmPosition) upVOffset = Vec3(0, 0, 5) upVOffset = upVXfo.transformVector(upVOffset) armUpVCtrl = TriangleControl('UpV') armUpVCtrl.xfo.tr.copy(upVOffset) armUpVCtrl.alignOnZAxis() armUpVCtrl.rotatePoints(180, 0, 0) armUpVCtrl.setColor(ctrlColor) armUpVCtrlSrtBuffer = SrtBuffer('UpV') self.addChild(armUpVCtrlSrtBuffer) armUpVCtrlSrtBuffer.xfo.tr.copy(upVOffset) armUpVCtrlSrtBuffer.addChild(armUpVCtrl) # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') bicepDef = Joint('bicep') bicepDef.setComponent(self) forearmDef = Joint('forearm') forearmDef.setComponent(self) wristDef = Joint('wrist') wristDef.setComponent(self) deformersLayer.addChild(bicepDef) deformersLayer.addChild(forearmDef) deformersLayer.addChild(wristDef) # ===================== # Create Component I/O # ===================== # Setup component Xfo I/O's clavicleEndInput = Locator('clavicleEnd') clavicleEndInput.xfo.copy(bicepXfo) bicepOutput = Locator('bicep') bicepOutput.xfo.copy(bicepXfo) forearmOutput = Locator('forearm') forearmOutput.xfo.copy(forearmXfo) armEndXfo = Xfo() armEndXfo.rot = forearmXfo.rot.clone() armEndXfo.tr.copy(wristPosition) armEndXfoOutput = Locator('armEndXfo') armEndXfoOutput.xfo.copy(armEndXfo) armEndPosOutput = Locator('armEndPos') armEndPosOutput.xfo.copy(armEndXfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) bone1LenInputAttr = FloatAttribute('bone1Len', bicepLen, 0.0, 100.0) bone2LenInputAttr = FloatAttribute('bone2Len', forearmLen, 0.0, 100.0) fkikInputAttr = FloatAttribute('fkik', 0.0, 0.0, 1.0) softIKInputAttr = BoolAttribute('softIK', True) softDistInputAttr = FloatAttribute('softDist', 0.5, 0.0, 1.0) stretchInputAttr = BoolAttribute('stretch', True) stretchBlendInputAttr = FloatAttribute('stretchBlend', 0.0, 0.0, 1.0) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') # Connect attrs to control attrs debugInputAttr.connect(armDebugInputAttr) bone1LenInputAttr.connect(armBone1LenInputAttr) bone2LenInputAttr.connect(armBone2LenInputAttr) fkikInputAttr.connect(armFkikInputAttr) softIKInputAttr.connect(armSoftIKInputAttr) softDistInputAttr.connect(armSoftDistInputAttr) stretchInputAttr.connect(armStretchInputAttr) stretchBlendInputAttr.connect(armStretchBlendInputAttr) # ============== # Constrain I/O # ============== # Constraint inputs armRootInputConstraint = PoseConstraint('_'.join([armIKCtrl.getName(), 'To', clavicleEndInput.getName()])) armRootInputConstraint.setMaintainOffset(True) armRootInputConstraint.addConstrainer(clavicleEndInput) bicepFKCtrlSrtBuffer.addConstraint(armRootInputConstraint) # Constraint outputs # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(clavicleEndInput) self.addOutput(bicepOutput) self.addOutput(forearmOutput) self.addOutput(armEndXfoOutput) self.addOutput(armEndPosOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(bone1LenInputAttr) self.addInput(bone2LenInputAttr) self.addInput(fkikInputAttr) self.addInput(softIKInputAttr) self.addInput(softDistInputAttr) self.addInput(stretchInputAttr) self.addInput(stretchBlendInputAttr) self.addInput(rightSideInputAttr)
def __init__(self, name='Tentacle', parent=None): Profiler.getInstance().push("Construct Tentacle Rig Component:" + name) super(TentacleComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Chain Base self.chainBase = Locator('ChainBase', parent=self.ctrlCmpGrp) self.chainBase.setShapeVisibility(False) # FK self.fkCtrlSpaces = [] self.fkCtrls = [] self.setNumControls(2) # IK Control self.tentacleIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.tentacleIKCtrl = Control('IK', parent=self.tentacleIKCtrlSpace, shape="sphere") self.tentacleIKCtrl.scalePoints(Vec3(0.25, 0.25, 0.25)) self.tentacleIKCtrl.lockScale(x=True, y=True, z=True) self.tentacleIKCtrl.lockRotation(x=True, y=True, z=True) # Add Component Params to IK control tentacleSettingsAttrGrp = AttributeGroup("DisplayInfo_LegSettings", parent=self.tentacleIKCtrl) tentacledrawDebugInputAttr = BoolAttribute( 'drawDebug', value=False, parent=tentacleSettingsAttrGrp) fkikInputAttr = ScalarAttribute('fkik', value=0.0, minValue=0.0, maxValue=1.0, parent=tentacleSettingsAttrGrp) waveLength_YInputAttr = ScalarAttribute('waveLength_Y', value=1.0, minValue=0.0, maxValue=5.0, parent=tentacleSettingsAttrGrp) waveAmplitude_YInputAttr = ScalarAttribute( 'waveAmplitude_Y', value=0.0, minValue=-3.0, maxValue=3.0, parent=tentacleSettingsAttrGrp) waveFrequency_YInputAttr = ScalarAttribute( 'waveFrequency_Y', value=2.0, minValue=0.0, maxValue=10.0, parent=tentacleSettingsAttrGrp) waveLength_ZInputAttr = ScalarAttribute('waveLength_Z', value=2.329, minValue=0.0, maxValue=5.0, parent=tentacleSettingsAttrGrp) waveAmplitude_ZInputAttr = ScalarAttribute( 'waveAmplitude_Z', value=0.0, minValue=-3.0, maxValue=3.0, parent=tentacleSettingsAttrGrp) waveFrequency_ZInputAttr = ScalarAttribute( 'waveFrequency_Z', value=3.354, minValue=0.0, maxValue=10.0, parent=tentacleSettingsAttrGrp) tipBiasInputAttr = ScalarAttribute('tipBias', value=1.0, minValue=0.0, maxValue=1.0, parent=tentacleSettingsAttrGrp) springStrengthInputAttr = ScalarAttribute( 'springStrength', value=0.3, minValue=0.0, maxValue=1.0, parent=tentacleSettingsAttrGrp) dampeningInputAttr = ScalarAttribute('dampening', value=0.03, minValue=0.0, maxValue=1.0, parent=tentacleSettingsAttrGrp) simulationWeightInputAttr = ScalarAttribute( 'simulationWeight', value=1.0, minValue=0.0, maxValue=1.0, parent=tentacleSettingsAttrGrp) softLimitBoundsInputAttr = ScalarAttribute( 'softLimitBounds', value=5.0, minValue=0.0, maxValue=10.0, parent=tentacleSettingsAttrGrp) # Connect IO to controls self.drawDebugInputAttr.connect(tentacledrawDebugInputAttr) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.deformerJoints = [] self.boneOutputsTgt = [] self.setNumDeformers(4) # ===================== # Create Component I/O # ===================== # Set IO Targets self.boneOutputs.setTarget(self.boneOutputsTgt) # ============== # Constrain I/O # ============== # Constraint inputs tentacleRootInputConstraint = PoseConstraint('_'.join([ self.fkCtrlSpaces[0].getName(), 'To', self.rootInputTgt.getName() ])) tentacleRootInputConstraint.setMaintainOffset(True) tentacleRootInputConstraint.addConstrainer(self.rootInputTgt) self.fkCtrlSpaces[0].addConstraint(tentacleRootInputConstraint) tentacleRootInputConstraint = PoseConstraint('_'.join([ self.tentacleIKCtrlSpace.getName(), 'To', self.rootInputTgt.getName() ])) tentacleRootInputConstraint.setMaintainOffset(True) tentacleRootInputConstraint.addConstrainer(self.rootInputTgt) self.tentacleIKCtrlSpace.addConstraint(tentacleRootInputConstraint) chainBaseInputConstraint = PoseConstraint('_'.join( [self.chainBase.getName(), 'To', self.rootInputTgt.getName()])) chainBaseInputConstraint.setMaintainOffset(True) chainBaseInputConstraint.addConstrainer(self.rootInputTgt) self.chainBase.addConstraint(chainBaseInputConstraint) # =============== # Add Canvas Ops # =============== # Add Canvas Op self.tentacleSolverKLOp = KLOperator('tentacle', 'TentacleSolver', 'Kraken') self.addOperator(self.tentacleSolverKLOp) # # Add Att Inputs self.tentacleSolverKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.tentacleSolverKLOp.setInput('rigScale', self.rigScaleInputAttr) self.tentacleSolverKLOp.setInput('ikblend', fkikInputAttr) self.tentacleSolverKLOp.setInput('waveLength_Y', waveLength_YInputAttr) self.tentacleSolverKLOp.setInput('waveAmplitude_Y', waveAmplitude_YInputAttr) self.tentacleSolverKLOp.setInput('waveFrequency_Y', waveFrequency_YInputAttr) self.tentacleSolverKLOp.setInput('waveLength_Z', waveLength_ZInputAttr) self.tentacleSolverKLOp.setInput('waveAmplitude_Z', waveAmplitude_ZInputAttr) self.tentacleSolverKLOp.setInput('waveFrequency_Z', waveFrequency_ZInputAttr) self.tentacleSolverKLOp.setInput('tipBias', tipBiasInputAttr) self.tentacleSolverKLOp.setInput('springStrength', springStrengthInputAttr) self.tentacleSolverKLOp.setInput('dampening', dampeningInputAttr) self.tentacleSolverKLOp.setInput('simulationWeight', simulationWeightInputAttr) self.tentacleSolverKLOp.setInput('softLimitBounds', softLimitBoundsInputAttr) self.tentacleSolverKLOp.setInput('tipBoneLen', self.tipBoneLenInputAttr) # Add Xfo Inputs self.tentacleSolverKLOp.setInput('chainBase', self.chainBase) self.tentacleSolverKLOp.setInput('ikgoal', self.tentacleIKCtrl) self.tentacleSolverKLOp.setInput('fkcontrols', self.fkCtrls) # Add Xfo Outputs self.tentacleSolverKLOp.setOutput('pose', self.boneOutputsTgt) self.tentacleSolverKLOp.setOutput('tentacleEnd', self.tentacleEndXfoOutputTgt) # Add Deformer Canvas Op self.outputsToDeformersKLOp = KLOperator('defConstraint', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', self.boneOutputsTgt) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', self.deformerJoints) Profiler.getInstance().pop()
def construct(self, jsonData): """Returns a constructed scene item based on the provided json data. Args: jsondata (dict): the JSON data to use to decode into a Math value. Returns: object: The constructed scene item. """ if '__typeHierarchy__' not in jsonData or 'name' not in jsonData: raise Exception("Invalid JSON data for constructing scene item:" + str(jsonData)) # ========= # Controls # ========= if "Control" in jsonData['__typeHierarchy__']: item = Control(jsonData['name']) # =========== # Attributes # =========== elif "AttributeGroup" in jsonData['__typeHierarchy__']: item = AttributeGroup(jsonData['name']) elif "BoolAttribute" in jsonData['__typeHierarchy__']: item = BoolAttribute(jsonData['name']) elif "ScalarAttribute" in jsonData['__typeHierarchy__']: item = ScalarAttribute(jsonData['name']) elif "IntegerAttribute" in jsonData['__typeHierarchy__']: item = IntegerAttribute(jsonData['name']) elif "StringAttribute" in jsonData['__typeHierarchy__']: item = StringAttribute(jsonData['name']) elif "ComponentInput" in jsonData['__typeHierarchy__']: item = ComponentInput(jsonData['name']) elif "ComponentOutput" in jsonData['__typeHierarchy__']: item = ComponentOutput(jsonData['name']) # ============ # Constraints # ============ elif "OrientationConstraint" in jsonData['__typeHierarchy__']: item = OrientationConstraint(jsonData['name']) elif "PoseConstraint" in jsonData['__typeHierarchy__']: item = PoseConstraint(jsonData['name']) elif "PositionConstraint" in jsonData['__typeHierarchy__']: item = PositionConstraint(jsonData['name']) elif "ScaleConstraint" in jsonData['__typeHierarchy__']: item = ScaleConstraint(jsonData['name']) elif "BaseConstraint" in jsonData['__typeHierarchy__']: item = BaseConstraint(jsonData['name']) # ========== # Operators # ========== elif "KLOperator" in jsonData['__typeHierarchy__']: item = KLOperator(jsonData['name']) # ============ # Scene Items # ============ elif "Group" in jsonData['__typeHierarchy__']: item = Group(jsonData['name']) elif "Null" in jsonData['__typeHierarchy__']: item = Null(jsonData['name']) elif "Chain" in jsonData['__typeHierarchy__']: item = Chain(jsonData['name']) elif "Joint" in jsonData['__typeHierarchy__']: item = Joint(jsonData['name']) elif "Container" in jsonData['__typeHierarchy__']: item = Container(jsonData['name']) elif "Curve" in jsonData['__typeHierarchy__']: item = Curve(jsonData['name']) elif "HierarchyGroup" in jsonData['__typeHierarchy__']: item = HierarchyGroup(jsonData['name']) elif "Joint" in jsonData['__typeHierarchy__']: item = Joint(jsonData['name']) elif "Layer" in jsonData['__typeHierarchy__']: item = Layer(jsonData['name']) elif "Locator" in jsonData['__typeHierarchy__']: item = Locator(jsonData['name']) elif "SceneItem" in jsonData['__typeHierarchy__']: item = SceneItem(jsonData['name']) else: raise Exception("KrakenLoader does not support the given type:" + jsonData['__typeHierarchy__']) # Before registering or decoding, set the parent so that the full name contains the entire path. if len(self.parentItems) > 0: item.setParent(self.parentItems[-1]) self.registerItem(item) # Store the item as the parent item before decoding the object # which in turn decodes the children items. self.parentItems.append(item) item.jsonDecode(self, jsonData) # Pop the parent item stack, which reverts the current parent item # to the previous value. self.parentItems.pop() return item
from kraken import plugins from kraken.core.objects.locator import Locator from kraken.core.objects.attributes.attribute_group import AttributeGroup from kraken.core.objects.attributes.bool_attribute import BoolAttribute from kraken.core.traverser.traverser import Traverser locA = Locator("locatorA") locB = Locator("locatorB") groupA = AttributeGroup("settings", locA) groupB = AttributeGroup("settings", locB) attrA = BoolAttribute('flag', True, groupA) attrB = BoolAttribute('flag', True, groupB) attrB.connect(attrA) trav = Traverser() trav.addRootItem(attrB) def callback(**args): item = args.get('item', None) print 'Visited '+item.getDecoratedPath() trav.traverse(itemCallback = callback)
def __init__(self, name="foot", parent=None): Profiler.getInstance().push("Construct Neck Rig Component:" + name) super(FootComponentRig, self).__init__(name, parent) # ========= # Controls # ========= self.ankleLenInputAttr = ScalarAttribute('ankleLen', 1.0, maxValue=1.0, parent=self.cmpInputAttrGrp) self.toeLenInputAttr = ScalarAttribute('toeLen', 1.0, maxValue=1.0, parent=self.cmpInputAttrGrp) self.rightSideInputAttr = BoolAttribute('rightSide', False, parent=self.cmpInputAttrGrp) self.footAll = Locator('footAll', parent=self.ctrlCmpGrp) self.footAll.setShapeVisibility(False) self.ankleIKCtrlSpace = CtrlSpace('ankleIK', parent=self.footAll) self.ankleIKCtrl = Control('ankleIK', parent=self.ankleIKCtrlSpace, shape="square") self.ankleIKCtrl.alignOnXAxis(negative=True) self.ankleIKCtrl.lockTranslation(True, True, True) self.ankleIKCtrl.lockScale(True, True, True) self.toeIKCtrlSpace = CtrlSpace('toeIK', parent=self.footAll) self.toeIKCtrl = Control('toeIK', parent=self.toeIKCtrlSpace, shape="square") self.toeIKCtrl.alignOnXAxis() self.toeIKCtrl.lockTranslation(True, True, True) self.toeIKCtrl.lockScale(True, True, True) self.ankleFKCtrlSpace = CtrlSpace('ankleFK', parent=self.ctrlCmpGrp) self.ankleFKCtrl = Control('ankleFK', parent=self.ankleFKCtrlSpace, shape="cube") self.ankleFKCtrl.alignOnXAxis() self.ankleFKCtrl.lockTranslation(True, True, True) self.ankleFKCtrl.lockScale(True, True, True) self.toeFKCtrlSpace = CtrlSpace('toeFK', parent=self.ankleFKCtrl) self.toeFKCtrl = Control('toeFK', parent=self.toeFKCtrlSpace, shape="cube") self.toeFKCtrl.alignOnXAxis() self.toeFKCtrl.lockTranslation(True, True, True) self.toeFKCtrl.lockScale(True, True, True) self.footSettingsAttrGrp = AttributeGroup("DisplayInfo_FootSettings", parent=self.ankleIKCtrl) self.footDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=self.footSettingsAttrGrp) self.footRockInputAttr = ScalarAttribute('footRock', value=0.0, minValue=-1.0, maxValue=1.0, parent=self.footSettingsAttrGrp) self.footBankInputAttr = ScalarAttribute('footBank', value=0.0, minValue=-1.0, maxValue=1.0, parent=self.footSettingsAttrGrp) self.drawDebugInputAttr.connect(self.footDebugInputAttr) self.pivotAll = Locator('pivotAll', parent=self.ctrlCmpGrp) self.pivotAll.setShapeVisibility(False) self.backPivotCtrl = Control('backPivot', parent=self.pivotAll, shape="axesHalfTarget") self.backPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) self.backPivotCtrl.lockScale(True, True, True) self.backPivotCtrlSpace = self.backPivotCtrl.insertCtrlSpace() self.frontPivotCtrl = Control('frontPivot', parent=self.pivotAll, shape="axesHalfTarget") self.frontPivotCtrl.rotatePoints(0.0, 180.0, 0.0) self.frontPivotCtrl.lockScale(True, True, True) self.frontPivotCtrlSpace = self.frontPivotCtrl.insertCtrlSpace() self.frontPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) self.outerPivotCtrl = Control('outerPivot', parent=self.pivotAll, shape="axesHalfTarget") self.outerPivotCtrl.rotatePoints(0.0, -90.0, 0.0) self.outerPivotCtrl.lockScale(True, True, True) self.outerPivotCtrlSpace = self.outerPivotCtrl.insertCtrlSpace() self.outerPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) self.innerPivotCtrl = Control('innerPivot', parent=self.pivotAll, shape="axesHalfTarget") self.innerPivotCtrl.rotatePoints(0.0, 90.0, 0.0) self.innerPivotCtrl.lockScale(True, True, True) self.innerPivotCtrlSpace = self.innerPivotCtrl.insertCtrlSpace() self.innerPivotCtrl.scalePoints(Vec3(0.5, 0.5, 0.5)) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.ankleDef = Joint('ankle', parent=self.defCmpGrp) self.ankleDef.setComponent(self) self.toeDef = Joint('toe', parent=self.defCmpGrp) self.toeDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint to inputs self.pivotAllInputConstraint = PoseConstraint('_'.join([self.pivotAll.getName(), 'To', self.ikHandleInputTgt.getName()])) self.pivotAllInputConstraint.setMaintainOffset(True) self.pivotAllInputConstraint.addConstrainer(self.ikHandleInputTgt) self.pivotAll.addConstraint(self.pivotAllInputConstraint) self.ankleFKInputConstraint = PoseConstraint('_'.join([self.ankleFKCtrlSpace.getName(), 'To', self.legEndFKInputTgt.getName()])) self.ankleFKInputConstraint.setMaintainOffset(True) self.ankleFKInputConstraint.addConstrainer(self.legEndFKInputTgt) self.ankleFKCtrlSpace.addConstraint(self.ankleFKInputConstraint) # Constraint outputs self.ikTargetOutputConstraint = PoseConstraint('_'.join([self.ikTargetOutputTgt.getName(), 'To', self.ankleIKCtrl.getName()])) self.ikTargetOutputConstraint.setMaintainOffset(True) self.ikTargetOutputConstraint.addConstrainer(self.ankleIKCtrl) self.ikTargetOutputTgt.addConstraint(self.ikTargetOutputConstraint) # ========================= # Add Foot Pivot Canvas Op # ========================= # self.footPivotCanvasOp = CanvasOperator('footPivotCanvasOp', 'Kraken.Solvers.Biped.BipedFootPivotSolver') self.footPivotCanvasOp = KLOperator('footPivotKLOp', 'BipedFootPivotSolver', 'Kraken') self.addOperator(self.footPivotCanvasOp) # Add Att Inputs self.footPivotCanvasOp.setInput('drawDebug', self.drawDebugInputAttr) self.footPivotCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.footPivotCanvasOp.setInput('rightSide', self.rightSideInputAttr) self.footPivotCanvasOp.setInput('footRock', self.footRockInputAttr) self.footPivotCanvasOp.setInput('footBank', self.footBankInputAttr) # Add Xfo Inputs self.footPivotCanvasOp.setInput('pivotAll', self.pivotAll) self.footPivotCanvasOp.setInput('backPivot', self.backPivotCtrl) self.footPivotCanvasOp.setInput('frontPivot', self.frontPivotCtrl) self.footPivotCanvasOp.setInput('outerPivot', self.outerPivotCtrl) self.footPivotCanvasOp.setInput('innerPivot', self.innerPivotCtrl) # Add Xfo Outputs self.footPivotCanvasOp.setOutput('result', self.footAll) # ========================= # Add Foot Solver Canvas Op # ========================= # self.footSolverCanvasOp = CanvasOperator('footSolverCanvasOp', 'Kraken.Solvers.Biped.BipedFootSolver') self.footSolverCanvasOp = KLOperator('footSolverKLOp', 'BipedFootSolver', 'Kraken') self.addOperator(self.footSolverCanvasOp) # Add Att Inputs self.footSolverCanvasOp.setInput('drawDebug', self.drawDebugInputAttr) self.footSolverCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.footSolverCanvasOp.setInput('ikBlend', self.ikBlendInputAttr) self.footSolverCanvasOp.setInput('ankleLen', self.ankleLenInputAttr) self.footSolverCanvasOp.setInput('toeLen', self.toeLenInputAttr) # Add Xfo Inputs self.footSolverCanvasOp.setInput('legEnd', self.legEndInputTgt) self.footSolverCanvasOp.setInput('ankleIK', self.ankleIKCtrl) self.footSolverCanvasOp.setInput('toeIK', self.toeIKCtrl) self.footSolverCanvasOp.setInput('ankleFK', self.ankleFKCtrl) self.footSolverCanvasOp.setInput('toeFK', self.toeFKCtrl) # Add Xfo Outputs self.footSolverCanvasOp.setOutput('ankle_result', self.ankleOutputTgt) self.footSolverCanvasOp.setOutput('toe_result', self.toeOutputTgt) # =================== # Add Deformer KL Op # =================== self.outputsToDeformersKLOp = KLOperator('foot' + self.getLocation() + 'DeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [self.ankleOutputTgt, self.toeOutputTgt]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [self.ankleDef, self.toeDef]) Profiler.getInstance().pop()
def __init__(self, name='limb', parent=None): Profiler.getInstance().push("Construct StretchyLimb Rig Component:" + name) super(StretchyLimbComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Upper (FK) self.upperFKCtrlSpace = CtrlSpace('upperFK', parent=self.ctrlCmpGrp) self.upperFKCtrl = Control('upperFK', parent=self.upperFKCtrlSpace, shape="cube") self.upperFKCtrl.alignOnXAxis() # Lower (FK) self.lowerFKCtrlSpace = CtrlSpace('lowerFK', parent=self.upperFKCtrl) self.lowerFKCtrl = Control('lowerFK', parent=self.lowerFKCtrlSpace, shape="cube") self.lowerFKCtrl.alignOnXAxis() # End (IK) self.limbIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.limbIKCtrl = Control('IK', parent=self.limbIKCtrlSpace, shape="pin") # Add Component Params to IK control # TODO: Move these separate control limbSettingsAttrGrp = AttributeGroup( "DisplayInfo_StretchyLimbSettings", parent=self.limbIKCtrl) limbDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=limbSettingsAttrGrp) self.limbBone0LenInputAttr = ScalarAttribute( 'bone0Len', value=1.0, parent=limbSettingsAttrGrp) self.limbBone1LenInputAttr = ScalarAttribute( 'bone1Len', value=1.0, parent=limbSettingsAttrGrp) limbIKBlendInputAttr = ScalarAttribute('ikblend', value=1.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSoftIKInputAttr = BoolAttribute('softIK', value=True, parent=limbSettingsAttrGrp) limbSoftRatioInputAttr = ScalarAttribute('softRatio', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbStretchInputAttr = BoolAttribute('stretch', value=True, parent=limbSettingsAttrGrp) limbStretchBlendInputAttr = ScalarAttribute('stretchBlend', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbSlideInputAttr = ScalarAttribute('slide', value=0.0, minValue=-1.0, maxValue=1.0, parent=limbSettingsAttrGrp) limbPinInputAttr = ScalarAttribute('pin', value=0.0, minValue=0.0, maxValue=1.0, parent=limbSettingsAttrGrp) self.rightSideInputAttr = BoolAttribute('rightSide', value=False, parent=limbSettingsAttrGrp) self.drawDebugInputAttr.connect(limbDrawDebugInputAttr) # UpV (IK Pole Vector) self.limbUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.limbUpVCtrl = Control('UpV', parent=self.limbUpVCtrlSpace, shape="triangle") self.limbUpVCtrl.alignOnZAxis() # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) upperDef = Joint('upper', parent=self.defCmpGrp) upperDef.setComponent(self) lowerDef = Joint('lower', parent=self.defCmpGrp) lowerDef.setComponent(self) endDef = Joint('end', parent=self.defCmpGrp) endDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.limbIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.limbIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.limbIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbIKCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.limbIKCtrlSpace.addConstraint(self.limbIKCtrlSpaceInputConstraint) self.limbUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.limbUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.limbUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.limbUpVCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.limbUpVCtrlSpace.addConstraint( self.limbUpVCtrlSpaceInputConstraint) self.limbRootInputConstraint = PoseConstraint('_'.join([ self.limbIKCtrl.getName(), 'To', self.limbParentInputTgt.getName() ])) self.limbRootInputConstraint.setMaintainOffset(True) self.limbRootInputConstraint.addConstrainer(self.limbParentInputTgt) self.upperFKCtrlSpace.addConstraint(self.limbRootInputConstraint) # =============== # Add Splice Ops # =============== # Add StretchyLimb Splice Op self.limbIKKLOp = KLOperator('limbKLOp', 'TwoBoneStretchyIKSolver', 'Kraken') self.addOperator(self.limbIKKLOp) # Add Att Inputs self.limbIKKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.limbIKKLOp.setInput('rigScale', self.rigScaleInputAttr) self.limbIKKLOp.setInput('bone0Len', self.limbBone0LenInputAttr) self.limbIKKLOp.setInput('bone1Len', self.limbBone1LenInputAttr) self.limbIKKLOp.setInput('ikblend', limbIKBlendInputAttr) self.limbIKKLOp.setInput('softIK', limbSoftIKInputAttr) self.limbIKKLOp.setInput('softRatio', limbSoftRatioInputAttr) self.limbIKKLOp.setInput('stretch', limbStretchInputAttr) self.limbIKKLOp.setInput('stretchBlend', limbStretchBlendInputAttr) self.limbIKKLOp.setInput('slide', limbSlideInputAttr) self.limbIKKLOp.setInput('pin', limbPinInputAttr) self.limbIKKLOp.setInput('rightSide', self.rightSideInputAttr) # Add Xfo Inputs self.limbIKKLOp.setInput('root', self.limbParentInputTgt) self.limbIKKLOp.setInput('bone0FK', self.upperFKCtrl) self.limbIKKLOp.setInput('bone1FK', self.lowerFKCtrl) self.limbIKKLOp.setInput('ikHandle', self.limbIKCtrl) self.limbIKKLOp.setInput('upV', self.limbUpVCtrl) # Add Xfo Outputs self.limbIKKLOp.setOutput('bone0Out', self.limbUpperOutputTgt) self.limbIKKLOp.setOutput('bone1Out', self.limbLowerOutputTgt) self.limbIKKLOp.setOutput('bone2Out', self.limbEndOutputTgt) # ===================== # Connect the deformers # ===================== # Add StretchyLimb Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('limbDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [ self.limbUpperOutputTgt, self.limbLowerOutputTgt, self.limbEndOutputTgt ]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [upperDef, lowerDef, endDef]) Profiler.getInstance().pop()
def __init__(self, name='arm', parent=None): Profiler.getInstance().push("Construct Arm Rig Component:" + name) super(ArmComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Bicep self.bicepFKCtrlSpace = CtrlSpace('bicepFK', parent=self.ctrlCmpGrp) self.bicepFKCtrl = Control('bicepFK', parent=self.bicepFKCtrlSpace, shape="cube") self.bicepFKCtrl.alignOnXAxis() # Forearm self.forearmFKCtrlSpace = CtrlSpace('forearmFK', parent=self.bicepFKCtrl) self.forearmFKCtrl = Control('forearmFK', parent=self.forearmFKCtrlSpace, shape="cube") self.forearmFKCtrl.alignOnXAxis() self.handCtrlSpace = CtrlSpace('hand', parent=self.ctrlCmpGrp) self.handCtrl = Control('hand', parent=self.handCtrlSpace, shape="circle") self.handCtrl.rotatePoints(0, 0, 90) self.handCtrl.scalePoints(Vec3(1.0, 0.75, 0.75)) # Arm IK self.armIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.armIKCtrl = Control('IK', parent=self.armIKCtrlSpace, shape="pin") # Add Params to IK control armSettingsAttrGrp = AttributeGroup("DisplayInfo_ArmSettings", parent=self.armIKCtrl) armDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=armSettingsAttrGrp) self.armBone0LenInputAttr = ScalarAttribute('bone1Len', value=0.0, parent=armSettingsAttrGrp) self.armBone1LenInputAttr = ScalarAttribute('bone2Len', value=0.0, parent=armSettingsAttrGrp) armIKBlendInputAttr = ScalarAttribute('fkik', value=0.0, minValue=0.0, maxValue=1.0, parent=armSettingsAttrGrp) armSoftIKInputAttr = BoolAttribute('softIK', value=True, parent=armSettingsAttrGrp) armSoftDistInputAttr = ScalarAttribute('softDist', value=0.0, minValue=0.0, parent=armSettingsAttrGrp) armStretchInputAttr = BoolAttribute('stretch', value=True, parent=armSettingsAttrGrp) armStretchBlendInputAttr = ScalarAttribute('stretchBlend', value=0.0, minValue=0.0, maxValue=1.0, parent=armSettingsAttrGrp) # Hand Params handSettingsAttrGrp = AttributeGroup("DisplayInfo_HandSettings", parent=self.handCtrl) handLinkToWorldInputAttr = ScalarAttribute('linkToWorld', 0.0, maxValue=1.0, parent=handSettingsAttrGrp) self.drawDebugInputAttr.connect(armDebugInputAttr) # UpV self.armUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.armUpVCtrl = Control('UpV', parent=self.armUpVCtrlSpace, shape="triangle") self.armUpVCtrl.alignOnZAxis() self.armUpVCtrl.rotatePoints(180, 0, 0) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) bicepDef = Joint('bicep', parent=defCmpGrp) bicepDef.setComponent(self) forearmDef = Joint('forearm', parent=defCmpGrp) forearmDef.setComponent(self) wristDef = Joint('wrist', parent=defCmpGrp) wristDef.setComponent(self) handDef = Joint('hand', parent=defCmpGrp) handDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.armIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.armIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.armIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.armIKCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.armIKCtrlSpace.addConstraint(self.armIKCtrlSpaceInputConstraint) self.armUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([ self.armUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName() ])) self.armUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.armUpVCtrlSpaceInputConstraint.addConstrainer( self.globalSRTInputTgt) self.armUpVCtrlSpace.addConstraint(self.armUpVCtrlSpaceInputConstraint) self.armRootInputConstraint = PoseConstraint('_'.join([ self.bicepFKCtrlSpace.getName(), 'To', self.clavicleEndInputTgt.getName() ])) self.armRootInputConstraint.setMaintainOffset(True) self.armRootInputConstraint.addConstrainer(self.clavicleEndInputTgt) self.bicepFKCtrlSpace.addConstraint(self.armRootInputConstraint) # Constraint outputs self.handConstraint = PoseConstraint('_'.join( [self.handOutputTgt.getName(), 'To', self.handCtrl.getName()])) self.handConstraint.addConstrainer(self.handCtrl) self.handOutputTgt.addConstraint(self.handConstraint) self.handCtrlSpaceConstraint = PoseConstraint('_'.join([ self.handCtrlSpace.getName(), 'To', self.armEndXfoOutputTgt.getName() ])) self.handCtrlSpaceConstraint.setMaintainOffset(True) self.handCtrlSpaceConstraint.addConstrainer(self.armEndXfoOutputTgt) self.handCtrlSpace.addConstraint(self.handCtrlSpaceConstraint) # =============== # Add Splice Ops # =============== # Add Splice Op self.spliceOp = KLOperator('armKLOp', 'TwoBoneIKSolver', 'Kraken') self.addOperator(self.spliceOp) # Add Att Inputs self.spliceOp.setInput('drawDebug', self.drawDebugInputAttr) self.spliceOp.setInput('rigScale', self.rigScaleInputAttr) self.spliceOp.setInput('bone0Len', self.armBone0LenInputAttr) self.spliceOp.setInput('bone1Len', self.armBone1LenInputAttr) self.spliceOp.setInput('ikblend', armIKBlendInputAttr) self.spliceOp.setInput('softIK', armSoftIKInputAttr) self.spliceOp.setInput('softDist', armSoftDistInputAttr) self.spliceOp.setInput('stretch', armStretchInputAttr) self.spliceOp.setInput('stretchBlend', armStretchBlendInputAttr) self.spliceOp.setInput('rightSide', self.rightSideInputAttr) # Add Xfo Inputs self.spliceOp.setInput('root', self.clavicleEndInputTgt) self.spliceOp.setInput('bone0FK', self.bicepFKCtrl) self.spliceOp.setInput('bone1FK', self.forearmFKCtrl) self.spliceOp.setInput('ikHandle', self.armIKCtrl) self.spliceOp.setInput('upV', self.armUpVCtrl) # Add Xfo Outputs self.spliceOp.setOutput('bone0Out', self.bicepOutputTgt) self.spliceOp.setOutput('bone1Out', self.forearmOutputTgt) self.spliceOp.setOutput('bone2Out', self.armEndXfoOutputTgt) # Add Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('armDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [ self.bicepOutputTgt, self.forearmOutputTgt, self.armEndXfoOutputTgt, self.handOutputTgt ]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput( 'constrainees', [bicepDef, forearmDef, wristDef, handDef]) Profiler.getInstance().pop()
def __init__(self, name='leg', parent=None): Profiler.getInstance().push("Construct Leg Rig Component:" + name) super(LegComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Femur self.femurFKCtrlSpace = CtrlSpace('femurFK', parent=self.ctrlCmpGrp) self.femurFKCtrl = Control('femurFK', parent=self.femurFKCtrlSpace, shape="cube") self.femurFKCtrl.alignOnXAxis() self.femurFKCtrl.lockTranslation(True, True, True) self.femurFKCtrl.lockScale(True, True, True) # Shin self.shinFKCtrlSpace = CtrlSpace('shinFK', parent=self.femurFKCtrl) self.shinFKCtrl = Control('shinFK', parent=self.shinFKCtrlSpace, shape="cube") self.shinFKCtrl.alignOnXAxis() self.shinFKCtrl.lockTranslation(True, True, True) self.shinFKCtrl.lockScale(True, True, True) # IK Handle self.legIKCtrlSpace = CtrlSpace('IK', parent=self.ctrlCmpGrp) self.legIKCtrl = Control('IK', parent=self.legIKCtrlSpace, shape="pin") self.legIKCtrl.lockScale(True, True, True) # Add Component Params to IK control legSettingsAttrGrp = AttributeGroup("DisplayInfo_LegSettings", parent=self.legIKCtrl) legDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=legSettingsAttrGrp) self.legRightSideInputAttr = BoolAttribute('rightSide', value=False, parent=legSettingsAttrGrp) self.legBone0LenInputAttr = ScalarAttribute('bone0Len', value=1.0, parent=legSettingsAttrGrp) self.legBone1LenInputAttr = ScalarAttribute('bone1Len', value=1.0, parent=legSettingsAttrGrp) legIKBlendInputAttr = ScalarAttribute('ikblend', value=1.0, minValue=0.0, maxValue=1.0, parent=legSettingsAttrGrp) # Util Objects self.ikRootPosition = Transform("ikRootPosition", parent=self.ctrlCmpGrp) # Connect Input Attrs self.drawDebugInputAttr.connect(legDrawDebugInputAttr) # Connect Output Attrs self.drawDebugOutputAttr.connect(legDrawDebugInputAttr) self.ikBlendOutputAttr.connect(legIKBlendInputAttr) # UpV self.legUpVCtrlSpace = CtrlSpace('UpV', parent=self.ctrlCmpGrp) self.legUpVCtrl = Control('UpV', parent=self.legUpVCtrlSpace, shape="triangle") self.legUpVCtrl.alignOnZAxis() self.legUpVCtrl.lockRotation(True, True, True) self.legUpVCtrl.lockScale(True, True, True) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) femurDef = Joint('femur', parent=self.defCmpGrp) femurDef.setComponent(self) kneeDef = Joint('knee', parent=self.defCmpGrp) kneeDef.setComponent(self) shinDef = Joint('shin', parent=self.defCmpGrp) shinDef.setComponent(self) # ============== # Constrain I/O # ============== # Constraint inputs self.legIKCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.legIKCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.legIKCtrlSpaceInputConstraint.setMaintainOffset(True) self.legIKCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.legIKCtrlSpace.addConstraint(self.legIKCtrlSpaceInputConstraint) self.legUpVCtrlSpaceInputConstraint = PoseConstraint('_'.join([self.legUpVCtrlSpace.getName(), 'To', self.globalSRTInputTgt.getName()])) self.legUpVCtrlSpaceInputConstraint.setMaintainOffset(True) self.legUpVCtrlSpaceInputConstraint.addConstrainer(self.globalSRTInputTgt) self.legUpVCtrlSpace.addConstraint(self.legUpVCtrlSpaceInputConstraint) self.legRootInputConstraint = PoseConstraint('_'.join([self.femurFKCtrlSpace.getName(), 'To', self.legPelvisInputTgt.getName()])) self.legRootInputConstraint.setMaintainOffset(True) self.legRootInputConstraint.addConstrainer(self.legPelvisInputTgt) self.femurFKCtrlSpace.addConstraint(self.legRootInputConstraint) self.ikRootPosInputConstraint = PoseConstraint('_'.join([self.ikRootPosition.getName(), 'To', self.legPelvisInputTgt.getName()])) self.ikRootPosInputConstraint.setMaintainOffset(True) self.ikRootPosInputConstraint.addConstrainer(self.legPelvisInputTgt) self.ikRootPosition.addConstraint(self.ikRootPosInputConstraint) # Constraint outputs self.legEndFKOutputConstraint = PoseConstraint('_'.join([self.legEndFKOutputTgt.getName(), 'To', self.shinFKCtrl.getName()])) self.legEndFKOutputConstraint.setMaintainOffset(True) self.legEndFKOutputConstraint.addConstrainer(self.shinFKCtrl) self.legEndFKOutputTgt.addConstraint(self.legEndFKOutputConstraint) self.ikHandleOutputConstraint = PoseConstraint('_'.join([self.ikHandleOutputTgt.getName(), 'To', self.legIKCtrl.getName()])) self.ikHandleOutputConstraint.setMaintainOffset(True) self.ikHandleOutputConstraint.addConstrainer(self.legIKCtrl) self.ikHandleOutputTgt.addConstraint(self.ikHandleOutputConstraint) # =============== # Add Splice Ops # =============== # Add Leg Splice Op self.legIKKLOp = KLOperator('legKLOp', 'TwoBoneIKSolver', 'Kraken') self.addOperator(self.legIKKLOp) # Add Att Inputs self.legIKKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.legIKKLOp.setInput('rigScale', self.rigScaleInputAttr) self.legIKKLOp.setInput('bone0Len', self.legBone0LenInputAttr) self.legIKKLOp.setInput('bone1Len', self.legBone1LenInputAttr) self.legIKKLOp.setInput('ikblend', legIKBlendInputAttr) self.legIKKLOp.setInput('rightSide', self.legRightSideInputAttr) # Add Xfo Inputs self.legIKKLOp.setInput('root', self.ikRootPosition) self.legIKKLOp.setInput('bone0FK', self.femurFKCtrl) self.legIKKLOp.setInput('bone1FK', self.shinFKCtrl) self.legIKKLOp.setInput('ikHandle', self.legIKTargetInputTgt) self.legIKKLOp.setInput('upV', self.legUpVCtrl) # Add Xfo Outputs self.legIKKLOp.setOutput('bone0Out', self.femurOutputTgt) self.legIKKLOp.setOutput('bone1Out', self.shinOutputTgt) self.legIKKLOp.setOutput('bone2Out', self.legEndOutputTgt) self.legIKKLOp.setOutput('midJointOut', self.kneeOutputTgt) # Add Leg Deformer Splice Op self.outputsToDeformersKLOp = KLOperator('legDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [self.femurOutputTgt, self.kneeOutputTgt, self.shinOutputTgt]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [femurDef, kneeDef, shinDef]) Profiler.getInstance().pop()
def __init__(self, name='FKCollision', parent=None): Profiler.getInstance().push("Construct FK Collision Rig Component:" + name) super(FKCollisionComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # Ground self.groundCtrl = Control('ground', parent=self.ctrlCmpGrp, shape='square') self.groundCtrl.insertCtrlSpace() groundSettingsAttrGrp = AttributeGroup("DisplayInfo_ChainSettings", parent=self.groundCtrl) self.groundOffsetYInputAttr = ScalarAttribute( 'ground_offsetY', 0.0, minValue=0.0, maxValue=10.0, parent=groundSettingsAttrGrp) # FK self.fkCtrlSpaces = [] self.fkCtrls = [] self.transforms = [] self.setNumControls(4) self.setNumTransforms(4) # Add Component Params to FK control chainSettingsAttrGrp = AttributeGroup("DisplayInfo_ChainSettings", parent=self.fkCtrls[0]) chainDrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=chainSettingsAttrGrp) # Connect IO to controls self.drawDebugInputAttr.connect(chainDrawDebugInputAttr) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.addItem('defCmpGrp', self.defCmpGrp) self.deformerJoints = [] self.boneOutputsTgt = [] self.setNumDeformers(4) # ===================== # Create Component I/O # ===================== # Set IO Targets self.boneOutputs.setTarget(self.boneOutputsTgt) # ============== # Constrain I/O # ============== # Constrain inputs self.rootInputConstraint = PoseConstraint('_'.join([ self.fkCtrlSpaces[0].getName(), 'To', self.rootInputTgt.getName() ])) self.rootInputConstraint.setMaintainOffset(True) self.rootInputConstraint.addConstrainer(self.rootInputTgt) self.fkCtrlSpaces[0].addConstraint(self.rootInputConstraint) # =============== # Add Canvas Ops # =============== # Add Output Canvas Op self.collisionCanvasOp = CanvasOperator( 'collisionCanvasOp', 'Kraken.Solvers.CollideChainSolver') self.addOperator(self.collisionCanvasOp) # Add Att Inputs self.collisionCanvasOp.setInput('drawDebug', self.drawDebugInputAttr) self.collisionCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.collisionCanvasOp.setInput('ground_offsetY', self.groundOffsetYInputAttr) # Add Xfo Inputs self.collisionCanvasOp.setInput('ground', self.groundCtrl) self.collisionCanvasOp.setInput('joints', self.transforms) # Add Xfo Outputs self.collisionCanvasOp.setOutput('outputs', self.boneOutputsTgt) # Add Deformer Canvas Op self.deformersToOutputsKLOp = KLOperator('fkChainDeformerKLOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.deformersToOutputsKLOp) # Add Att Inputs self.deformersToOutputsKLOp.setInput('drawDebug', False) self.deformersToOutputsKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.deformersToOutputsKLOp.setInput('constrainers', self.boneOutputsTgt) # Add Xfo Outputs self.deformersToOutputsKLOp.setOutput('constrainees', self.deformerJoints) Profiler.getInstance().pop()
def __init__(self, name='mjEyelid', parent=None): Profiler.getInstance().push("Construct Eyelid Rig Component:" + name) super(mjEyelidComponentRig, self).__init__(name, parent) # ========= # Controls // Get the Guide Xfos data and create the final controllers, offset them if needed. # ========= # Inputs self.eyelidCtrlSpace = CtrlSpace('eyelid', parent=self.ctrlCmpGrp) self.eyeballLocator = Locator('eyeball', parent=self.ctrlCmpGrp) self.eyeballLocator.setShapeVisibility(False) self.eyelidUpVLocator = Locator('eyelid_Upv', parent=self.eyelidCtrlSpace) self.eyelidUpVLocator.setShapeVisibility(False) # Lid Sides self.lidMedialLocator = Locator('lid_Medial', parent=self.eyelidCtrlSpace) self.lidMedialLocator.setShapeVisibility(False) self.lidLateralLocator = Locator('lid_Lateral', parent=self.eyelidCtrlSpace) self.lidLateralLocator.setShapeVisibility(False) # Lid Upper self.lidUpCtrlSpace = CtrlSpace('lid_Up', parent=self.eyelidCtrlSpace) self.lidUpCtrl = Control('lid_Up', parent=self.lidUpCtrlSpace, shape="cube") self.lidUpCtrl.scalePoints(Vec3(0.05, 0.05, 0.05)) self.lidUpCtrl.lockTranslation(x=True, y=False, z=True) self.lidUpCtrl.setColor("yellow") self.lipUpMedialLocator = Locator('lid_Up_Medial', parent=self.eyelidCtrlSpace) self.lipUpMedialLocator.setShapeVisibility(False) self.lipUpLateralLocator = Locator('lid_Up_Lateral', parent=self.eyelidCtrlSpace) self.lipUpLateralLocator.setShapeVisibility(False) # Lid Lower self.lidLowCtrlSpace = CtrlSpace('lid_Low', parent=self.eyelidCtrlSpace) self.lidLowCtrl = Control('lid_Low', parent=self.lidLowCtrlSpace, shape="cube") self.lidLowCtrl.scalePoints(Vec3(0.05, 0.05, 0.05)) self.lidLowCtrl.lockTranslation(x=True, y=False, z=True) self.lidLowCtrl.setColor("yellow") self.lidLowMedialLocator = Locator('lid_Low_Medial', parent=self.eyelidCtrlSpace) self.lidLowMedialLocator.setShapeVisibility(False) self.lidLowLateralLocator = Locator('lid_Low_Lateral', parent=self.eyelidCtrlSpace) self.lidLowLateralLocator.setShapeVisibility(False) # Lid Attributes lidUp_AttrGrp = AttributeGroup("Eyelid_Settings", parent=self.lidUpCtrl) lidLow_AttrGrp = AttributeGroup("Eyelid_Settings", parent=self.lidLowCtrl) self.lidUp_OffsetInputAttr = BoolAttribute('Eyeball_Offset', value=True, parent=lidUp_AttrGrp) self.lidUp_FollowFactorInputAttr = ScalarAttribute( 'Eyeball_Follow_Factor', value=1.0, parent=lidUp_AttrGrp) self.lidUp_DebugInputAttr = BoolAttribute('DrawDebug', value=False, parent=lidUp_AttrGrp) self.lidUp_MedialBlinkInputAttr = ScalarAttribute( 'Medial_Blink_Factor', value=0.25, parent=lidUp_AttrGrp) self.lidUp_LateralBlinkInputAttr = ScalarAttribute( 'Lateral_Blink_Factor', value=0.65, parent=lidUp_AttrGrp) self.lidUp_DefCountInputAttr = IntegerAttribute('numDeformers', value=10, parent=lidUp_AttrGrp) self.lidLow_OffsetInputAttr = BoolAttribute('Eyeball_Offset', value=True, parent=lidLow_AttrGrp) self.lidLow_FollowFactorInputAttr = ScalarAttribute( 'Eyeball_Follow_Factor', value=0.8, parent=lidLow_AttrGrp) self.lidLow_DebugInputAttr = BoolAttribute('DrawDebug', value=False, parent=lidLow_AttrGrp) self.lidLow_MedialBlinkInputAttr = ScalarAttribute( 'Medial_Blink_Factor', value=0.25, parent=lidLow_AttrGrp) self.lidLow_LateralBlinkInputAttr = ScalarAttribute( 'Lateral_Blink_Factor', value=0.65, parent=lidLow_AttrGrp) self.lidLow_DefCountInputAttr = IntegerAttribute('numDeformers', value=10, parent=lidLow_AttrGrp) self.lidUp_DebugInputAttr.connect(self.drawDebugInputAttr) self.lidLow_DebugInputAttr.connect(self.drawDebugInputAttr) self.lidUp_DefCountInputAttr.connect(self.numUpDeformersInputAttr) self.lidLow_DefCountInputAttr.connect(self.numLowDeformersInputAttr) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) # Lid Sides lidMedialDef = Joint('lid_Medial', parent=self.defCmpGrp) lidMedialDef.setComponent(self) lidLateralDef = Joint('lid_Lateral', parent=self.defCmpGrp) lidLateralDef.setComponent(self) # Lid Up self.eyelidUpDef = [] self.eyelidUpOutputs = [] self.setNumUpDeformers(1) # Lid Low self.eyelidLowDef = [] self.eyelidLowOutputs = [] self.setNumLowDeformers(1) # ===================== # Create Component I/O # ===================== # Setup component Xfo I/O's self.eyelidUpOutput.setTarget(self.eyelidUpOutputs) self.eyelidLowOutput.setTarget(self.eyelidLowOutputs) # ============== # Constrain I/O # ============== # Constraint inputs self.headInputConstraint = PoseConstraint('_'.join([ self.eyelidCtrlSpace.getName(), 'To', self.headInputTgt.getName() ])) self.headInputConstraint.addConstrainer(self.headInputTgt) self.eyelidCtrlSpace.addConstraint(self.headInputConstraint) self.eyeballInputConstraint = PoseConstraint('_'.join([ self.eyeballLocator.getName(), 'To', self.eyeballInputTgt.getName() ])) self.eyeballInputConstraint.setMaintainOffset(True) self.eyeballInputConstraint.addConstrainer(self.eyeballInputTgt) self.eyeballLocator.addConstraint(self.eyeballInputConstraint) # =============== # Add Splice Ops # =============== # Add MultiPoseConstraint Joints Splice Op self.outputsToDeformersKLOp = KLOperator('Canvas_Eyelid_Side_Op', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToDeformersKLOp) # Add Att Inputs self.outputsToDeformersKLOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToDeformersKLOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToDeformersKLOp.setInput('constrainers', [ self.lidMedialLocator, self.lidLateralLocator, ]) # Add Xfo Outputs self.outputsToDeformersKLOp.setOutput('constrainees', [ lidMedialDef, lidLateralDef, ]) # Add Lid Up Canvas Op self.lidUpCanvasOp = CanvasOperator( 'Canvas_Eyelid_Up_Op', 'MJCG.Solvers.mjEyelidConstraintSolver') self.addOperator(self.lidUpCanvasOp) # Add Attributes Inputs self.lidUpCanvasOp.setInput('drawDebug', self.lidUp_DebugInputAttr) self.lidUpCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.lidUpCanvasOp.setInput('Eyeball_Offset', self.lidUp_OffsetInputAttr) self.lidUpCanvasOp.setInput('Eyeball_Follow_Factor', self.lidUp_FollowFactorInputAttr) self.lidUpCanvasOp.setInput('Medial_Blink_Factor', self.lidUp_MedialBlinkInputAttr) self.lidUpCanvasOp.setInput('Lateral_Blink_Factor', self.lidUp_LateralBlinkInputAttr) self.lidUpCanvasOp.setInput('Deformer_Count', self.lidUp_DefCountInputAttr) # Add Xfo Inputs self.lidUpCanvasOp.setInput('Eye_Center', self.eyeballLocator) self.lidUpCanvasOp.setInput('Lid_Global', self.eyelidCtrlSpace) self.lidUpCanvasOp.setInput('Lid_UpV', self.eyelidUpVLocator) self.lidUpCanvasOp.setInput('Lid_Medial', self.lidMedialLocator) self.lidUpCanvasOp.setInput('Lid_MedialCen', self.lipUpMedialLocator) self.lidUpCanvasOp.setInput('Lid_Center_Ref', self.lidUpCtrlSpace) self.lidUpCanvasOp.setInput('Lid_Center_Ctrl', self.lidUpCtrl) self.lidUpCanvasOp.setInput('Lid_LateralCen', self.lipUpLateralLocator) self.lidUpCanvasOp.setInput('Lid_Lateral', self.lidLateralLocator) #Add Xfo Outputs self.lidUpCanvasOp.setOutput('result', self.eyelidUpDef) # Add Lid Low Canvas Op self.lidLowCanvasOp = CanvasOperator( 'Canvas_Eyelid_Low_Op', 'MJCG.Solvers.mjEyelidConstraintSolver') self.addOperator(self.lidLowCanvasOp) # Add Attributes Inputs self.lidLowCanvasOp.setInput('drawDebug', self.lidLow_DebugInputAttr) self.lidLowCanvasOp.setInput('rigScale', self.rigScaleInputAttr) self.lidLowCanvasOp.setInput('Eyeball_Offset', self.lidLow_OffsetInputAttr) self.lidLowCanvasOp.setInput('Eyeball_Follow_Factor', self.lidLow_FollowFactorInputAttr) self.lidLowCanvasOp.setInput('Medial_Blink_Factor', self.lidLow_MedialBlinkInputAttr) self.lidLowCanvasOp.setInput('Lateral_Blink_Factor', self.lidLow_LateralBlinkInputAttr) self.lidLowCanvasOp.setInput('Deformer_Count', self.lidLow_DefCountInputAttr) # Add Xfo Inputs self.lidLowCanvasOp.setInput('Eye_Center', self.eyeballLocator) self.lidLowCanvasOp.setInput('Lid_Global', self.eyelidCtrlSpace) self.lidLowCanvasOp.setInput('Lid_UpV', self.eyelidUpVLocator) self.lidLowCanvasOp.setInput('Lid_Medial', self.lidMedialLocator) self.lidLowCanvasOp.setInput('Lid_MedialCen', self.lidLowMedialLocator) self.lidLowCanvasOp.setInput('Lid_Center_Ref', self.lidLowCtrlSpace) self.lidLowCanvasOp.setInput('Lid_Center_Ctrl', self.lidLowCtrl) self.lidLowCanvasOp.setInput('Lid_LateralCen', self.lidLowLateralLocator) self.lidLowCanvasOp.setInput('Lid_Lateral', self.lidLateralLocator) #Add Xfo Outputs self.lidLowCanvasOp.setOutput('result', self.eyelidLowDef) Profiler.getInstance().pop()
def __init__(self, name, parent=None, location='M'): super(FootComponent, self).__init__(name, parent, location) # ========= # Controls # ========= # Setup component attributes defaultAttrGroup = self.getAttributeGroupByIndex(0) defaultAttrGroup.addAttribute(BoolAttribute("toggleDebugging", True)) # Default values if location == 'R': ctrlColor = "red" footPosition = Vec3(-7.1886, 12.2819, 0.4906) footUpV = Vec3(-1.7454, 0.1922, -1.7397) footEndPosition = Vec3(-2.0939, 0.4288, 0.0944) else: ctrlColor = "greenBright" footPosition = Vec3(7.1886, 12.2819, 0.4906) footUpV = Vec3(1.7454, 0.1922, -1.7397) footEndPosition = Vec3(2.0939, 0.4288, 0.0944) # Calculate Clavicle Xfo rootToEnd = footEndPosition.subtract(footPosition).unit() rootToUpV = footUpV.subtract(footPosition).unit() bone1ZAxis = rootToEnd.cross(rootToUpV).unit() bone1Normal = rootToEnd.cross(bone1ZAxis).unit() footXfo = Xfo() if location == "R": footQuat = Quat(Vec3(0.5695, -0.6377, 0.4190), 0.3053) footPos = Vec3(-1.841, 1.1516, -1.237) else: footQuat = Quat(Vec3(0.6377, -0.5695, 0.3053), 0.4190) footPos = Vec3(1.841, 1.1516, -1.237) footXfo.rot = footQuat.clone() footXfo.tr.copy(footPos) # Add Controls footCtrlSrtBuffer = SrtBuffer('foot', parent=self) footCtrlSrtBuffer.xfo.copy(footXfo) footCtrl = CubeControl('foot', parent=footCtrlSrtBuffer) footCtrl.alignOnXAxis() footCtrl.scalePoints(Vec3(2.5, 1.5, 0.75)) footCtrl.xfo.copy(footCtrlSrtBuffer.xfo) footCtrl.setColor(ctrlColor) # Rig Ref objects footRefSrt = Locator('footRef', parent=self) footRefSrt.xfo.copy(footCtrlSrtBuffer.xfo) # Add Component Params to IK control footDebugInputAttr = BoolAttribute('debug', True) footLinkToWorldInputAttr = FloatAttribute('linkToWorld', 1.0, 0.0, 1.0) footSettingsAttrGrp = AttributeGroup("DisplayInfo_HandSettings") footCtrl.addAttributeGroup(footSettingsAttrGrp) footSettingsAttrGrp.addAttribute(footDebugInputAttr) footSettingsAttrGrp.addAttribute(footLinkToWorldInputAttr) # ========== # Deformers # ========== container = self.getParent().getParent() deformersLayer = container.getChildByName('deformers') footDef = Joint('foot') footDef.setComponent(self) deformersLayer.addChild(footDef) # ===================== # Create Component I/O # ===================== # Setup Component Xfo I/O's legEndXfoInput = Locator('legEndXfo') legEndXfoInput.xfo.copy(footCtrlSrtBuffer.xfo) legEndPosInput = Locator('legEndPos') legEndPosInput.xfo.copy(footCtrlSrtBuffer.xfo) footEndOutput = Locator('handEnd') footEndOutput.xfo.copy(footCtrlSrtBuffer.xfo) footOutput = Locator('hand') footOutput.xfo.copy(footCtrlSrtBuffer.xfo) # Setup componnent Attribute I/O's debugInputAttr = BoolAttribute('debug', True) rightSideInputAttr = BoolAttribute('rightSide', location is 'R') linkToWorldInputAttr = FloatAttribute('linkToWorld', 0.0, 0.0, 1.0) # Connect attrs to control attrs debugInputAttr.connect(footDebugInputAttr) linkToWorldInputAttr.connect(footLinkToWorldInputAttr) # ============== # Constrain I/O # ============== # Constraint inputs # Constraint outputs handConstraint = PoseConstraint('_'.join([footOutput.getName(), 'To', footCtrl.getName()])) handConstraint.addConstrainer(footCtrl) footOutput.addConstraint(handConstraint) handEndConstraint = PoseConstraint('_'.join([footEndOutput.getName(), 'To', footCtrl.getName()])) handEndConstraint.addConstrainer(footCtrl) footEndOutput.addConstraint(handEndConstraint) # ================== # Add Component I/O # ================== # Add Xfo I/O's self.addInput(legEndXfoInput) self.addInput(legEndPosInput) self.addOutput(footOutput) self.addOutput(footEndOutput) # Add Attribute I/O's self.addInput(debugInputAttr) self.addInput(rightSideInputAttr) self.addInput(linkToWorldInputAttr)
def __init__(self, name='FKChain', parent=None): Profiler.getInstance().push("Construct FK Chain Rig Component:" + name) super(FKChainComponentRig, self).__init__(name, parent) # ========= # Controls # ========= # FK self.fkCtrlSpaces = [] self.fkCtrls = [] self.setNumControls(4) # Add Component Params to IK control legSettingsAttrGrp = AttributeGroup("DisplayInfo_ChainSettings", parent=self.fkCtrls[0]) legdrawDebugInputAttr = BoolAttribute('drawDebug', value=False, parent=legSettingsAttrGrp) # Connect IO to controls self.drawDebugInputAttr.connect(legdrawDebugInputAttr) # ========== # Deformers # ========== deformersLayer = self.getOrCreateLayer('deformers') self.defCmpGrp = ComponentGroup(self.getName(), self, parent=deformersLayer) self.deformerJoints = [] self.boneOutputsTgt = [] self.setNumDeformers(4) # ===================== # Create Component I/O # ===================== # Set IO Targets self.boneOutputs.setTarget(self.boneOutputsTgt) # ============== # Constrain I/O # ============== # Constraint inputs rootInputConstraint = PoseConstraint('_'.join([ self.fkCtrlSpaces[0].getName(), 'To', self.rootInputTgt.getName() ])) rootInputConstraint.setMaintainOffset(True) rootInputConstraint.addConstrainer(self.rootInputTgt) self.fkCtrlSpaces[0].addConstraint(rootInputConstraint) # =============== # Add Splice Ops # =============== # Add Output Splice Op self.outputsToControlsSpliceOp = SpliceOperator( 'fkChainOutputSpliceOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.outputsToControlsSpliceOp) # Add Att Inputs self.outputsToControlsSpliceOp.setInput('drawDebug', self.drawDebugInputAttr) self.outputsToControlsSpliceOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.outputsToControlsSpliceOp.setInput('constrainers', self.fkCtrls) # Add Xfo Outputs self.outputsToControlsSpliceOp.setOutput('constrainees', self.boneOutputsTgt) # Add Deformer Splice Op self.deformersToOutputsSpliceOp = SpliceOperator( 'fkChainDeformerSpliceOp', 'MultiPoseConstraintSolver', 'Kraken') self.addOperator(self.deformersToOutputsSpliceOp) # Add Att Inputs self.deformersToOutputsSpliceOp.setInput('drawDebug', self.drawDebugInputAttr) self.deformersToOutputsSpliceOp.setInput('rigScale', self.rigScaleInputAttr) # Add Xfo Inputs self.deformersToOutputsSpliceOp.setInput('constrainers', self.boneOutputsTgt) # Add Xfo Outputs self.deformersToOutputsSpliceOp.setOutput('constrainees', self.deformerJoints) Profiler.getInstance().pop()
from kraken import plugins from kraken.core.objects.locator import Locator from kraken.core.objects.attributes.attribute_group import AttributeGroup from kraken.core.objects.attributes.bool_attribute import BoolAttribute from kraken.core.traverser.traverser import Traverser locA = Locator("locatorA") locB = Locator("locatorB") groupA = AttributeGroup("settings", locA) groupB = AttributeGroup("settings", locB) attrA = BoolAttribute('flag', True, groupA) attrB = BoolAttribute('flag', True, groupB) attrB.connect(attrA) trav = Traverser() trav.addRootItem(attrB) def callback(**args): item = args.get('item', None) print 'Visited ' + item.getDecoratedPath() trav.traverse(itemCallback=callback)