Ejemplo n.º 1
0
def createIK(primJntNameList, limbs):
    for pos in posList:
        ctrlName = 'CTRL_IK_' + pos + primJntNameList[1]
        pvName = 'CTRL_IK_' + pos + primJntNameList[0] + 'TW'
        ikName = 'IK_' + pos + primJntNameList[1]
        pVector = ikName + '.poleVector'
        PVOffset = ikName + '_poleVectorConstraint1.offset'
        sJoint = jointPrifix + pos + limbs[0]
        eEfector = jointPrifix + pos + limbs[2]

        cmds.ikHandle(n=ikName, sol='ikRPsolver', sj=sJoint, ee=eEfector)

        prePVValuX = cmds.getAttr(pVector + 'X')
        prePVValuY = cmds.getAttr(pVector + 'Y')
        prePVValuZ = cmds.getAttr(pVector + 'Z')

        cmds.pointConstraint(ctrlName, ikName, mo=True)

        cmds.poleVectorConstraint(pvName, ikName)
        pVValuX = cmds.getAttr(pVector + 'X')
        pVValuY = cmds.getAttr(pVector + 'Y')
        pVValuZ = cmds.getAttr(pVector + 'Z')

        setX = prePVValuX - pVValuX
        setY = prePVValuY - pVValuY
        setZ = prePVValuZ - pVValuZ

        cmds.setAttr(PVOffset + 'X', setX)
        cmds.setAttr(PVOffset + 'Y', setY)
        cmds.setAttr(PVOffset + 'Z', setZ)

        srcCTRL = ctrlName
        dstJNT = jointPrifix + pos + limbs[2]
        cmds.orientConstraint(srcCTRL, dstJNT, mo=True)
Ejemplo n.º 2
0
    def sample(self, *args):
        # Build joint chain
        cmds.select(cl=True)
        chain1_jnt = cmds.joint(n='chain1_jnt', p=[0, 6, 0])
        cmds.joint(n='chain2_jnt', p=[0, 3, 1])
        chain3_jnt = cmds.joint(n='chain3_jnt', p=[0, 0, 0])

        # Build ikHandle
        chain_ikHandle = cmds.ikHandle(n='chain_ikHandle',
                                       startJoint=chain1_jnt,
                                       endEffector=chain3_jnt,
                                       sol='ikRPsolver')[0]

        # Build pole vector
        pole_vector_loc = cmds.spaceLocator(n='pole_vector_loc')[0]
        cmds.setAttr('{0}.translateY'.format(pole_vector_loc), 3)
        cmds.setAttr('{0}.translateZ'.format(pole_vector_loc), 2)
        cmds.poleVectorConstraint(pole_vector_loc, chain_ikHandle)

        # Build controller
        controller = cmds.circle(nr=[0, 1, 0], r=1)[0]
        cmds.pointConstraint(controller, chain_ikHandle)

        # Run Standalone code
        No_Flip_Pole_Vector().build(root_joint=chain1_jnt,
                                    controller=controller,
                                    pole_vector=pole_vector_loc,
                                    name='example')
    def createElbow(self, ikJntsDrive, leftRight, armLength, ikArms, isLeft,
                    colourTU, *args):

        elbowName = "CTRL_" + leftRight + "elbow"

        elbowOffsetCtrl = []
        elbowOffsetCtrl.append(
            mc.group(n="OFFSET_" + elbowName, w=True, em=True))
        elbowOffsetCtrl.append(mc.spaceLocator(p=(0, 0, 0), name=elbowName)[0])
        elbowOffsetCtrl.append(mc.group(n="AUTO_" + elbowName, w=True,
                                        em=True))

        mc.parent(elbowOffsetCtrl[2], elbowOffsetCtrl[0])
        mc.parent(elbowOffsetCtrl[1], elbowOffsetCtrl[2])

        mc.setAttr("{0}.overrideEnabled".format(elbowOffsetCtrl[1]), 1)
        mc.setAttr("{0}.overrideColor".format(elbowOffsetCtrl[1]), colourTU)

        toDelete = mc.pointConstraint(ikJntsDrive, elbowOffsetCtrl[0])
        toDelete2 = mc.aimConstraint(ikJntsDrive[1],
                                     elbowOffsetCtrl[0],
                                     aim=(0, 0, 1))

        mc.delete(toDelete, toDelete2)

        if not isLeft:
            armLength = -armLength

        mc.move(armLength / 2, elbowOffsetCtrl[0], z=True, os=True)

        mc.poleVectorConstraint(elbowOffsetCtrl[1], ikArms[0])

        return elbowOffsetCtrl
Ejemplo n.º 4
0
    def ConnectNoFlipControls(self, prefix):
        #grab the legs and ikh them
        topNFIKH = cmds.ikHandle(n=prefix + 'topNoFlip_IKH',
                                 sj=self.topNoFlipJnt,
                                 ee=self.topNoFlipEndJnt,
                                 sol="ikRPsolver")[0]
        botNFIKH = cmds.ikHandle(n=prefix + 'botNoFlip_IKH',
                                 sj=self.botNoFlipJnt,
                                 ee=self.botNoFlipEndJnt,
                                 sol="ikRPsolver")[0]

        #pv the locs
        cmds.poleVectorConstraint(self.topNFPV, topNFIKH)
        cmds.poleVectorConstraint(self.botNFPV, botNFIKH)

        #appropriate parenting
        cmds.parent(self.botNFPV, self.revAnkleJnt)
        cmds.parent(topNFIKH, self.revAnkleJnt)
        cmds.parent(self.botNoFlipJnt, self.revAnkleJnt)
        #connect the leg to the connector joing
        cmds.parent(self.hipJnt, self.legConJnt)
        #finish parenting under the connector
        cmds.parent(self.topNFPV, self.legConJnt)
        cmds.parent(botNFIKH, self.legConJnt)
        cmds.parent(self.topNoFlipJnt, self.legConJnt)

        #knee loc parenting
        cmds.parent(self.kneeTopLoc, self.topNoFlipJnt)
        cmds.parent(self.kneeBottomLoc, self.botNoFlipJnt)

        #final constraint to enable the no flip behavior
        cmds.pointConstraint(self.kneeTopLoc, self.kneeBottomLoc,
                             prefix + self.LEG_JNT_NAMES[1] + "PVOffset_GRP")
Ejemplo n.º 5
0
def findPoleVector(loc, targetHandle):

    # This func is kinda black magic
    # All credits to https://vimeo.com/66015036
    start = cmds.xform(ogChain[0], q=1, ws=1, t=1)
    mid = cmds.xform(ogChain[1], q=1, ws=1, t=1)
    end = cmds.xform(ogChain[2], q=1, ws=1, t=1)

    startV = om.MVector(start[0], start[1], start[2])
    midV = om.MVector(mid[0], mid[1], mid[2])
    endV = om.MVector(end[0], end[1], end[2])

    startEnd = endV - startV
    startMid = midV - startV

    dotP = startMid * startEnd
    proj = float(dotP) / float(startEnd.length())
    startEndN = startEnd.normal()
    projV = startEndN * proj

    arrowV = startMid - projV
    arrowV*= 10 #distance from joint
    finalV = arrowV + midV
    
    cmds.xform(loc, ws=1, t=(finalV.x, finalV.y ,finalV.z))

    locGrp = cmds.group(em=1, n=loc + "_grp")

    #snap, parent offsetGrp, set color and then make Constraint
    cmds.delete(cmds.pointConstraint(loc, locGrp))
    cmds.parent(loc, locGrp)
    cmds.makeIdentity(loc, a=1, t=1, r=1, s=1)
    cmds.color(loc, rgb=controllerColor)

    cmds.poleVectorConstraint(loc, targetHandle)
Ejemplo n.º 6
0
    def create_pole_vector(self, side, thigh, knee, knee_end, name, ik, color):
        #create a pole vector
        start = cmds.xform(thigh, ws=True, q=True, t=True)
        mid = cmds.xform(knee, ws=True, q=True, t=True)
        end = cmds.xform(knee_end, ws=True, q=True, t=True)
        startV = om.MVector(start[0], start[1], start[2])
        midV = om.MVector(mid[0], mid[1], mid[2])
        endV = om.MVector(end[0], end[1], end[2])

        start_point = endV - startV
        mid_point = midV - startV

        dotP = mid_point * start_point
        proj = float(dotP) / float(start_point.length())

        start_point_N = start_point.normal()
        projV = start_point_N * proj

        arrowV = (mid_point - projV) * 30
        arrowV *= 0.5
        finalV = arrowV + midV

        c = custom_controls.create_custom_controls()
        control = c.knee_curve('PV_ik_' + name + '_' + side)
        self.override_colors(control, color)
        control_group = cmds.group(control,
                                   n='PV_ik_' + name + '_' + side + '_Null')
        cmds.xform(control_group, ws=1, t=(finalV.x, finalV.y, finalV.z))
        cmds.parent(control_group, 'controls')

        #pole vector constraint locator to ik
        cmds.poleVectorConstraint(control, ik)
        return control
def constrainToSelection(_sel, _conType, _parent, _offset, *args):
    if _conType == 'parent':
        for x in _sel:
            conParent = x + str(_parent)
            cmds.parentConstraint( conParent, x, mo=(_offset))
    elif _conType == 'point':
        for x in _sel:
            conParent = x + str(_parent)
            cmds.pointConstraint( conParent, x, mo=(_offset))
    elif _conType == 'orient':
        for x in _sel:
            conParent = x + str(_parent)
            cmds.orientConstraint( conParent, x, mo=(_offset))
    elif _conType == 'scale':
        for x in _sel:
            conParent = x + str(_parent)
            cmds.scaleConstraint( conParent, x, mo=(_offset))
    elif _conType == 'aim':
        for x in _sel:
            conParent = x + str(_parent)
            cmds.aimConstraint( conParent, x, mo=(_offset))
    elif _conType == 'pole vector':
        for x in _sel:
            conParent = x + str(_parent)
            cmds.poleVectorConstraint( conParent, x)
    else:
       return 'ERROR NOT A RECOGNIZED CONSTRAINT TYPE'
Ejemplo n.º 8
0
def bdRigIkArm(side):
    ikChainStart = bdBuildDrvChain(side, 'ik')
    ikChainJoints = cmds.listRelatives(ikChainStart, ad=True, type='joint')
    ikChainJoints.reverse()
    ikBones = ikChainStart + ikChainJoints
    print ikBones
    armIk = cmds.ikHandle(sol='ikRPsolver',
                          sticky='sticky',
                          startJoint=ikBones[0],
                          endEffector=ikBones[2],
                          name=side + '_arm_ikHandle')
    handIk = cmds.ikHandle(sol='ikSCsolver',
                           sticky='sticky',
                           startJoint=ikBones[2],
                           endEffector=ikBones[3],
                           name=side + '_hand_ikHandle')
    ikHandlesGrp = cmds.group([armIk[0], handIk[0]],
                              n=side + '_arm_ikHandles_grp')
    wristPos = cmds.xform(ikBones[2], q=True, ws=True, t=True)
    cmds.move(wristPos[0], wristPos[1], wristPos[2],
              [ikHandlesGrp + '.scalePivot', ikHandlesGrp + '.rotatePivot'])
    pvAnim = cmds.ls(side + '_elbow_ik_anim', type='transform')[0]
    if pvAnim:
        cmds.poleVectorConstraint(pvAnim, armIk[0])

    ikAnimCtrl = cmds.ls(side + '_hand_ik_anim', type='transform')[0]
    cmds.parentConstraint(ikAnimCtrl, ikHandlesGrp)
Ejemplo n.º 9
0
 def surfJnts(name, pairL):
     jntPairs = []
     iks = []
     j = 0
     for pair in pairL:
         jnts = []
         i = 0
         suff = ['_root', '_aim', '_up']
         for point in pair:
             cmds.select(point)
             pos = cmds.xform(point, q=True, t=True, ws=True)
             jnts.append(place.joint(0, name + str(j) + suff[i] + '_jnt', pad=2, rpQuery=False)[0])
             i = i + 1
         j = j + 1
         # parent ik joints
         cmds.parent(jnts[1], jnts[0])
         # orient ik joints
         cmds.joint(jnts[0], e=True, oj='zyx', secondaryAxisOrient='yup')
         jnt.ZeroJointOrient(jnts[1])
         # orient up vector jnt
         cmds.parent(jnts[2], jnts[0])
         jnt.ZeroJointOrient(jnts[2])
         cmds.parent(jnts[2], w=True)
         # append pairs to list
         jntPairs.append(jnts)
         # ik
         ikhndl = cmds.ikHandle(sj=jnts[0], ee=jnts[1], sol='ikRPsolver', sticky='sticky')[0]
         cmds.setAttr(ikhndl + '.visibility', False)
         cmds.poleVectorConstraint(jnts[2], ikhndl)
         iks.append(ikhndl)
         # cleanup
         place.cleanUp(jnts[0], SknJnts=True)
         place.cleanUp(jnts[2], SknJnts=True)
         place.cleanUp(ikhndl, World=True)
     return jntPairs, iks
Ejemplo n.º 10
0
def test_record_ik():
    # Recording IK involves retargeting and untargeting

    _new()
    joint1 = cmds.joint()
    cmds.move(0, 5, 0)
    joint2 = cmds.joint()
    cmds.move(5, 5, 0)
    joint3 = cmds.joint()  # tip
    cmds.move(10, 5, 0)

    handle, eff = cmds.ikHandle(joint1, joint2)
    pole = cmds.spaceLocator()[0]
    cmds.poleVectorConstraint(pole, handle)[0]

    # o---o---o
    # 1   2   3

    solver = api.createSolver()
    markers = api.assignMarkers([joint1, joint2, joint3], solver)
    api.untarget_marker(markers[0])
    api.retarget_marker(markers[1], pole)
    api.retarget_marker(markers[2], handle)

    cmdx.min_time(1)
    cmdx.max_time(5)  # Won't need many frames
    api.recordPhysics(solver)

    joint1 = cmdx.encode(joint1)
    joint2 = cmdx.encode(joint2)
    handle = cmdx.encode(handle)

    assert not joint1["tx"].connected, "%s was connected" % joint1["tx"].path()
    assert not joint2["tx"].connected, "%s was connected" % joint2["tx"].path()
    assert handle["tx"].connected, "%s was not connected" % handle["tx"].path()
Ejemplo n.º 11
0
    def addIKChain(self, startJoint, endJoint, worldParent):
        '''Create an IK RP solver on a chain with end and aim ctrls. Requires three or more joints in chain.
        Also creates a "stub" joint with an SC solver at the end of the chain, so that the last joint's
        rotation is blended between the IK end ctrl and the last FK ctrl properly.
        - worldParent = Drives IK translate and rotate.
        Returns list of [IKAim,IKEnd] ctrls
        '''
        jointList = mpJoint.getJointList(startJoint, endJoint)
        if len(jointList) < 3:
            raise RuntimeError('FKIKChain needs at least three joints')
        #Create IK Chain
        RIGLOG.debug('Adding IK Chain')
        self.name.desc = 'iKHandle'
        handle, effector = cmds.ikHandle(n=self.name.get(),
                                         solver='ikRPsolver',
                                         sj=startJoint,
                                         ee=endJoint)
        self.name.desc = 'effector'
        effector = cmds.rename(effector, self.name.get())
        cmds.parent(handle, self.noXform)

        #-find the location of the aim
        midJointIdx = int(len(jointList) / 2)
        midJoint = jointList[midJointIdx]
        midV = mpMath.Vector(midJoint)
        endV = mpMath.Vector(endJoint)
        aimV = mpRig.getAimVector(startJoint, midJoint, endJoint)

        aimZero, aimCtrl = self.addCtrl('aim',
                                        type='IK',
                                        shape='cross',
                                        parent=worldParent,
                                        xform=aimV)
        endZero, endCtrl = self.addCtrl('end',
                                        type='IK',
                                        shape='cube',
                                        parent=worldParent,
                                        xform=endV)

        #make an 'end null' to have a buffer between the last ctrl and the handle
        self.name.desc = 'IKEnd'
        endNull = cmds.group(em=True, n=self.name.get(), p=self.noXform)
        cmds.xform(endNull,
                   ws=True,
                   m=cmds.xform(endCtrl, ws=True, q=True, m=True))

        #constrain everything
        cmds.parentConstraint(endCtrl, endNull, mo=True)
        cmds.parentConstraint(endNull, handle, mo=True)
        cmds.poleVectorConstraint(aimCtrl, handle)

        #make the aim float between end and root of ik system
        cmds.pointConstraint(endCtrl, worldParent, aimZero, mo=True)

        #IK ctrl pickwalks
        mpRig.addPickParent(aimCtrl, endCtrl)
        mpRig.addPickParent(endCtrl, aimCtrl)

        return (aimCtrl, endCtrl)
Ejemplo n.º 12
0
    def add_constraint(self):
        self.build_ik()

        # Shoulder pivot
        cmds.parentConstraint(self.ctrl_list[0], self.jnt_list[0])
        cmds.parentConstraint(self.ctrl_list[0], self.jnt_helper_list[0])

        # Front foot pivot group
        toe_tap_pivot_grp = cmds.group(em=1,
                                       name='{}toetap_pivot_grp'.format(
                                           self.name))
        flex_pivot_grp = cmds.group(em=1,
                                    name='{}flex_pivot_grp'.format(self.name))
        flex_offset_grp = cmds.group(em=1,
                                     name='{}flex_offset_grp'.format(
                                         self.name))
        swivel_pivot_grp = cmds.group(em=1,
                                      name='{}swivel_pivot_grp'.format(
                                          self.name))
        toe_tip_pivot_grp = cmds.group(em=1,
                                       name='{}toetip_pivot_grp'.format(
                                           self.name))

        foot_pos = cmds.xform(self.jnt_list[3], q=1, ws=1, t=1)
        toe_pos = cmds.xform(self.jnt_list[4], q=1, ws=1, t=1)

        cmds.move(foot_pos[0], foot_pos[1], foot_pos[2], flex_offset_grp)
        cmds.move(foot_pos[0], foot_pos[1], foot_pos[2], flex_pivot_grp)
        cmds.move(foot_pos[0], foot_pos[1], foot_pos[2], toe_tap_pivot_grp)
        cmds.move(foot_pos[0], foot_pos[1], foot_pos[2], swivel_pivot_grp)
        cmds.move(toe_pos[0], toe_pos[1], toe_pos[2], toe_tip_pivot_grp)

        outliner.batch_parent([self.leg_ik_name, self.foot_ik_name],
                              flex_pivot_grp)
        cmds.parent(flex_pivot_grp, flex_offset_grp)
        cmds.parentConstraint(self.jnt_helper_list[3], flex_offset_grp, mo=1)
        outliner.batch_parent([self.toe_ik_name, self.helper_ik_name],
                              toe_tap_pivot_grp)
        outliner.batch_parent([toe_tap_pivot_grp, flex_offset_grp],
                              toe_tip_pivot_grp)
        cmds.parent(toe_tip_pivot_grp, swivel_pivot_grp)
        cmds.parent(swivel_pivot_grp, self.ctrl_list[3])

        cmds.connectAttr(self.ctrl_list[3] + '.Flex',
                         flex_pivot_grp + '.rotateX')
        cmds.connectAttr(self.ctrl_list[3] + '.Swivel',
                         swivel_pivot_grp + '.rotateY')
        cmds.connectAttr(self.ctrl_list[3] + '.Toe_Tap',
                         toe_tap_pivot_grp + '.rotateX')
        cmds.connectAttr(self.ctrl_list[3] + '.Toe_Tip',
                         toe_tip_pivot_grp + '.rotateX')

        # Pole vector constraint
        cmds.poleVectorConstraint(self.ctrl_list[2], self.leg_ik_name)
        cmds.poleVectorConstraint(self.ctrl_list[2], self.helper_ik_name)
        cmds.parent(self.ctrl_offset_list[2], swivel_pivot_grp)

        # Scalable rig setup
        self.add_measurement()
Ejemplo n.º 13
0
def ikControllerConstraintsAlt(constraint, target, constraint2, target2):
    #3b. select parent of target joint
    mc.select(constraint, target)
    mc.parentConstraint(mo=1)
    mc.select(constraint2, target2)
    snapToPos()
    mc.select(constraint2, target)
    mc.poleVectorConstraint()
Ejemplo n.º 14
0
def ikControllerConstraintsAlt(constraint, target, constraint2, target2):
    #3b. select parent of target joint
    mc.select(constraint, target)
    mc.parentConstraint(mo=1)
    mc.select(constraint2, target2)
    snapToPos()
    mc.select(constraint2,target)
    mc.poleVectorConstraint()
Ejemplo n.º 15
0
 def _create_ik_handle(self):
     """Overriden to NOT constrain the ik handle.
     """
     ik_chain = self.chain_b.get()
     ik_handle, effector = cmds.ikHandle(
         startJoint=ik_chain[0], endEffector=self.ik_chain_end_joint.get())
     self.ik_handle.set(ik_handle)
     cmds.parent(ik_handle, self.extras_group.get())
     cmds.poleVectorConstraint(self.ik_pv_ctl.get(), ik_handle)
Ejemplo n.º 16
0
    def install(self):
        cmds.select(d=True)
        # Create Ik joints
        self.rig_info['ikjnts']=utils.createJoint(self.module_info['ikjnts'], self.rig_info['positions'], self.instance)

        # Create Fk joints
        self.rig_info['fkjnts']=utils.createJoint(self.module_info['fkjnts'], self.rig_info['positions'], self.instance)
 
        # Create Rig joints
        self.rig_info['rigjnts']=utils.createJoint(self.module_info['rigjnts'], self.rig_info['positions'], self.instance)
        
    
        # Create Ik Rig
        # Ik handle
        #"ikcontrols": ["ctrl_ik_arm, ikh_arm", "ctrl_pv_arm"
        # Generate a name for the ik handle using self.instance
        ikhname = self.module_info["ikcontrols"][1].replace('_s_', self.instance)
        self.rig_info['ikh']=cmds.ikHandle(n=ikhname, sj=self.rig_info['ikjnts'][0], ee=self.rig_info['ikjnts'][2], sol='ikRPsolver', p=2, w=1 )

        ikctrlname = self.module_info["ikcontrols"][0].replace('_s_', self.instance)
        self.rig_info['ikcontrol']=utils.createControl([[self.rig_info['positions'][2], ikctrlname, 'HandControl.ma']])[0]

        pvpos = utils.calculatePVPosition([self.rig_info['ikjnts'][0], self.rig_info['ikjnts'][1], self.rig_info['ikjnts'][2]])

        self.rig_info['pvcontrol']=utils.createControl([[pvpos, self.module_info["ikcontrols"][2], 'RectangleControl.ma']])[0]

        # Make a control for arm settings
        self.rig_info['setcontrol']=utils.createControl([[self.rig_info['positions'][2], 'ctrl_settings', 'RectangleControl.ma']])[0]
        cmds.addAttr(self.rig_info['setcontrol'][1], ln='IK_FK', at="enum", en="fk:ik:", k=True )

        # Parent ikh to ctrl
        cmds.parent(self.rig_info['ikh'][0], self.rig_info['ikcontrol'][1])

        # PV constraint
        cmds.poleVectorConstraint(self.rig_info['pvcontrol'][1], self.rig_info['ikh'][0])
    
        # orient constrain arm ik_wrist to ctrl_arm
        cmds.orientConstraint(self.rig_info['ikcontrol'][1], self.rig_info['ikjnts'][2], mo=True)

        # Create FK rig   
        self.rig_info['fkcontrols'] = utils.createControl([[self.rig_info['positions'][0], self.module_info["fkcontrols"][0], 'RectangleControl.ma'],
        [self.rig_info['positions'][1], self.module_info["fkcontrols"][1], 'RectangleControl.ma'],
        [self.rig_info['positions'][2], self.module_info["fkcontrols"][2], 'RectangleControl.ma']])

        # Parent fk controls      
        cmds.parent(self.rig_info['fkcontrols'][2][0], self.rig_info['fkcontrols'][1][1])
        cmds.parent(self.rig_info['fkcontrols'][1][0], self.rig_info['fkcontrols'][0][1])

        # Connect Ik and Fk to Rig joints
        switchattr = self.rig_info['setcontrol'][1] + '.IK_FK'
        utils.connectThroughBC(self.rig_info['ikjnts'], self.rig_info['fkjnts'], self.rig_info['rigjnts'], self.instance, switchattr )
  
        # Constrain fk joints to controls.
        [cmds.parentConstraint(self.rig_info['fkcontrols'][i][1], self.rig_info['fkjnts'][i], mo=True) for i in range(len(self.rig_info['fkcontrols']))]

        # SetupIk/Fk match scriptJob
        """
Ejemplo n.º 17
0
    def createArmIK(self):
        ##Create initial IK
        #even though the ik handle is given its start and end it still looks at what maya has selected and complains when more joints are selected, that is shit. autodesk wtf
        ma.select(cl=True)
        ma.select((self.upperArmJnt, self.handJnt))

        #Create IK handle
        self.ikHNodes = ma.ikHandle(self.upperArmJnt, self.handJnt)

        #Rename handle
        self.ikH = ma.rename(self.ikHNodes[0],
                             self.side + "_armIK_" + self.ikhPrefix)

        #Rename control ik end control
        self.ikHandCtlGrp = ma.rename(
            self.ikHandCtlGrp, self.side + "_armIKCtl_" + self.grpPrefix)
        self.ikHandCtl = ma.listRelatives(self.ikHandCtlGrp, f=True)
        #Rename Curve
        self.ikHandCtl = ma.rename(self.ikHandCtl,
                                   self.side + "_armIK_" + self.ctlPrefix)

        #Move end control to object
        pointConTemp = ma.pointConstraint(self.handJnt, self.ikHandCtlGrp)
        ma.delete(pointConTemp)  #delete uneeded constraint
        #Constrain handle to control
        ma.pointConstraint(self.ikHandCtl, self.ikH)

        ##Create a polevector

        #Rename control ik Pole Vector control
        self.ikPVCtlGrp = ma.rename(self.ikPVCtlGrp,
                                    self.side + "_armPVCtl_" + self.grpPrefix)
        self.ikPVCtl = ma.listRelatives(self.ikPVCtlGrp, f=True)
        #Rename Curve
        self.ikPVCtl = ma.rename(self.ikPVCtl,
                                 self.side + "_armPV_" + self.ctlPrefix)

        #Move end Pole Vector to object
        pointConTemp = ma.pointConstraint(self.lowerArmJnt, self.ikPVCtlGrp)
        #Aim down the arm, set up vector to objectRotationUp, and up object to ikStartJnt
        aimConTemp = ma.aimConstraint(self.handJnt,
                                      self.ikPVCtlGrp,
                                      wut="object",
                                      wuo=self.upperArmJnt)

        #delete uneeded constraint
        ma.delete(pointConTemp)
        #delete unneeded constraint
        ma.delete(aimConTemp)

        #Move pole vector backwards
        ma.move(0, -50, 0, self.ikPVCtlGrp, os=True, r=True)
        ma.rotate(0, 0, 0, self.ikPVCtlGrp)

        #pole vector constraint
        ma.poleVectorConstraint(self.ikPVCtl, self.ikH)
Ejemplo n.º 18
0
def ikControllerConstraints(constraint, target, constraint2, target2):
    #3b. select parent of target joint

    # got rid of selection
    #mc.select(constraint, target)
    mc.parentConstraint(constraint, target, mo=1)
    #mc.select(constraint2, target2)
    snapToPos([constraint2, target2])
    #mc.select(constraint2,target)
    mc.poleVectorConstraint(constraint2, target)
Ejemplo n.º 19
0
def ikControllerConstraints(constraint, target, constraint2, target2):
    #3b. select parent of target joint

    # got rid of selection
    #mc.select(constraint, target)
    mc.parentConstraint(constraint, target, mo=1)
    #mc.select(constraint2, target2)
    snapToPos([constraint2, target2])
    #mc.select(constraint2,target)
    mc.poleVectorConstraint(constraint2, target)
Ejemplo n.º 20
0
 def _create_ik_handle(self):
     ik_chain = self.chain_b.get()
     ik_handle, effector = cmds.ikHandle(
         startJoint=ik_chain[0],  # hip
         endEffector=self.ik_chain_end_joint.get(),  # ankle
         solver="ikSpringSolver",
     )
     self.ik_handle.set(ik_handle)
     cmds.parent(ik_handle, self.extras_group.get())
     cmds.poleVectorConstraint(self.ik_pv_ctl.get(), ik_handle)
Ejemplo n.º 21
0
 def _create_ik_handle(self):
     ik_chain = self.chain_b.get()
     ik_handle, effector = cmds.ikHandle(startJoint=ik_chain[0],
                                         endEffector=ik_chain[2])
     self.ik_handle.set(ik_handle)
     cmds.parent(ik_handle, self.extras_group.get())
     cmds.poleVectorConstraint(self.ik_pv_ctl.get(), ik_handle)
     mop.dag.matrix_constraint(self.ik_end_ctl.get(),
                               ik_handle,
                               maintain_offset=True)
Ejemplo n.º 22
0
def bdRigLegBones(side):
    legBones = ['thigh', 'knee', 'foot', 'toe', 'toe_end']
    for i in range(len(legBones)):
        legBones[i] = side + '_' + legBones[i] + '_jnt'
#START setup foot roll
    legIk = cmds.ikHandle(sol='ikRPsolver',
                          sticky='sticky',
                          startJoint=legBones[0],
                          endEffector=legBones[2],
                          name=side + '_leg_ikHandle')
    footIk = cmds.ikHandle(sol='ikSCsolver',
                           sticky='sticky',
                           startJoint=legBones[2],
                           endEffector=legBones[3],
                           name=side + '_foot_ikHandle')
    toeIk = cmds.ikHandle(sol='ikSCsolver',
                          sticky='sticky',
                          startJoint=legBones[3],
                          endEffector=legBones[4],
                          name=side + '_toe_ikHandle')
    #create the groups that will controll the foot animations ( roll, bend, etc etc)
    footGrp = bdCreateGroup([legIk[0], footIk[0], toeIk[0]],
                            side + '_foot_grp', legBones[2])
    ballGrp = bdCreateGroup([legIk[0]], side + '_ball_grp', legBones[3])
    toeGrp = bdCreateGroup([ballGrp, footIk[0], toeIk[0]], side + '_toe_grp',
                           legBones[4])
    heelGrp = bdCreateGroup([toeGrp], side + '_heel_grp', legBones[2])
    #add atributes on the footGrp - will be conected later to an anim controler
    attrList = ['Heel_R', 'Ball_R', 'Toe_R', 'kneeTwist']
    bdAddAttribute(footGrp, attrList)
    #connect the attributes
    cmds.connectAttr(footGrp + '.' + attrList[0], heelGrp + '.rx')
    cmds.connectAttr(footGrp + '.' + attrList[1], ballGrp + '.rx')
    cmds.connectAttr(footGrp + '.' + attrList[2], toeGrp + '.rx')
    #setup the controller
    bdRigLegCtrl(side)
    #END setup foot roll

    #START no flip knee knee
    poleVectorLoc = cmds.spaceLocator()
    poleVectorLoc = cmds.rename(poleVectorLoc, side + 'poleVector')
    poleVectorLocGrp = cmds.group(poleVectorLoc, n=poleVectorLoc + '_GRP')

    thighPos = cmds.xform(legBones[0], q=True, ws=True, t=True)
    cmds.move(thighPos[0] + 5, thighPos[1], thighPos[2], poleVectorLocGrp)

    cmds.poleVectorConstraint(poleVectorLoc, legIk[0])

    shadingNodeADL = cmds.shadingNode('addDoubleLinear',
                                      asUtility=True,
                                      name=side + 'adl_twist')
    cmds.setAttr(shadingNodeADL + '.input2', 90)

    cmds.connectAttr(footGrp + '.' + attrList[3], shadingNodeADL + '.input1')
    cmds.connectAttr(shadingNodeADL + '.output', legIk[0] + '.twist')
Ejemplo n.º 23
0
	def rig_leg(self):
		cmds.select(d=True)
		#Create IK Joints
		self.rig_info['IKjoints'] = utils.createJoint(self.module_info['IKjoints'], self.rig_info['position'], self.instance)
		
		#Create FK Joints
		self.rig_info['FKjoints'] = utils.createJoint(self.module_info['FKjoints'], self.rig_info['position'], self.instance)
		
		#Create RIG Joints
		self.rig_info['RIGjoints'] = utils.createJoint(self.module_info['RIGjoints'], self.rig_info['position'], self.instance)

		#Create IK Rig
		#IK Handle
		#IKcontrols': ["s_legPV_CTRL", "s_leg_ikHandle", "s_legIK_CTRL"]
		ikHandleName = self.module_info['IKcontrols'][1].replace('s_', self.instance)
		self.rig_info['IKhandle'] = cmds.ikHandle(n=ikHandleName, sj=self.rig_info['IKjoints'][0], ee=self.rig_info['IKjoints'][2], p=2, w=1 )

		IKcontrolName = self.module_info['IKcontrols'][0].replace('s_', self.instance)
		self.rig_info['IKcontrol'] = utils.createControl([[self.rig_info['position'][2], IKcontrolName]])[0]

		PVpos = utils.calculatePVposition([self.rig_info['IKjoints'][0], self.rig_info['IKjoints'][1], self.rig_info['IKjoints'][2]])

		self.rig_info['PVctrlInfo'] = utils.createControl([[PVpos, self.module_info['IKcontrols'][0]]])[0]

		# Make a control for leg settings
		self.rig_info['setcontrol']=utils.createControl([[self.rig_info['position'][2], 'ctrl_settings']])[0]
		cmds.addAttr(self.rig_info['setcontrol'][1], ln='IK_FK', at="enum", en="FK:IK:", k=True )

		#parent ikHandle to ctrl
		cmds.parent(self.rig_info['IKhandle'][0], self.rig_info['IKcontrol'][1])

		#PV constraint
		cmds.poleVectorConstraint(self.rig_info['PVctrlInfo'][1], self.rig_info['IKhandle'][0])

		#orient constraint leg ik_endLeg to endLeg_ctrl
		cmds.orientConstraint(self.rig_info['IKcontrol'][1], self.rig_info['IKjoints'][2], mo=True)

		#Create FK rig
		self.rig_info['FKcontrols'] = utils.createControl([[self.rig_info['position'][0], self.module_info['FKcontrols'][0]],
		[self.rig_info['position'][1], self.module_info['FKcontrols'][1]],
		[self.rig_info['position'][2], self.module_info['FKcontrols'][2]]])

		#Parent FK controls
		cmds.parent(self.rig_info['FKcontrols'][2][0], self.rig_info['FKcontrols'][1][1])
		cmds.parent(self.rig_info['FKcontrols'][1][0], self.rig_info['FKcontrols'][0][1])


		# Connect Ik and Fk to Rig joints
		switchattr = self.rig_info['setcontrol'][0] + ".IK_FK"
		utils.connectThroughBC(self.rig_info['IKjoints'], self.rig_info['FKjoints'], self.rig_info['RIGjoints'], self.instance, switchattr )


		# Constrain fk joints to controls.
		[cmds.parentConstraint(self.rig_info['FKcontrols'][i][1], self.rig_info['FKjoints'][i]) for i in range(len(self.rig_info['FKcontrols']))]
Ejemplo n.º 24
0
def buildIKLimb(ik_joints, ik_ctrl, pv_ctrl, constrain_last_jnt=True):
    'create ik handle and connect to ik controllers'

    ik_handlename = ik_joints[0] + "h"
    ik_handle = mc.ikHandle(sj=ik_joints[0],
                            ee=ik_joints[2],
                            name=ik_handlename)[0]
    mc.poleVectorConstraint(pv_ctrl, ik_handle)
    if constrain_last_jnt:
        mc.pointConstraint(ik_ctrl, ik_handle, mo=True)
        mc.orientConstraint(ik_ctrl, ik_joints[2], mo=True)
Ejemplo n.º 25
0
 def setup_ik(self):
     # Create ik handle and constraints
     armIK_ctl = self.side + "armIK_ctl"
     arm_ik_hdl = cmds.ikHandle(
         sj = self.ik_jnts[0], ee = self.ik_jnts[2], sol = "ikRPsolver", \
         n = self.ik_jnts[0].replace("jnt", "hdl"))
     cmds.poleVectorConstraint(self.side + "armPV_ctl", arm_ik_hdl[0])
     cmds.parentConstraint(armIK_ctl, arm_ik_hdl[0], mo=1)
     # May need to change parent constraint on group
     cmds.parent(arm_ik_hdl[0], self.rig_grp)
     cmds.orientConstraint(armIK_ctl, self.ik_jnts[2], mo=0)
Ejemplo n.º 26
0
def ikSolver(rootJoint, endJoint, type, pvControl, handControl, parent):
    ikHandle = mc.ikHandle(n=rootJoint.replace(nameLib.prefixNames.ikSuffix, "") + "_ikHandle", sj=rootJoint, ee=endJoint , sol="ikRPsolver")[0]

    # hide solver
    mc.setAttr(ikHandle + ".v", 0)

    # add pc control to ikHandle
    mc.poleVectorConstraint(pvControl, ikHandle)

    # parent under hand control
    mc.parent(ikHandle, handControl)
Ejemplo n.º 27
0
    def _createIK(self):
        '''
         create the leg IK 
        '''
        self._ik_jnts = self.createJointsFromGuide(append="_ik")

        self._ik_ctl = controllers.BoxControl("%s_ctl_foot_0" % self._side)
        self._ik_ctl.set_position(sc=[1.5, 1, 4], obj=self._ik_jnts[3])
        self._ik_ctl.set_pivot(obj=self._ik_jnts[2])
        self._ik_ctl.set_colour(self._colour)
        self._ik_ctl.hide_scale()

        # create the IK solvers
        ik_data = cmds.ikHandle(n="%s_legIKHandle" % self._side,
                                startJoint=self._ik_jnts[0],
                                endEffector=self._ik_jnts[2],
                                solver="ikRPsolver",
                                sticky="sticky")

        self._ik_handle_foot = ik_data[0]
        self._ik_effector_foot = ik_data[1]

        ik_data = cmds.ikHandle(n="%s_ballIKHandle" % self._side,
                                startJoint=self._ik_jnts[2],
                                endEffector=self._ik_jnts[3],
                                solver="ikSCsolver")

        self._ik_handle_ball = ik_data[0]
        self._ik_effector_ball = ik_data[1]

        ik_data = cmds.ikHandle(n="%s_toeIKHandle" % self._side,
                                startJoint=self._ik_jnts[3],
                                endEffector=self._ik_jnts[4],
                                solver="ikSCsolver")

        self._ik_handle_toe = ik_data[0]
        self._ik_effector_toe = ik_data[1]

        # create the pole vector constraint
        self._knee_ctl = controllers.LocatorControl("%s_ctl_kneePV_0" %
                                                    self._side)
        toe_pos = cmds.xform(self._ik_jnts[4], q=True, ws=True, t=True)
        knee_pos = cmds.xform(self._ik_jnts[1], q=True, ws=True, t=True)
        pos = [knee_pos[0], knee_pos[1], toe_pos[2]]
        self._knee_ctl.set_position(trans=pos)
        self._knee_ctl.set_colour(self._colour)
        self._knee_ctl.hide_scale()
        self._knee_ctl.hide_rotation()
        cmds.poleVectorConstraint(self._knee_ctl.name, self._ik_handle_foot)

        self.inputIK = self._ik_jnts[0]

        self._createReverseFoot()
 def create_poleVector(self):
     pv_name = "{0}_{1}".format("leg_PV", self.SIDE)
     scale = self.FOOT_WIDTH * 0.4
     
     coords = cmds.xform( self.knee_bone, query=True, translation=True, worldSpace=True )
     ctrl = cmds.circle(name=pv_name, normal=(0,0,1), degree=1, sections=3)
     self.knee_polevector = ctrl[0]
     print coords
     cmds.setAttr("{0}.translate".format(ctrl[0]), coords[0], coords[1], coords[2]+12)
     cmds.setAttr("{0}.scale".format(ctrl[0]), scale, scale, scale)
     cmds.makeIdentity(self.knee_polevector, apply=True )
     cmds.poleVectorConstraint( self.knee_polevector, self.leg_ik )
 def lIkSetup(self):
     cmds.ikHandle(n='L_arm_Ikh', sj='L_Ik_shoulder', ee='L_Ik_wrist', sol='ikRPsolver', p=2, w=1)
     # find the worldspace ws translate position of the wrist
     posTransIk = cmds.xform('L_Ik_wrist', q=True, t=True, ws=True)
     # find the worldspace ws orientation position of the wrist
     posOrientIk = cmds.xform('L_Ik_wrist', q=True, ro=True, ws=True)
     # create the empty group
     cmds.group(em=True, n='L_Ik_arm_Grp')
     # create the control
     cmds.circle(n='L_Ik_arm_Ctl', nr=(0, 0, 1), c=(0, 0, 0), r=0.35)
     # orient the group to the wrist
     cmds.xform('L_Ik_arm_Grp', ro=posOrientIk, ws=True)
     # parent the control to the group
     cmds.parent('L_Ik_arm_Ctl', 'L_Ik_arm_Grp')
     # move the group to the wrist
     cmds.xform('L_Ik_arm_Grp', t=posTransIk, ws=True)
     # parent the Ikhandle to the controller
     cmds.parent('L_arm_Ikh', 'L_Ik_arm_Ctl')
     # getting controller to control the orient of the wrist
     cmds.orientConstraint('L_Ik_arm_Ctl', 'L_Ik_wrist', mo=True)
     # create a locator as a poleVector
     cmds.spaceLocator(n='L_poleVec_Loc')
     # create a group as the group for a poleVector
     cmds.group(em=True, n='L_poleVec_Grp')
     # parent locator to the group
     cmds.parent('L_poleVec_Loc', 'L_poleVec_Grp')
     # place the group between the shoulder and the wrist
     cmds.pointConstraint('L_Ik_shoulder', 'L_Ik_wrist', 'L_poleVec_Grp')
     # aim the locator twoards the elbow
     cmds.aimConstraint('L_Ik_elbow', 'L_poleVec_Grp', aim=(1, 0, 0), u=(0, 1, 0))
     # delete the constraints
     cmds.delete('L_poleVec_Grp_pointConstraint1')
     cmds.delete('L_poleVec_Grp_aimConstraint1')
     # place the locater out from the elbow using the X axis trans
     cmds.move(-5, 'L_poleVec_Loc', z=True, a=True)
     # create controller for the polevector
     cmds.circle(n='L_Ik_elbow_Ctl', nr=(0, 0, 1), c=(0, 0, 0), r=0.5)
     # rotate the controller
     cmds.rotate(0, '90deg', 0, 'L_Ik_elbow_Ctl')
     # move parent the controller to the locator locatieon
     cmds.pointConstraint('L_poleVec_Loc', 'L_Ik_elbow_Ctl')
     # delete pointConstraint from controller
     cmds.delete('L_Ik_elbow_Ctl_pointConstraint1')
     # parent controller to grp
     cmds.parent('L_Ik_elbow_Ctl', 'L_poleVec_Grp')
     # freeze orientation on controller
     cmds.makeIdentity('L_Ik_elbow_Ctl', a=True)
     # parent poleVEc to controller
     cmds.parent('L_poleVec_Loc', 'L_Ik_elbow_Ctl')
     # connect the polevector constraint to the ikhandle and the locator
     cmds.poleVectorConstraint('L_poleVec_Loc', 'L_arm_Ikh')
     # hide locator
     cmds.hide('L_poleVec_Loc')
Ejemplo n.º 30
0
def create_ik_setup(controls, joints):
    """Creates an IK rig setup.

    Args:
        controls (list): control objects.
        joints (list): ik joint objects.

    Returns:
        str: ikHandle name
    """

    root_control, pole_control, goal_control = controls

    handle, effector = cmds.ikHandle(sj=joints[0],
                                     ee=joints[-1],
                                     sol='ikRPsolver')
    cmds.setAttr('{}.hiddenInOutliner'.format(handle), True)
    cmds.orientConstraint(goal_control, joints[-1], mo=True)
    cmds.parent(handle, goal_control)

    # connect root control to ik joint offset group
    ik_joints_offset = cmds.listRelatives(joints[0], p=True)[0]
    cmds.parentConstraint(root_control, ik_joints_offset, mo=True)
    cmds.scaleConstraint(root_control, ik_joints_offset, mo=True)

    # connect twisting and pole vector control
    cmds.addAttr(goal_control, ln='twist', at='float', k=True)
    cmds.connectAttr('{}.twist'.format(goal_control),
                     '{}.twist'.format(handle))

    cmds.poleVectorConstraint(pole_control, handle)

    # add curve that points elbow to pole control
    crv = cmds.curve(p=[[0, 0, 0], [0, 1, 0]], d=1)
    cmds.connectAttr('{}.visibility'.format(pole_control),
                     '{}.visibility'.format(crv))
    lock_hide_attrs(
        crv, attrs=['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
    cmds.setAttr('{}.overrideEnabled'.format(crv), True)
    cmds.setAttr('{}.overrideDisplayType'.format(crv), 2)
    decomp_joint = cmds.createNode('decomposeMatrix')
    decomp_control = cmds.createNode('decomposeMatrix')
    cmds.connectAttr('{}.worldMatrix'.format(joints[1]),
                     '{}.inputMatrix'.format(decomp_joint))
    cmds.connectAttr('{}.worldMatrix'.format(pole_control),
                     '{}.inputMatrix'.format(decomp_control))
    cmds.connectAttr('{}.outputTranslate'.format(decomp_joint),
                     '{}.controlPoints[0]'.format(crv))
    cmds.connectAttr('{}.outputTranslate'.format(decomp_control),
                     '{}.controlPoints[1]'.format(crv))

    return handle, crv
Ejemplo n.º 31
0
def move_locator(locatorName, addPosition, effectorName):
    sel = cmds.ls(locatorName)

    # ピボットポイントをオブジェクトのバウンディングボックスの中心に設定
    cmds.xform(locatorName, cp=True)
    locator = cmds.spaceLocator(n="Dummy_Locator")
    cmds.move(addPosition[0], addPosition[1], addPosition[2], ws=True)
    cmds.delete("Dummy_Locator")

    # 極ベクトル
    cmds.poleVectorConstraint(locatorName, effectorName)

    cmds.select(locatorName, deselect=True)
Ejemplo n.º 32
0
def createIk(ikJnts):
	ikInfo = []
	ikhName = ikJnts[2].replace('ikj', 'ikh')
	ikh = cmds.ikHandle(n=ikhName, sj=ikJnts[0], ee=ikJnts[2], sol='ikRPsolver', p=2, w=.5 )
	# Make a poleVector
	pvCon = cmds.spaceLocator(n=ikhName+'_pv')
	tmpCon = cmds.parentConstraint(ikJnts[1], pvCon, mo=False)
	cmds.delete(tmpCon) 
	cmds.move(-1, pvCon, r=True, z=True )
	cmds.makeIdentity(pvCon, apply=True )
	# Creat a pv constraint
	cmds.poleVectorConstraint( pvCon, ikh[0] )
	return ikh
Ejemplo n.º 33
0
def move_locator(locatorName, addPosition, effectorName):
    sel = cmds.ls(locatorName)

    #ピボットポイントをオブジェクトのバウンディングボックスの中心に設定
    cmds.xform(locatorName, cp=True)
    locator = cmds.spaceLocator(n='Dummy_Locator')
    cmds.move(addPosition[0], addPosition[1], addPosition[2], ws=True)
    cmds.delete('Dummy_Locator')

    #極ベクトル
    cmds.poleVectorConstraint(locatorName, effectorName)

    cmds.select(locatorName, deselect=True)
Ejemplo n.º 34
0
def createIK(name, joints, controls):
    firstJoint = joints[0]
    lastJoint = joints[-1]
    cmds.ikHandle(sj=firstJoint,
                  ee=lastJoint,
                  sol='ikRPsolver',
                  n=name + '_ik')
    poleAxis = 'X'

    #create pole control
    cmds.spaceLocator(n=name + '_cc_loc')
    cmds.pointConstraint(joints[1], name + '_cc_loc')
    cmds.pointConstraint(joints[1], name + '_cc_loc', rm=True)
    if poleAxis == 'X':
        cmds.move(10, 0, 0, name + '_cc_loc', r=True)
    if poleAxis == 'Y':
        cmds.move(0, 10, 0, name + '_cc_loc', r=True)
    if poleAxis == 'Z':
        cmds.move(0, 0, 10, name + '_cc_loc', r=True)
        print 'pole is in Z'
    if poleAxis == 'Y':
        #set preferred angle
        cmds.rotate('90deg', 0, 0, joints[1])
        cmds.joint(joints[1], e=True, spa=True)
        cmds.rotate(0, 0, 0, joints[1])
    if poleAxis == 'Z':
        #set preferred angle
        cmds.rotate(90, 0, 0, joints[1])
        cmds.joint(joints[1], e=True, spa=True)
        cmds.rotate(0, 0, 0, joints[1])
    if poleAxis == 'X':
        #set preferred angle
        cmds.rotate(0, 0, '90deg', joints[1])
        cmds.joint(joints[1], e=True, spa=True)
        cmds.rotate(0, 0, 0, joints[1])
    if controls == None:
        ctrl_name = name + '_ik_cc'
        cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), r=(4) * 2, n=ctrl_name)
        cmds.parentConstraint(lastJoint, ctrl_name)
        cmds.parentConstraint(lastJoint, ctrl_name, rm=True)
        cmds.parentConstraint(ctrl_name, name + '_ik')

    else:
        cmds.parentConstraint(controls, name + '_ik', w=1, mo=True)

    cmds.makeIdentity(name + '_cc_loc',
                      apply=True,
                      translate=True,
                      rotate=True,
                      scale=True)
    cmds.poleVectorConstraint(name + '_cc_loc', name + '_ik', w=1)
Ejemplo n.º 35
0
 def add_poleVector_constraint_control(self, **p):
     ctrl_obj = self.cn + '_ctrl_' + p['control']
     ik_handle = self.cn + '_' + p['ik_handle']
     align_joint = self.cn + '_' + p['align_joint']
     self.pvt_align_control(align_joint,
                            ctrl_obj,
                            p['parent'],
                            offset=(0, 0, 40))
     n = ctrl_obj + '_poleVecConstraint'
     cmds.poleVectorConstraint(ctrl_obj, ik_handle, n=n)
     cmds.parent(n, self.CONTROLS_EXTRAS_GROUP)
     cmds.setAttr(ctrl_obj + '.ty', lock=True)
     cmds.setAttr(ctrl_obj + '.tz', lock=True)
     lock_rotate_and_scale(ctrl_obj)
Ejemplo n.º 36
0
def twoJointPV(name, ik, distance=1, constrain=True, size=1):
    sj = cmds.ikHandle(ik, q=True, sj=True)
    Gp = null2(name + '_PvGrp', sj, False)[0]
    Pv = circle(name + '_PV', sj, 'diamond_ctrl', size * 1, 17, 8, 1, (0, 0, 1))[0]
    cmds.parent(Pv, Gp)
    X = cmds.getAttr(ik + '.poleVectorX')
    Y = cmds.getAttr(ik + '.poleVectorY')
    Z = cmds.getAttr(ik + '.poleVectorZ')
    cmds.setAttr(Pv + '.translateX', distance * X)
    cmds.setAttr(Pv + '.translateY', distance * Y)
    cmds.setAttr(Pv + '.translateZ', distance * Z)
    if constrain == True:
        cmds.poleVectorConstraint(Pv, ik)
    return Gp, Pv
Ejemplo n.º 37
0
def create_pole_vector(pv_ctl, ik_handle):
    """Positions pv_ctl and creates pole vector constraint for ik_handle to prevent any joint rotation

    Arguments:
        pv_ctl:    Transform to use as pole vector control

        ik_handle: IK handle to add pole vector constrain to

    Example:
        create_pole_vector( 'locator2', 'ikHandle1' )
    """
    # Find the start joint from querying ik handle
    start_joint = cmds.ikHandle(ik_handle, q=True, startJoint=True)
    mid_joint = cmds.listRelatives(start_joint, children=True, type='joint')
    end_eff = cmds.ikHandle(ik_handle, q=True, endEffector=True)

    # Constrain the pole vector control transform between start joint and ik_handle
    cmds.delete(cmds.pointConstraint(start_joint, ik_handle, pv_ctl))

    # Aim pole vector control to mid_joint - Aim X-axis
    cmds.delete(
        cmds.aimConstraint(mid_joint[0],
                           pv_ctl,
                           aim=[1, 0, 0],
                           u=[0, 0, 1],
                           wut='object',
                           wuo=end_eff))

    # Find distance from pole vector control to mid_joint
    pv_pos = cmds.xform(pv_ctl, q=True, ws=True, t=True)
    mid_pos = cmds.xform(mid_joint[0], q=True, ws=True, t=True)
    pv_dist = (pv_pos[0] - mid_pos[0], pv_pos[1] - mid_pos[1],
               pv_pos[2] - mid_pos[2])

    # Add offset away from mid position
    # - Moves pole vector to mid position PLUS original distance from initial position to mid position
    pv_pos_off = (mid_pos[0] - pv_dist[0], mid_pos[1] - pv_dist[1],
                  mid_pos[2] - pv_dist[2])
    cmds.xform(pv_ctl, t=pv_pos_off)

    # Add group node above pole vector control to zero it out
    pv_grp = cmds.duplicate(pv_ctl, po=True, name='{}_grp'.format(pv_ctl))[0]
    cmds.parent(pv_ctl, pv_grp)

    # Create pole vector constraint
    cmds.poleVectorConstraint(pv_ctl, ik_handle)

    return pv_pos_off
Ejemplo n.º 38
0
def AutoClav(jnt_clav='jnt_shoulder_l'):
    jnt_arm = mc.listRelatives(jnt_clav, c=1, typ='joint')[0]
    if mc.parentConstraint(jnt_clav, q=1):
        ctrl_clav = mc.parentConstraint(jnt_clav, q=1, tl=1)[0]
    else:
        ctrl_clav = fkThis([jnt_clav])[0]
    mc.group(ctrl_clav,
             p=mc.listRelatives(ctrl_clav, p=1)[0],
             n=ctrl_clav + '_autoclav')
    ikh = mc.ikHandle(n=jnt_clav.replace('jnt', 'ikh'),
                      sj=jnt_clav,
                      ee=jnt_arm)[0]
    print ikh
    offikh = offsetgrp([ikh])
    print offikh
    if mc.parentConstraint(jnt_arm, q=1):
        ctrl_arm = mc.parentConstraint(jnt_arm, q=1, tl=1)[0]
    else:
        ctrl_arm = fkThis([jnt_arm])[0]
    ctrl_arm_offset = mc.listRelatives(ctrl_arm, p=1)[0]
    mc.delete(mc.parentConstraint(ctrl_arm_offset, q=1))
    mc.parentConstraint(ctrl_clav, ctrl_arm_offset, mo=1)
    mc.parentConstraint(ctrl_arm, offikh, mo=1)
    pole = mc.spaceLocator(n=jnt_clav.replace('jnt', 'pole'))[0]
    print pole
    polecste = mc.parentConstraint(ctrl_clav, pole, mo=0)[0]
    print polecste
    poloffset = mc.getAttr(jnt_arm + '.tx')
    mc.setAttr(polecste + '.target[0].targetOffsetTranslateX',
               (poloffset) * -.5)
    mc.setAttr(polecste + '.target[0].targetOffsetTranslateY',
               (poloffset) * -2)
    mc.poleVectorConstraint(pole, ikh)
    dim = mc.createNode('distanceDimShape',
                        n=jnt_clav.replace('jnt', 'dist'),
                        p=ikh)
    pos_clav = mc.createNode('locator',
                             n=jnt_clav.replace('jnt', 'pos'),
                             p=jnt_clav)
    pos_arm = mc.createNode('locator', n=jnt_arm.replace('jnt', 'pos'), p=ikh)
    mc.connectAttr(pos_clav + '.worldPosition[0]', dim + '.startPoint')
    mc.connectAttr(pos_arm + '.worldPosition[0]', dim + '.endPoint')

    mc.disconnectAttr(
        mc.listConnections(jnt_arm + '.ty', p=1)[-1], jnt_arm + '.ty')
    mc.disconnectAttr(
        mc.listConnections(jnt_arm + '.tz', p=1)[-1], jnt_arm + '.tz')
    mc.connectAttr(dim + '.distance', jnt_arm + '.tx', f=1)
Ejemplo n.º 39
0
    def setupPoleVec(self):
        middleName = rg.stripMiddle(self.m_joints.m_shoulder, 0, 3)
        desiredName = self.m_name+"PoleVec_LOC"
        self.m_poleVec = cmds.spaceLocator(n = desiredName)[0]
        # Add to controls
        rc.addToControlDict(self.m_allControls, "%s_IKPoleVec" %(self.m_baseName), self.m_poleVec)
        rc.addToLayer(self.m_sceneData, "mainCtrl", self.m_poleVec)
        cmds.addAttr(
            self.m_poleVec, 
            ln=self.m_poleVecPinAttr, 
            min=0, 
            max=1, 
            k=True, 
            dv=0
            )
        cmds.addAttr(
            self.m_poleVec, 
            ln=self.m_maxStretchAttr, 
            at = "float", 
            min=0, 
            dv=10, 
            k=1
            )
        self.m_maxStretch = "%s.%s" %(self.m_poleVec, self.m_maxStretchAttr)
        rc.orientControl(self.m_poleVec, self.m_joints.m_elbow1)
        groups = rg.add3Groups(self.m_poleVec, ["_SDK", "_CONST", "_0"])
        cmds.poleVectorConstraint(self.m_poleVec, self.m_ikHandle)
        cmds.parent(groups[-1], self.m_group, r=1)
        # Lock unused attributes
        rc.lockAttrs(
            self.m_poleVec,
            ["scale", "rotate"],
            True,
            False
            )


        axis , offset = self.getPoleVecAxis(2)
        if axis != "":
            cmds.setAttr("%s.t%s" %(groups[1], axis), offset) 

        #Create line
        midGroup = cmds.group(em=1, n=self.m_name+"PoleVec_GRP")
        cmds.parent(midGroup, self.m_group)
        cmds.pointConstraint(self.m_joints.m_elbow1, midGroup)
        cmds.pointConstraint(self.m_joints.m_elbow2, midGroup)
        lineNodes = rc.createLine([self.m_poleVec, midGroup], self.m_sceneData, "mainCtrl")
        cmds.parent(lineNodes[0], self.m_group)
Ejemplo n.º 40
0
def targetAliasList(constraint):
	'''
	Return a list of targets (drivers) attribute aliases for the specified constraint node
	@param constraint: The constraint node whose targets will be returned
	@type constraint: str
	'''
	# Check Constraint
	if not isConstraint(constraint):
		raise Exception('Constraint "'+constraint+'" does not exist!!')
	
	# Get Target List
	targetList = []
	constraintType = mc.objectType(constraint)
	if constraintType == 'aimConstraint': targetList = mc.aimConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'geometryConstraint': targetList = mc.geometryConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'normalConstraint': targetList = mc.normalConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'orientConstraint': targetList = mc.orientConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'parentConstraint': targetList = mc.parentConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'pointConstraint': targetList = mc.pointConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'poleVectorConstraint': targetList = mc.poleVectorConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'scaleConstraint': targetList = mc.scaleConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'tangentConstraint': targetList = mc.tangentConstraint(constraint,q=True,weightAliasList=True)
	
	# Check Target List
	if not targetList: targetList = []
	
	# Return Result
	return targetList
Ejemplo n.º 41
0
    def setupPV(self, IKHandle, type, x):
        """type can be "normal" (a control) or "noFlip" with hidden control and twist attribute. add to self.PVList """
        # set values for this chain, side
        thisChain = self.IKChains[x]
        side = self.prefixList[x]

        pv = "%s_%s_PV" % (side, self.limbName)

        if type == "normal":
            if x == 0:
                thisPV = rig.createControl(pv, "sphere", self.jAxis1, "darkBlue")
            if x == 1:
                thisPV = rig.createControl(pv, "sphere", self.jAxis1, "darkRed")
            thisGrp = cmds.group(pv, n="%s_%s" % (pv, self.groupSuffix))

            # get pos of joints 0 and 2 to position pv group
            topPosRaw = cmds.xform(thisChain[0], ws=True, q=True, t=True)
            topPos = om.MVector(topPosRaw[0], topPosRaw[1], topPosRaw[2])
            lowPosRaw = cmds.xform(thisChain[2], ws=True, q=True, t=True)
            lowPos = om.MVector(lowPosRaw[0], lowPosRaw[1], lowPosRaw[2])

            midPos = (topPos + lowPos) / 2

            cmds.xform(thisGrp, ws=True, t=(midPos.x, midPos.y, midPos.z))

            aim = cmds.aimConstraint(thisChain[1], thisGrp, aim=(0, 0, -1))
            cmds.delete(aim)

            cmds.xform(thisGrp, os=True, r=True, t=(0, 0, -10))

            # strip control to translate
            rig.stripToTranslate(thisPV)

            # -----------capture all constraints as list?
            # hook up pv
            cmds.poleVectorConstraint(thisPV, IKHandle)

            # add pv to list
            self.PVList.append(thisPV)

            # return pv
            return thisPV
        cmds.addAttr(thisPV, ln="follow", at="enum", en="world:foot")

        if type == "noFlip":
            pass
        pass
Ejemplo n.º 42
0
 def create_ik_setup(self):
     """Creates the IK setup."""
     ik_leg = cmds.ikHandle(sj=self.ik_jnts[0], ee=self.ik_jnts[2], sol='ikRPsolver')
     cmds.rename(ik_leg[1], '%s_%s_%s' % (self.side, 'leg', self.nc.effector))
     ik_leg = cmds.rename(ik_leg[0], '%s_%s_%s' % (self.side, 'leg', self.nc.ikhandle))
     ik_foot = cmds.ikHandle(sj=self.ik_jnts[2], ee=self.ik_jnts[3])
     cmds.rename(ik_foot[1], '%s_%s_%s' % (self.side, 'foot', self.nc.effector))
     ik_foot = cmds.rename(ik_foot[0], '%s_%s_%s' % (self.side, 'foot', self.nc.ikhandle))
     ik_ball = cmds.ikHandle(sj=self.ik_jnts[3], ee=self.ik_jnts[4])
     cmds.rename(ik_ball[1], '%s_%s_%s' % (self.side, 'ball', self.nc.effector))
     ik_ball = cmds.rename(ik_ball[0], '%s_%s_%s' % (self.side, 'ball', self.nc.ikhandle))
     cmds.parent(ik_leg, ik_foot, self.controls['ik'])
     self.create_ik_stretch()
     cmds.poleVectorConstraint(self.controls['knee'], ik_leg, weight=1)
     self.create_knee_pin()
     self._reverse_foot([ik_leg, ik_foot, ik_ball])
     self._foot_attributes([ik_leg, ik_foot, ik_ball])
Ejemplo n.º 43
0
def bdRigIkArm(side):
    ikChainStart = bdBuildDrvChain(side,'ik')
    ikChainJoints = cmds.listRelatives(ikChainStart, ad=True,type='joint')
    ikChainJoints.reverse()
    ikBones = ikChainStart + ikChainJoints
    print ikBones
    armIk = cmds.ikHandle(sol= 'ikRPsolver',sticky='sticky', startJoint=ikBones[0],endEffector = ikBones[2],name = side + '_arm_ikHandle')
    handIk = cmds.ikHandle(sol= 'ikSCsolver',sticky='sticky', startJoint=ikBones[2],endEffector = ikBones[3],name = side + '_hand_ikHandle')
    ikHandlesGrp = cmds.group([armIk[0],handIk[0]],n=side + '_arm_ikHandles_grp')
    wristPos = cmds.xform(ikBones[2],q=True,ws=True,t=True)
    cmds.move(wristPos[0], wristPos[1], wristPos[2], [ikHandlesGrp + '.scalePivot',ikHandlesGrp + '.rotatePivot'])
    pvAnim = cmds.ls(side + '_elbow_ik_anim', type='transform')[0]
    if pvAnim:
        cmds.poleVectorConstraint(pvAnim,armIk[0])
    
    ikAnimCtrl = cmds.ls(side + '_hand_ik_anim',type='transform')[0] 
    cmds.parentConstraint(ikAnimCtrl, ikHandlesGrp)
Ejemplo n.º 44
0
    def createIkControls(self):
        # Create controls and solvers
        wristControl = self.createWristControl()
        poleVector = self.createPoleVector(distanceScale=5)
        ikHandle = self.createIkHandle()[0]

        # Create and constrain arm ik handle
        cmds.pointConstraint(wristControl, ikHandle)
        cmds.poleVectorConstraint(poleVector, ikHandle)

        # Create null groups
        self.utils.createNullGroup(wristControl)
        self.utils.createNullGroup(poleVector)

        # Lock controller attributes
        self.utils.lockAttrs(wristControl, rotate=True, scale=True, visibility=True)
        self.utils.lockAttrs(poleVector, rotate=True, scale=True, visibility=True)
Ejemplo n.º 45
0
    def createNoFlipKnee(self, iksSolver, hip, footControl, *args):
        """ Create a locator """

        """ Create a locator to use for the PoleVector"""
        lctrName = hip.replace("Jnt_", "LctrPV_")
        lctrPos = cmds.xform(hip, q=True, ws=True, t=True)
        pvPoint = cmds.spaceLocator(n=lctrName, p=lctrPos)
        cmds.xform(cp=True)
        cmds.makeIdentity( apply=True )

        """ Parent the locator to the cog """
        cmds.parent(pvPoint, "rig_root") #Temp

        """ Constran ikHandle to PV """
        cmds.poleVectorConstraint(pvPoint[0], iksSolver[0])

        """ Create a twist attribute on the foot control """
        cmds.select(footControl)
        try:
            cmds.addAttr( shortName='twist', longName='twist', defaultValue=0, k=True)
        except:
            print "twist attr may have not been created"
        cmds.select(d=True)

        """ Create an mdiv and a pma node """
        mdivNamePrefix = hip.replace("Jnt_", "mDiv_PV_") 
        mdivNode = cmds.shadingNode("multiplyDivide", asUtility=True, n=mdivNamePrefix)

        pmaNamePrefix = hip.replace("Jnt_", "Pma_PV__") 
        pmaNode = cmds.shadingNode("plusMinusAverage", asUtility=True, n=pmaNamePrefix)

        cmds.connectAttr(footControl[0]+".twist", mdivNode+".input1X")
        cmds.connectAttr(footControl[0]+".ry", mdivNode+".input1Y")
        # Will need to change this with cog
        cmds.connectAttr("jnt_c1_spine1.ry", mdivNode+".input1Z")

        cmds.setAttr(mdivNode+".input2X", -1)
        cmds.setAttr(mdivNode+".input2Y", -1)
        cmds.setAttr(mdivNode+".input2Z", -1)

        cmds.connectAttr(mdivNode+".input1X", pmaNode+".input1D[0]")
        cmds.connectAttr(mdivNode+".input1Y", pmaNode+".input1D[1]")
        cmds.connectAttr(pmaNode+".output1D", iksSolver[0]+".twist")
        #142.4
        cmds.setAttr(footControl[0]+".twist", 90)
Ejemplo n.º 46
0
 def ikArmSetup(self):
     """
     #- ik arm setup
     """
     
     cmds.select(cl = True)
     for lr in self.lrPrefix:
         cmds.select('%sshoulder_jnt' %lr, r = True)
         cmds.duplicate(rr = True, n = '%sik_shoulder_jnt' %lr)          
         armChild = cmds.listRelatives('%sik_shoulder_jnt' %lr, ad = True, f = True)
         
         cmds.rename(armChild[0], '%sik_wrist_jnt' %lr )
         cmds.rename(armChild[1], '%sik_elbow_jnt' %lr ) 
         
         if lr == self.left:
                 ctlColor = 6
         else:
                 ctlColor = 12
         controller.boxController('%sarm_ik_ctl' %lr, ctlColor, ['sc', 'vi'])
         controller.arrowController('%sarm_polevector_ctl' %lr, ctlColor, ['ro', 'sc', 'vi'])
 
         cmds.select('%sik_wrist_jnt' %lr, r = True)
         cmds.select('%sarm_ik_ctl_grp' %lr, tgl = True)
         cmds.pointConstraint(mo = False, weight = 1)
         cmds.orientConstraint(mo = False, weight = 1)
         cmds.delete('%sarm_ik_ctl_grp_pointConstraint1' %lr)
         cmds.delete('%sarm_ik_ctl_grp_orientConstraint1' %lr)
         
         cmds.select('%sarm_ik_ctl' %lr, r = True)
         cmds.select('%sik_wrist_jnt' %lr, tgl = True)
         cmds.orientConstraint(mo = False, weight = 1)
         
         cmds.select('%sik_shoulder_jnt.rotatePivot' %lr, r = True)
         cmds.select('%sik_wrist_jnt.rotatePivot' %lr, add = True)
         cmds.ikHandle(n = '%sarm_ikHandle' %lr, sol = 'ikRPsolver')             
         
         self.util.parent('%sarm_ikHandle' %lr, '%sarm_ik_ctl' %lr)
         
         polVecPos = poleVector.getPolVectorPos('%sik_shoulder_jnt' %lr, '%sik_elbow_jnt' %lr, '%sik_wrist_jnt' %lr, 1)
         cmds.select('%sarm_polevector_ctl_grp' %lr, r = True)
         cmds.move(polVecPos[0], polVecPos[1], polVecPos[2])
         
         cmds.select('%sarm_polevector_ctl' %lr, r = True)
         cmds.select('%sarm_ikHandle' %lr, tgl = True)
         cmds.poleVectorConstraint(weight = 1)
Ejemplo n.º 47
0
def ikSolver(rootJoint, endJoint, type, controller, parent, pvControl=False):
    solver = "ikRPsolver"
    if type == "sc":
        solver = "ikSCsolver"

    ikHandle = mc.ikHandle(n=rootJoint.replace(nameLib.prefixNames.ikSuffix, "") + "_ikHandle", sj=rootJoint, ee=endJoint , sol=solver)[0]

    # hide solver
    mc.setAttr(ikHandle + ".v", 0)

    # add pc control to ikHandle
    if pvControl:
        mc.poleVectorConstraint(pvControl, ikHandle)

    # parent under hand control
    mc.parent(ikHandle, controller)

    return ikHandle
Ejemplo n.º 48
0
def buildPoleVect(definition, ikSolver, hip, knee, ankle, toeTIP, crvName):
    from maya.OpenMaya import MVector
    name = definition['component'].data['name']
    side = definition['component'].data['side']
    color = definition['color']
    if cmds.objExists(crvName):
        return crvName

    ####################### POLE
    ## query the pole vector attributes before parenting the ik handle BEFORE parenting...
    poleVecArmValue = cmds.getAttr("{}.poleVector".format(ikSolver))
    hip = cmds.xform(hip, q = True, a = True, ws = True, t = True)
    hipVec = MVector(hip[0], hip[1], hip[2])
    knee = cmds.xform(knee, q = True, a = True, ws = True, t = True)
    kneeVec = MVector(knee[0], knee[1], knee[2])
    ankle = cmds.xform(ankle, q = True, a = True, ws = True, t = True)
    ankleVec = MVector(ankle[0], ankle[1], ankle[2])
    toeTIP = cmds.xform(toeTIP, q = True, a = True, ws = True, t = True)
    toeTIPVec = MVector(toeTIP[0], toeTIP[1], toeTIP[2])
    ## Calculated vectors
    vecHipToKneeDifference = (hipVec - kneeVec)
    hipLength = (vecHipToKneeDifference.length() * 0.5)
    vecKneeToAnkleDifference = (kneeVec- ankleVec)
    kneeLength = vecKneeToAnkleDifference.length()
    vecAnkleToToeDifference = (ankleVec - toeTIPVec)
    toeTIPLength = vecAnkleToToeDifference.length()
    ## Make the Pole Vector Handle
    poleCrv = crvB.buildControlCurve(curveName = crvName, curveType = 'sphere', snap = False, snapTo = '', orientation = 'Y', grouped = True, scaleFactor = .2, color = color, suffix = False)
    ## Group the pole vector transform with an orient group
    poleVectorArmGrp = poleCrv[0]
    ## Determine the position of the pole vector control
    pvPlacement = []
    pos0 = (knee[0] + (poleVecArmValue[0][0] * (kneeLength * 0.25)));
    pos1 = (knee[1] + (poleVecArmValue[0][1] * (kneeLength * 0.25)));
    pos2 = (knee[2] + (poleVecArmValue[0][2] * (kneeLength * 0.25)));
    pvPlacement.append(pos0)
    pvPlacement.append(pos1)
    pvPlacement.append(pos2)
    ## Move it into position
    cmds.xform(poleVectorArmGrp, a = True, ws = True, t = pvPlacement)
    ## Apply the pv constraint
    polecst = cmds.poleVectorConstraint(poleCrv[1], ikSolver, weight = 1)
    newPoleCstName = polecst[0][:-1]
    cmds.rename(polecst[0], newPoleCstName)
    createDefaultMetaData(newPoleCstName, name, side, 'poleVectorConstraint')
    ## Add metaData
    ctrls = [poleCrv]
    for eachCtrl in ctrls:
        createDefaultMetaData(eachCtrl[0], name, side, 'ctrlBuffer')
        createDefaultMetaData(eachCtrl[1], name, side, 'ctrl')
        addMessageAttr(eachCtrl[1], 'parent')
        connMessageAttr(eachCtrl[1], 'parent', eachCtrl[0])

        parentTo(eachCtrl[0], definition['component'].data['control'])

    return poleCrv
Ejemplo n.º 49
0
    def create_ik_setup(self):
        """@todo: insert doc for create_ik_setup"""
        # ik arm, hand
        ik_leg = cmds.ikHandle(sj=self.ik_jnts[0], ee=self.ik_jnts[2], sol='ikRPsolver')
        cmds.rename(ik_leg[1], '%s_%s_%s' % (self.side, 'leg', self.nc['effector']))
        ik_leg = cmds.rename(ik_leg[0], '%s_%s_%s' % (self.side, 'leg', self.nc['ikhandle']))

        ik_foot = cmds.ikHandle(sj=self.ik_jnts[2], ee=self.ik_jnts[3])
        cmds.rename(ik_foot[1], '%s_%s_%s' % (self.side, 'foot', self.nc['effector']))
        ik_foot = cmds.rename(ik_foot[0], '%s_%s_%s' % (self.side, 'foot', self.nc['ikhandle']))

        # ik_ball = cmds.ikHandle(sj=self.ik_jnts[2], ee=self.ik_jnts[3])
        # cmds.rename(ik_ball[1], '%s_%s_%s' % (self.side, 'ball', self.nc['effector']))
        # ik_ball = cmds.rename(ik_ball[0], '%s_%s_%s' % (self.side, 'ball', self.nc['ikhandle']))

        cmds.parent(ik_leg, ik_foot, self.controls['ik'])
        self.create_ik_stretch()
        cmds.poleVectorConstraint(self.controls['knee'], ik_leg, weight=1)
        self.create_knee_pin()
Ejemplo n.º 50
0
def createPoleVec(joints, ikHandle, position):
    """
        Creates pole vector for handle for three joints
    """
    if len(joints) != 3:
        cmds.error("Incorrect number of joints supplied to IkHandle.")
    
    # Create locator to act as pole vector
    locName = (String.removeSuffix(ikHandle) + "Pole_LOC")
    poleGrpName = (String.removeSuffix(ikHandle) + "Pole_GRP")
    poleVecName = (String.removeSuffix(ikHandle) + "Pole_PVC")
    
    loc = Lib.getFirst(cmds.spaceLocator(n = locName, p= (0,0,0) ))
    cmds.xform(loc, ws= True, t= (position[0], position[1], position[2]) )
    locGrp = cmds.group(loc, n= poleGrpName)
    cmds.poleVectorConstraint( loc , ikHandle, n= poleVecName, w=.1 )
    cmds.setAttr((loc + ".v"), 0)
    
    return locGrp
Ejemplo n.º 51
0
def stretchyRP_ik(rootJoint, midJoint, endJoint):

    cmds.setAttr(rootJoint + ".preferredAngleY", -50)
    cmds.setAttr(midJoint + ".preferredAngleY", 50)

    rootJointPos = cmds.xform(rootJoint, q = True, ws = True, a = True, translation = True)
    midJointPos = cmds.xform(midJoint, q = True, ws = True, a = True, translation = True)
    endJointPos = cmds.xform(endJoint, q = True, ws = True, a = True, translation = True)

    rootJointLoc = cmds.spaceLocator(name = rootJoint + "_ikStretchLoc")[0]
    midJointLoc = cmds.spaceLocator(name = midJoint + "_ikStretchLoc")[0]
    endJointLoc = cmds.spaceLocator(name = endJoint + "_ikStretchLoc")[0]

    cmds.xform(rootJointLoc, ws = True, a = True, translation = rootJointPos)
    cmds.xform(midJointLoc, ws = True, a = True, translation = midJointPos)
    cmds.xform(endJointLoc, ws = True, a = True, translation = endJointPos)

    ikNodes = cmds.ikHandle(solver = "ikRPsolver", sj = rootJoint, ee = endJoint, name = rootJoint + "_RPikHandle")
    ikHandle = ikNodes[0]
    ikEndEffector = ikNodes[1]

    ##  parent locators to correct parent
    cmds.parent(ikHandle, endJointLoc)
    cmds.parentConstraint(rootJointLoc, rootJoint, maintainOffset = True, name = rootJoint + "_pointConstraint")
    cmds.poleVectorConstraint(midJointLoc, ikHandle, name = midJoint + "_poleVectorConstraint")


    ##  add distance nodes to root2mid and mid2end
    root2mid_distanceNode = cmds.shadingNode("distanceBetween", asUtility = True, n = "root2mid_distanceNode")
    cmds.connectAttr(rootJointLoc + 'Shape.worldPosition[0]', root2mid_distanceNode + '.point1')
    cmds.connectAttr(midJointLoc + 'Shape.worldPosition[0]', root2mid_distanceNode + '.point2')

    mid2end_distanceNode = cmds.shadingNode("distanceBetween", asUtility = True, n = "mid2end_distanceNode")
    cmds.connectAttr(midJointLoc + 'Shape.worldPosition[0]', mid2end_distanceNode + '.point1')
    cmds.connectAttr(endJointLoc + 'Shape.worldPosition[0]', mid2end_distanceNode + '.point2')

    ##  connect distance nodes to joints
    cmds.connectAttr(root2mid_distanceNode + ".distance", midJoint + ".tx", force = True)
    cmds.connectAttr(mid2end_distanceNode + ".distance", endJoint + ".tx", force = True)

    return [rootJointLoc, midJointLoc,endJointLoc]
Ejemplo n.º 52
0
    def add_polevector(self, description=None, offset=[0, 0, 0]):
        """Add pole vector for ikHandle"""

        description = description or name.get_description(name.set_description_suffix(self.ik_ctl.ctl, "pv"))
        
        # Create control
        ctl = Control(self.position, description)
        ctl.create()
        ctl.set_style("pyramid")

        ctl.lock_rotates()
        ctl.lock_scales()

        # TODO
        # Create aim
        # for axis in ["X", "Y", "Z"]:
        #     cmds.setAttr("%s.rotate%s" % (ctl.ctl, axis), k=False, cb=False)

        # Find center of ik handle
        start_pos = cmds.xform(self.ik_joints[0], q=1, t=1, ws=1)
        end_pos = cmds.xform(self.ik_joints[-1], q=1, t=1, ws=1)
        middle_pos = vector.average_3f(start_pos, end_pos)
        middle_pos = vector.add_3f(middle_pos, offset)

         # Find center of ik handle
        start_rot = cmds.xform(self.ik_joints[0], q=1, ro=1, ws=1)
        end_rot = cmds.xform(self.ik_joints[-1], q=1, ro=1, ws=1)
        middle_rot = vector.average_3f(start_rot, end_rot)

        # Move into position
        cmds.xform(ctl.grp, t=middle_pos, ws=True)

        # Create poleVector
        cmds.poleVectorConstraint(ctl.ctl, self.ik, weight=True)

        # Add annotation
        mid_jnt = self.ik_joints[(len(self.ik_joints)-1)/2]
        self.anno = anno.aim(ctl.ctl, mid_jnt, "pv")

        self.pv_ctl = ctl
        self.controls[ctl.name] = ctl
Ejemplo n.º 53
0
    def rig_arm(self):
        # Create Ik joints
        createJoint(ikjnt_list)
        cmds.select(d=True)
        # Create Fk joints
        createJoint(fkjnt_list)
        cmds.select(d=True)
        # Create Rig joints
        createJoint(rigjnt_list)
        cmds.select(d=True)


        # Create Ik Rig
        # Ik handle
        ikh = cmds.ikHandle( n='ikh_arm', sj='ik_shoulder_jnt', ee='ik_wrist_jnt', sol='ikRPsolver', p=2, w=1 )

        ikctrlinfo = [[ikjnt_list[2][1], 'ctrl_ik_arm', 'grp_ctrl_ik_arm']]
        createControl(ikctrlinfo)

        pvpos = calculatePVPosition([ikjnt_list[0][0], ikjnt_list[1][0], ikjnt_list[2][0]])
        pvctrlinfo = [[pvpos, 'ctrl_pv_arm', 'grp_ctrl_pv_arm']]
        createControl(pvctrlinfo)

        # Parent ikh to ctrl
        cmds.parent('ikh_arm', 'ctrl_ik_arm')

        # PV constraint
        cmds.poleVectorConstraint(pvctrlinfo[0][1], ikh[0])

        # orient constrain arm ik_wrist to ctrl_arm
        cmds.orientConstraint(ikctrlinfo[0][1], ikjnt_list[2][0], mo=True)

        # Create FK rig
        fkctrlinfo = [[fkjnt_list[0][1], 'ctrl_fk_shoulder', 'grp_ctrl_fk_shoulder'],
        [fkjnt_list[1][1], 'ctrl_fk_elbow', 'grp_ctrl_fk_elbow'],
        [fkjnt_list[2][1], 'ctrl_fk_wrist', 'grp_ctrl_fk_wrist']]

        # Parent fk controls
        cmds.parent(fkctrlinfo[1][2], fkctrlinfo[0][1])
        cmds.parent(fkctrlinfo[2][2], fkctrlinfo[1][1])
Ejemplo n.º 54
0
def bdRigLegBones(side):
        legBones = ['thigh','knee','foot','toe','toe_end']
        for i in range(len(legBones)):
                legBones[i] = side + '_' + legBones[i] + '_jnt'
	#START setup foot roll 
	legIk = cmds.ikHandle(sol= 'ikRPsolver',sticky='sticky', startJoint=legBones[0],endEffector = legBones[2],name = side + '_leg_ikHandle')
	footIk = cmds.ikHandle(sol= 'ikSCsolver',sticky='sticky', startJoint=legBones[2],endEffector = legBones[3],name = side + '_foot_ikHandle')
	toeIk = cmds.ikHandle(sol= 'ikSCsolver',sticky='sticky', startJoint=legBones[3],endEffector = legBones[4],name = side + '_toe_ikHandle')
	#create the groups that will controll the foot animations ( roll, bend, etc etc)
	footGrp = bdCreateGroup([legIk[0],footIk[0],toeIk[0]],side + '_foot_grp',legBones[2]) 
	ballGrp = bdCreateGroup([legIk[0]],side + '_ball_grp',legBones[3])
	toeGrp = bdCreateGroup([ballGrp,footIk[0],toeIk[0]],side + '_toe_grp',legBones[4])
	heelGrp = bdCreateGroup([toeGrp],side + '_heel_grp',legBones[2])
	#add atributes on the footGrp - will be conected later to an anim controler
	attrList = ['Heel_R','Ball_R','Toe_R','kneeTwist']
	bdAddAttribute(footGrp,attrList)
	#connect the attributes
	cmds.connectAttr(footGrp + '.' + attrList[0],heelGrp + '.rx')
	cmds.connectAttr(footGrp + '.' + attrList[1],ballGrp + '.rx')
	cmds.connectAttr(footGrp + '.' + attrList[2],toeGrp + '.rx')
	#setup the controller 
	bdRigLegCtrl(side)
	#END setup foot roll 
	
	#START no flip knee knee 
	poleVectorLoc = cmds.spaceLocator()
	poleVectorLoc = cmds.rename(poleVectorLoc,side + 'poleVector')
	poleVectorLocGrp = cmds.group(poleVectorLoc,n=poleVectorLoc + '_GRP')
	
	thighPos = cmds.xform(legBones[0],q=True,ws=True,t=True)
	cmds.move(thighPos[0] + 5,thighPos[1],thighPos[2],poleVectorLocGrp)
	
	cmds.poleVectorConstraint(poleVectorLoc,legIk[0])
	
	shadingNodeADL = cmds.shadingNode('addDoubleLinear', asUtility=True,name = side + 'adl_twist')
	cmds.setAttr(shadingNodeADL + '.input2',90)
	
	cmds.connectAttr(footGrp + '.' + attrList[3],shadingNodeADL + '.input1')
	cmds.connectAttr(shadingNodeADL + '.output',legIk[0] + '.twist')
Ejemplo n.º 55
0
	def sample( self, *args ):
		# Build joint chain
		cmds.select( cl = True )
		chain1_jnt = cmds.joint( n = 'chain1_jnt', p = [0, 6, 0] )
		cmds.joint( n = 'chain2_jnt', p = [0, 3, 1] )
		chain3_jnt = cmds.joint( n = 'chain3_jnt', p = [0, 0, 0] )

		# Build ikHandle
		chain_ikHandle = cmds.ikHandle ( n = 'chain_ikHandle', startJoint = chain1_jnt, endEffector = chain3_jnt, sol = 'ikRPsolver' )[0]

		# Build pole vector
		pole_vector_loc = cmds.spaceLocator( n = 'pole_vector_loc' )[0]
		cmds.setAttr( '{0}.translateY'.format( pole_vector_loc ), 3 )
		cmds.setAttr( '{0}.translateZ'.format( pole_vector_loc ), 2 )
		cmds.poleVectorConstraint( pole_vector_loc, chain_ikHandle )

		# Build controller
		controller = cmds.circle ( nr = [0, 1, 0], r = 1 )[0]
		cmds.pointConstraint( controller, chain_ikHandle )

		# Run Standalone code
		No_Flip_Pole_Vector().build( root_joint = chain1_jnt, controller = controller, pole_vector = pole_vector_loc, name = 'example' )
Ejemplo n.º 56
0
def createPoleVector(hingeJnt, ikHandleName, poleVectorCtl, adjNodeName):
    
    """Create IK pole vector constraint"""
    locator = cmds.spaceLocator(name = poleVectorCtl)
    print locator
    temp = cmds.pointConstraint(hingeJnt, poleVectorCtl)
    cmds.delete(temp)
    cmds.move(-20, z = True)
    cmds.setAttr(poleVectorCtl + ".overrideEnabled", 1)
    cmds.setAttr(poleVectorCtl + ".overrideColor", 13)
    poleVector = cmds.poleVectorConstraint(poleVectorCtl, ikHandleName, weight=1)

    """Create poleVector ADJ node"""
    adjNode = adj_node.createAdjNode(poleVectorCtl, adjNodeName)
Ejemplo n.º 57
0
def generateAutoClav(_name, _shoulderSDK, _wristIK):
	print "doing something"
	error.assertString(_name)
	error.assertMayaObject(_shoulderSDK)
	error.assertMayaObject(_wristIK)
	cmds.select(clear=True)

	# Create joints
	joint1 = cmds.joint(n="%s_IK_JNT" %(_name))
	rc.copyTranslation(joint1, _shoulderSDK)
	joint2 = cmds.joint(n="%s_IKEND_JNT" %(_name))
	rc.copyTranslation(joint2, _wristIK)
	#cmds.parent(joint2, joint1)

	# Create IK
	ikControl = cmds.ikHandle(
		n="%s_IK" %(_name),
		sol="ikRPsolver",
		sj= joint1,
		ee=joint2
		)[0]
	# deselect so we don't get warnings
	cmds.select(d=1)

	# Create pole vec
	locator = cmds.spaceLocator(n="%s_up_LOC" %(_name))[0]
	rc.orientControl(locator, _wristIK)
	locGroup = rg.addGroup(locator, "%s_0" %(locator))
	cmds.setAttr("%s.ty" %(locator), 2)

	cmds.poleVectorConstraint(locator, ikControl)

	# Connect up to rig
	cmds.pointConstraint(_wristIK, locGroup, mo=1)
	cmds.pointConstraint(_wristIK, ikControl, mo=1)

	cmds.orientConstraint(joint1, _shoulderSDK, mo=1)
Ejemplo n.º 58
0
 def create_ik_setup(self):
     """@todo: insert doc for create_ik_setup"""
     # ik arm, hand
     ik_arm = cmds.ikHandle(sj=self.ik_jnts[0], ee=self.ik_jnts[2], sol='ikRPsolver')
     cmds.rename(ik_arm[1], '%s_%s_%s' % (self.side, 'arm', self.nc.effector))
     ik_arm = cmds.rename(ik_arm[0], '%s_%s_%s' % (self.side, 'arm', self.nc.ikhandle))
     ik_hand = cmds.ikHandle(sj=self.ik_jnts[2], ee=self.ik_jnts[3])
     cmds.rename(ik_hand[1], '%s_%s_%s' % (self.side, 'arm', self.nc.effector))
     ik_hand = cmds.rename(ik_hand[0], '%s_%s_%s' % (self.side, 'hand', self.nc.ikhandle))
     cmds.parent(ik_arm, ik_hand, self.controls['handik'])
     self.create_ik_arm_stretch()
     pv = cmds.poleVectorConstraint(self.controls['elbow'], ik_arm, weight=1)
     self.create_elbow_pin()
     # twist switch
     cmds.connectAttr('%s.twist' % self.controls['hand'], '%s_%s_%s.dTwistControlEnable' % (self.side, 'upperArm', self.nc.ikhandle), f=True)
     cmds.connectAttr('%s.twist' % self.controls['hand'], '%s_%s_%s.dTwistControlEnable' % (self.side, 'foreArm', self.nc.ikhandle), f=True)
Ejemplo n.º 59
0
    def RMCreatePoleVector(self,IKHandle):

        if not self.IKjointStructure:
            self.IKjointStructure = self.RMIdentifyIKJoints(IKHandle)
        locator = self.RMGetPoleVectorReferencePoint(self.IKjointStructure)
        
        distancia = RMRigTools.RMPointDistance(locator , self.IKjointStructure[1])

        self.PoleVectorControlResetPnt, self.PoleVectorControl = RMRigShapeControls.RMCreateBoxCtrl( locator, customSize = distancia / 5, name = self.NameConv.RMGetAShortName(self.IKjointStructure[1]) + "PoleVectorIK", centered = True)

        
        dataGroup, Curve = RMRigTools.RMCreateLineBetwenPoints(self.PoleVectorControl, self.IKjointStructure[1])
        cmds.parent(Curve, self.PoleVectorControl)
        cmds.parentConstraint(self.world, Curve)

        PoleVectorCnstraint = cmds.poleVectorConstraint( self.PoleVectorControl, IKHandle, name = "PoleVector")[0]
        PoleVectorCnstraint = self.NameConv.RMRenameBasedOnBaseName(self.PoleVectorControl,PoleVectorCnstraint,NewName=PoleVectorCnstraint)

        self.kinematics.append(dataGroup)
        cmds.delete(locator)
Ejemplo n.º 60
0
def targetList(constraint):
    """
    Return a list of targets (drivers) for the specified constraint node
    @param constraint: The constraint node whose targets will be returned
    @type constraint: str
    """
    # Check Constraint
    if not isConstraint(constraint):
        raise Exception('Constraint "' + constraint + '" does not exist!!')

    # Get Target List
    targetList = []
    constraintType = cmds.objectType(constraint)
    if constraintType == 'aicmdsonstraint':
        targetList = cmds.aicmdsonstraint(constraint, q=True, tl=True)
    elif constraintType == 'geometryConstraint':
        targetList = cmds.geometryConstraint(constraint, q=True, tl=True)
    elif constraintType == 'normalConstraint':
        targetList = cmds.normalConstraint(constraint, q=True, tl=True)
    elif constraintType == 'orientConstraint':
        targetList = cmds.orientConstraint(constraint, q=True, tl=True)
    elif constraintType == 'parentConstraint':
        targetList = cmds.parentConstraint(constraint, q=True, tl=True)
    elif constraintType == 'pointConstraint':
        targetList = cmds.pointConstraint(constraint, q=True, tl=True)
    elif constraintType == 'poleVectorConstraint':
        targetList = cmds.poleVectorConstraint(constraint, q=True, tl=True)
    elif constraintType == 'scaleConstraint':
        targetList = cmds.scaleConstraint(constraint, q=True, tl=True)
    elif constraintType == 'tangentConstraint':
        targetList = cmds.tangentConstraint(constraint, q=True, tl=True)

    # Check Target List
    if not targetList: targetList = []

    # Return Result
    return targetList