def buildSpan(self, points, index): num = str(index + 1).zfill(2) main_grp = pmc.group(empty=1, name='%s_span_%s_GRP' % (self.name, num)) # Create curve and connect curve points crv = curveBetweenNodes(points[0], points[2], name='%s_span_%s' % (self.name, num)) crv.setParent(main_grp) locs = connectCurve(crv) pmc.pointConstraint(points[0], points[1], locs[1], mo=0) pmc.pointConstraint(points[1], points[2], locs[2], mo=0) locs[0].setParent(points[0]) locs[1].setParent(main_grp) locs[2].setParent(main_grp) locs[3].setParent(points[2]) # Motionpath node mp = nodesAlongCurve(crv, numNodes=1, name='%s_span_%s' % (self.name, str(index)), upNode=points[1]) npc = pmc.createNode('nearestPointOnCurve', name='%s_span_%s' % (self.name, num)) points[1].worldPosition[0].connect(npc.inPosition) crv.worldSpace[0].connect(npc.inputCurve) npc.parameter.connect(mp['mpNodes'][0].uValue) mp['mpNodes'][0].fractionMode.set(0) mp['grps'][0].setParent(main_grp) # Tangents tanGrp = coreUtils.addChild(points[1], 'group', '%s_span_%s_tangent_GRP' % (self.name, num)) pmc.orientConstraint(mp['grps'][0], tanGrp) tanDrv = coreUtils.addChild(tanGrp, 'group', '%s_span_%s_tangent_DRV' % (self.name, num)) points[1].r.connect(tanDrv.r) points[1].s.connect(tanDrv.s) inTan_grp = coreUtils.addChild(tanDrv, 'group', '%s_span_%s_inTangent_GRP' % (self.name, num)) inTan_loc = coreUtils.addChild(inTan_grp, 'locator', '%s_span_%s_inTangent_LOC' % (self.name, num)) inDist = coreUtils.distanceBetweenNodes(points[0], points[1], '%s_span_%s_in_dist' % (self.name, num)) outTan_grp = coreUtils.addChild(tanDrv, 'group', '%s_span_%s_outTangent_GRP' % (self.name, num)) outTan_loc = coreUtils.addChild(outTan_grp, 'locator', '%s_span_%s_outTangent_LOC' % (self.name, num)) outDist = coreUtils.distanceBetweenNodes(points[1], points[2], '%s_span_%s_out_dist' % (self.name, num)) pmc.addAttr(points[1], ln='tangentWeight', at="float", minValue=0.0, maxValue=1.0, keyable=1, hidden=0, defaultValue=0.25) inWeight_md = coreUtils.multiply(inDist.distance, points[1].tangentWeight, 'md_%s_span_%s_inWeight_UTL' % (self.name, num)) outWeight_md = coreUtils.multiply(outDist.distance, points[1].tangentWeight, 'md_%s_span_%s_outWeight_UTL' % (self.name, num)) weight_uc = coreUtils.convert(inWeight_md.outputX, -1, 'uc_%s_span_%s_weightInvert_UTL' % (self.name, num)) outWeight_md.outputX.connect(outTan_grp.tx) weight_uc.output.connect(inTan_grp.tx) return { 'inTan': inTan_loc, 'outTan': outTan_loc, 'inDist': inDist, 'outDist': outDist, # 'weight_md':weight_md, 'main_grp': main_grp, }
def circle(self, joint): a = 0.25 b = 0.3432 p0 = Point(a + 0.005,0 , -a - 0.005) p1 = Point(b + 0.05, 0, 0) p2 = Point(a + 0.005, 0, a + 0.005) p3 = Point(0, 0, b) p4 = Point(-a - 0.005, 0, a + 0.005) p5 = Point(-b - 0.05, 0, 0) p6 = Point(-a - 0.005, 0, -a - 0.005) p7 = Point(0, 0, - b) points = [p0, p1, p2, p3, p4, p5, p6, p7, p0, p1, p2] pts = [] for point in points: pts.append(point.getPoint()) pm.curve(per = True, d = 3, p = pts, k = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) pm.parent("%s" % str(pm.ls(sl = True)[0]), "%s" % str(joint), relative = True) pm.parent("%s" % str(pm.ls(sl = True)[0]), world = True) pm.makeIdentity(r = True) curve = "%s" % str(pm.ls(sl = True)[0]) g = 0 while g < 8: pm.moveVertexAlongDirection(curve + ".cv[" + str(g) + "]", d = [0,1,0], m = -0.08) g += 1 group = pm.group(curve) pm.orientConstraint(curve, joint, mo = True) handle = joint + "IK" pm.pointConstraint(curve, handle, mo = True)
def scale_hierarchy(): # Select the entire hierarchy of your current selection and store everything in a list pm.select(hi=True, r=True) selected = pm.ls(sl=True) # If the ScaleMe group does not exist, create it if not pm.objExists('ScaleMe'): # Create the group that you will scale to resize your items scale_me = pm.createNode('transform', n='ScaleMe') # Iterate through all items, create a locator for each and set the locators to the items... # then reverse the constraint relationship so that the locators drive the items. Make all locators children of the ScaleMe group for s in selected: loc = pm.spaceLocator(n=s + '_ScaleLoc') p_con = pm.pointConstraint(s, loc) o_con = pm.orientConstraint(s, loc) pm.delete(p_con, o_con) pm.pointConstraint(loc, s) pm.orientConstraint(loc, s) pm.parent(loc, scale_me) else: # Grabbing all applicable joints using the locators attached to them items_to_key = [ item.split('_ScaleLoc')[0] for item in pm.listRelatives('ScaleMe', c=True) ] # Setting a keyframe on each item, then deleting the ScaleMe group (which deletes all constraints with it) for item in items_to_key: pm.setKeyframe(item, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz']) pm.delete('ScaleMe') # Gets rid of all keys on the items that were just resized. You can comment this out if you want to keep the keyframes. for item in items_to_key: pm.cutKey(item)
def generateShoulderCtrls(self): self.shoulder_ctrl = self.generateAlignedControl( 'main', self.spineJoints[0], 'shoulder', [0, 90, 0], 6) trans = self.spineJoints[-1 - 1]._getTranslation(space='world') pm.xform(self.shoulder_ctrl[0], rp=trans, sp=trans, ws=1) if self.ikfk: pm.addAttr(self.shoulder_ctrl[0], ln='ikfk_div', nn='-', at='enum', en='Xtra Attrs:', k=0, h=0) pm.setAttr(self.shoulder_ctrl[0] + '.ikfk_div', cb=1) pm.addAttr(self.shoulder_ctrl[0], ln='l_ikfk', nn='L Arm IK/FK', at='enum', en='IK:FK', k=1, h=0) pm.addAttr(self.shoulder_ctrl[0], ln='r_ikfk', nn='R Arm IK/FK', at='enum', en='IK:FK', k=1, h=0) pm.orientConstraint(self.shoulder_ctrl, self.spineJoints[-1 - 1], mo=0) pm.parent(self.shoulder_ctrl[0].getParent(), self.spineCtrls[-1])
def bdSwitchIKFK(self): if 'arm' in self.limb: print self.side + ' arm IK -> FK switch' for loc in self.fkArmCons: shadowLoc = pm.ls(self.namespace + self.side + loc + 'LOC')[0] tempLoc = pm.duplicate(shadowLoc) pm.parent(tempLoc, w=True) fkCon = pm.ls(self.namespace + self.side + loc + 'CON', type='transform')[0] tempCnstr = pm.orientConstraint(tempLoc, fkCon) pm.delete([tempCnstr, tempLoc]) self.armSwitchCon.attr('ikFkBlend').set(1) elif 'leg' in self.limb: print self.side + ' leg IK->FK switch ' for loc in self.fkLegCons: shadowLoc = pm.ls(self.namespace + self.side + loc + 'LOC')[0] tempLoc = pm.duplicate(shadowLoc) pm.parent(tempLoc, w=True) fkCon = pm.ls(self.namespace + self.side + loc + 'CON', type='transform')[0] tempCnstr = pm.orientConstraint(tempLoc, fkCon) pm.delete([tempCnstr, tempLoc]) self.legSwitchCon.attr('ikFkBlend').set(1)
def _bind(source, target, translate, rotate, snapTranslation=True, snapRotation=True, scale=10.0): # Create the nodes tBuffer = pmc.group(empty=True, n=target.shortName() + '_NODE') _connectToTarget(tBuffer, target) _addToNodeGroup(tBuffer) tNode = _createNode(curveData=CUBE_CURVEDATA, scale=scale, color=dt.Color(1, 1, 0)) pmc.rename(tNode, target.shortName() + '_translateOffset') pmc.parent(tNode, tBuffer) rBuffer = pmc.group(empty=True, n=target.shortName() + '_rotateBuffer') pmc.parent(rBuffer, tNode) rNode = _createNode(curveData=OCTO_CURVEDATA, scale=scale / 2, color=dt.Color.blue) pmc.rename(rNode, target.shortName() + '_rotateOffset') pmc.parent(rNode, rBuffer) # Set the nodes default positions and reset them if snapTranslation: tBuffer.setTranslation(target.getTranslation(worldSpace=True), worldSpace=True) else: tBuffer.setTranslation(source.getTranslation(worldSpace=True), worldSpace=True) if snapRotation: rBuffer.setRotation(target.getRotation(worldSpace=True), worldSpace=True) else: rBuffer.setRotation(source.getRotation(worldSpace=True), worldSpace=True) if translate: pmc.pointConstraint(source, tBuffer, mo=True) if rotate: pmc.orientConstraint(source, rBuffer, mo=True) if not translate and target.getParent() is not None: pmc.parentConstraint(target.getParent(), tBuffer, mo=True) pmc.pointConstraint(tNode, target, mo=snapTranslation) pmc.orientConstraint(rNode, target, mo=snapRotation) # Lock and hide the controls we don't want modified pmc.setAttr(tNode.rotate, channelBox=False, keyable=False, lock=True) pmc.setAttr(rNode.translate, channelBox=False, keyable=False, lock=True) pmc.setAttr(tNode.scale, channelBox=False, keyable=False, lock=True) pmc.setAttr(rNode.scale, channelBox=False, keyable=False, lock=True)
def align_bind_node(self, **kws): ''' Overwrite the default behaviour: Align the newly made BindNode as required for this bind ''' parentNode = self.sourceNode.listRelatives(p=True)[0] if parentNode: # Parent the BindNode to the Source Driver Node pm.parent(self.BindNode['Root'], self.sourceNode.listRelatives(p=True)[0]) else: pm.parent(self.BindNode['Root'], self.sourceNode) self.BindNode['Main'].rotateOrder.set(self.sourceNode.rotateOrder.get()) self.BindNode['Root'].rotateOrder.set(self.destinationNode.rotateOrder.get()) # Positional Alignment if self.settings.align_to_control_trans: pm.delete(pm.pointConstraint(self.sourceNode, self.BindNode['Root'])) pm.makeIdentity(self.BindNode['Root'], apply=True, t=1, r=0, s=0) pm.delete(pm.pointConstraint(self.destinationNode, self.BindNode['Root'])) if self.settings.align_to_source_trans: pm.delete(pm.pointConstraint(self.sourceNode, self.BindNode['Root'])) pm.makeIdentity(self.BindNode['Root'], apply=True, t=1, r=0, s=0) # Rotation Alignment if parentNode: pm.orientConstraint(self.sourceNode, self.BindNode['Root']) if self.settings.align_to_control_rots: pm.delete(pm.orientConstraint(self.destinationNode, self.BindNode['Main'])) if self.settings.align_to_source_rots: pm.delete(pm.orientConstraint(self.sourceNode, self.BindNode['Main']))
def ExtraControlForJnt(jnts=None): if not jnts: jnts = pm.ls(sl=True) else: jnts = pm.ls(jnts) for jnt in jnts: # duplicate joint pm.select(clear=True) newJnt = pm.joint(p=[0, 0, 0], name='%s_extra' % jnt.name()) pm.delete(pm.pointConstraint(jnt, newJnt)) pm.delete(pm.orientConstraint(jnt, newJnt)) pm.parent(newJnt, jnt) newJnt.jointOrient.set(jnt.jointOrient.get()) # create control curve for joint ctrl = CubeCrv(name='%s_ctrl' % jnt.name()) pm.delete(pm.pointConstraint(jnt, ctrl)) pm.delete(pm.orientConstraint(jnt, ctrl)) zeroAndOfs = ZeroGrp(ctrl) ctrl.translate >> newJnt.translate ctrl.rotate >> newJnt.rotate ctrl.scale >> newJnt.scale # make controls to move with base joints pm.parentConstraint(jnt, zeroAndOfs[0]) pm.scaleConstraint(jnt, zeroAndOfs[0])
def AlignBindNode(self, **kws): ''' Overwrite the default behaviour: Align the newly made BindNode as required for this bind ''' parentNode = self.SourceNode.listRelatives(p=True)[0] if parentNode: #Parent the BindNode to the Source Driver Node pm.parent(self.BindNode['Root'], self.SourceNode.listRelatives(p=True)[0]) else: pm.parent(self.BindNode['Root'], self.SourceNode) self.BindNode['Main'].rotateOrder.set(self.SourceNode.rotateOrder.get()) self.BindNode['Root'].rotateOrder.set(self.DestinationNode.rotateOrder.get()) #Positional Alignment if self.Settings.AlignToControlTrans: pm.delete(pm.pointConstraint(self.SourceNode, self.BindNode['Root'])) pm.makeIdentity(self.BindNode['Root'], apply=True, t=1, r=0, s=0) pm.delete(pm.pointConstraint(self.DestinationNode, self.BindNode['Root'])) if self.Settings.AlignToSourceTrans: pm.delete(pm.pointConstraint(self.SourceNode, self.BindNode['Root'])) pm.makeIdentity(self.BindNode['Root'], apply=True, t=1, r=0, s=0) #Rotation Alignment if parentNode: pm.orientConstraint(self.SourceNode, self.BindNode['Root']) if self.Settings.AlignToControlRots: pm.delete(pm.orientConstraint(self.DestinationNode, self.BindNode['Main'])) if self.Settings.AlignToSourceRots: pm.delete(pm.orientConstraint(self.SourceNode, self.BindNode['Main']))
def makeFK(self, limbJoints, topFingerJoints, rigScale, rigmodule): """ Do FK Arm/Leg, Metacarpal and Finger/Toe ctrl :param limbJoints: list(str), Arm/leg joints :param topFingerJoints: list(str), Metacarpal joints :param rigScale: float :param rigmodule: dict :return: """ limbCtrlInstanceList = [] handFeetCtrlInstanceList = [] limbCtrlConstraintList = [] handFeetCtrlConstraintList = [] # Arm/Leg for jnt in limbJoints: prefix = name.removeSuffix(jnt) parent = rigmodule.controlsGrp if len(limbCtrlInstanceList) > 0: parent = limbCtrlInstanceList[-1].C ctrl = control.Control(prefix=prefix, translateTo=jnt, rotateTo=jnt, parent=parent, shape='circleX') orientCnst = pm.orientConstraint(ctrl.getControl(), jnt, mo=True) limbCtrlConstraintList.append(orientCnst) limbCtrlInstanceList.append(ctrl) # Hand/Foot for topJntList in topFingerJoints: fnjJntList = joint.listHierarchy(topJntList, withEndJoints=False) fingerJointList = [] for jnt in fnjJntList: prefix = name.removeSuffix(jnt) parent = limbCtrlInstanceList[-1].C if len(fingerJointList) > 0: parent = fingerJointList[-1].C ctrl = control.Control(prefix=prefix, translateTo=jnt, rotateTo=jnt, parent=parent, shape='circleX') orientCnst = pm.orientConstraint(ctrl.getControl(), jnt) fingerJointList.append(ctrl) handFeetCtrlConstraintList.append(orientCnst) handFeetCtrlInstanceList.extend(fingerJointList) return limbCtrlInstanceList, limbCtrlConstraintList, handFeetCtrlInstanceList, handFeetCtrlConstraintList
def createFkAnimatedSystemConstraints(self): pm.select(cl = True) #FkManips #iterate fkManipsList for index in range(0, len(self.fkAnimatedManipsList) - 1): #constrain pm.scaleConstraint( self.fkAnimatedManipsList[index], self.fkAnimatedManipsList[index + 1].getParent(), mo = True ) pm.parentConstraint( self.fkAnimatedManipsList[index], self.fkAnimatedManipsList[index + 1].getParent(), mo = True ) pm.select(cl = True) #FkManipBase pm.scaleConstraint( self.manip_master, self.fkAnimatedManipsList[0].getParent(), mo = True ) pm.parentConstraint( self.manip_master, self.fkAnimatedManipsList[0].getParent(), mo = True ) pm.select(cl = True) #FkAnimatedJointsGrp pm.scaleConstraint( self.manip_master, self.fkAnimatedJointsGrp, mo = True ) pm.parentConstraint( self.manip_master, self.fkAnimatedJointsGrp, mo = True ) pm.select(cl = True) #Orientconstrain all fkAnimatedJoints for index in range(0, len(self.fkAnimatedManipsList)): pm.orientConstraint( self.fkAnimatedManipsList[index], self.fkAnimatedJointsList[index], mo = True ) pm.select(cl = True)
def twistJointConnect(mainJointList, twistList, joints, twistSyncJoints): """ Connect control rig twistJoints to skin joints: ARGS: mainJointList(List): Main joints, general 3 joints mainJointList(list): [[TwsA1, TwsA2,..],[TwsB1, TwsB2,..],...] same len than MainJointList joints(list): skined joints list, no twists p.e: upperLeg, lowerLeg, leg_End twistSyncJoints(List): Twist skinnedJoints, sync with joints like: [[TwsA1, TwsA2,..],[TwsB1, TwsB2,..],...] TODO: make this method? """ for i, joint in enumerate(mainJointList): if len(twistList) > i: # exclude last twist joint, empty items of a list for j, twistJnt in enumerate(twistList[i]): # exclude first term review? # leg joint or specific twist skinJoint = joints[i] if j == 0 else twistSyncJoints[i][j - 1] # skined joints # orient and scale twistJnt.scaleY.connect(skinJoint.scaleY) twistJnt.scaleZ.connect(skinJoint.scaleZ) # connect orient and point to deform twistJnt.rename(str(skinJoint).replace('joint', 'main')) pm.orientConstraint(twistJnt, skinJoint, maintainOffset=False) pm.pointConstraint(twistJnt, skinJoint, maintainOffset=False)
def upper_part(self): """ creat a torso from an ik spline chain """ self.chain_torso = Chain.make_jnt_chain(self.controls[-3:-1], name_template=self.prefix + "_IK_top_spine_{number}_JNT", parent=self.spline_chain[-1]) transform.match(self.controls[-1], self.chain_torso[0]) pm.pointConstraint(self.spline_chain[-1], self.chain_torso[0]) pm.orientConstraint(self.controls[-1], self.chain_torso[0]) self.main_ctrl = Control.make_control(self.controls[0], name=self.prefix + "main_ctrl_spine_{number}_CTRL", parent=self.root_grp) pm.move(self.main_ctrl.getShape().cv, 1, 0, 0, relative=True) [ctl.set_parent(self.main_ctrl) for ctl in self.controls[::1]] self.fk_spline_chain = self.spline_chain.duplicate( name_template=self.prefix + "_FK_torso_{number}_JNT") self.fk_spline_chain.set_parent(self.root_grp) for jnt_torso, fk_ctrl in zip(self.fk_spline_chain, self.spine_fk_ctrl): pm.parentConstraint(fk_ctrl, jnt_torso) pm.connectAttr(self.root_grp.scale, self.null_chain[0].scale) pm.connectAttr(self.root_grp.scale, self.spine_fk_ctrl[0].getParent().scale)
def makeNull(): #pm.melGlobals.initVar( 'string[]', 'KinectSkelNames' ) i = 0 for i in range(0, 24): pm.spaceLocator(p=(0, 0, 0), n=KinectSkelNames[i]) pm.spaceLocator(p=(0, 0, 0), n="KINECT_HAND") for i in range(0, 15): point[i] = [0.0, 0.0, 0.0] makeSkel() for i in range(0, 15): pm.rename('joint' + str(i + 1), KinectSkelJoints[i] + '_jt') for i in range(0, 15): pm.pointConstraint(KinectSkelJoints[i], KinectSkelJoints[i] + '_jt') pm.orientConstraint(KinectSkelJoints[i], KinectSkelJoints[i] + '_jt') #Create Camera cam = pm.camera()[1] #print pm.camera(cam, query=True, aspectRatio=True) cam.setAspectRatio(3) print cam.getAspectRatio()
def plug(node=None, socket=None, plugType='parent', name=''): if not node or not socket: sel = pmc.selected() if len(sel) == 2: node = sel[0] socket = sel[1] else: return 'Please supply or select node and socket' main_grp = pmc.group(empty=1, name='%s_%s_PLUG' % (name, plugType)) # constrained group const_grp = coreUtils.addChild(main_grp, 'group', name='%s_%s_CONST' % (name, plugType)) coreUtils.align(const_grp, node) pmc.parentConstraint(socket, const_grp, mo=1) if plugType == 'parent': pmc.parentConstraint(const_grp, node, mo=1) elif plugType == 'point': pmc.pointConstraint(const_grp, node, mo=1) else: pmc.orientConstraint(const_grp, node, mo=1) return main_grp
def connectStereoCameras(camera, stereo_cams, base_percent=0.7, interactive=False, threshod=0.001): if not pm.objExists(camera): print 'The given center camera does not exists: '+str(camera) return else: camera = pm.PyNode(camera) if not isinstance(stereo_cams, type([])): stereo_cams = [stereo_cams] stereoCameras = {} for s in stereo_cams: s = pm.PyNode(s) # constrain stereo camera to main camera pm.pointConstraint(camera, s, offset=(0,0,0), weight=1) pm.orientConstraint(camera, s, offset=(0,0,0), weight=1) # local pivot alignment rot_local = pm.xform(camera, query=True, os=True, rp=True) scale_local = pm.xform(camera, query=True, os=True, sp=True) local_pivot_bool = False for v in rot_local: if math.fabs(v) >= threshod: local_pivot_bool = True pm.xform(s, os=True, rp=tuple(rot_local)) break for v in scale_local: if math.fabs(v) >= threshod: local_pivot_bool = True pm.xform(s, os=True, sp=tuple(scale_local)) break if interactive and local_pivot_bool: pm.confirmDialog(title='Warning', message='Found non-zero value on local pivot attribute of camera!', button='OK', defaultButton='OK', cancelButton='OK', dismissString='OK') # connect attributes of cameras for a in ['focalLength', 'horizontalFilmAperture', 'verticalFilmAperture']: camera.attr(a) >> s.attr(a) try: filmFit = camera.attr('filmFit').get() if filmFit==0: filmFit = 1 camera.attr('filmFit').set(filmFit) s.attr('filmFit').set(filmFit) s.getShape().attr('stereo').set(2) s.getShape().attr('displayResolution').set(0) except: print traceback.format_exc() # create safe plane planes = createStereoSafePlanes(s) # add roundness ratio addRoundnessRatio(planes['safePlane'], planes['convergePlane']) stereoCameras.update( {s:{'camera':camera, 'safePlane':planes['safePlane'], 'convergePlane':planes['convergePlane'], 'node':s}} ) return stereoCameras
def makeFkIk(*args): bindRoot = pm.ls(selection = True)[0] bindChain = pm.ls(bindRoot, dag = True) fkChain = pm.duplicate(bindRoot) replaceSuffix(fkChain, 'fk') makeFk(False, fkChain) ikChain = pm.duplicate(bindRoot) replaceSuffix(ikChain, 'ik') makeIk(False, ikChain) fkChainList = pm.ls(fkChain, dag = True) ikChainList = pm.ls(ikChain, dag = True) createPad(bindRoot) suffixIndex = bindChain[0].rfind('_') hanldeName = bindChain[0][:suffixIndex] + '_switch' handle = createHandle(hanldeName) pm.rename(handle, hanldeName) pm.parentConstraint(bindChain[-1], handle) constraintList = [] for i, item in enumerate(bindChain): newConstraint = pm.orientConstraint(fkChainList[i], ikChainList[i], bindChain[i], mo = False) fkCon = pm.orientConstraint(newConstraint, q = True, wal = True)[1] ikCon = pm.orientConstraint(newConstraint, q = True, wal = True)[0] pm.setDrivenKeyframe(fkCon, cd = handle + '.switch', v = 1, dv = 10) pm.setDrivenKeyframe(fkCon, cd = handle + '.switch', v = 0, dv = 0) pm.setDrivenKeyframe(ikCon, cd = handle + '.switch', v = 0, dv = 10) pm.setDrivenKeyframe(ikCon, cd = handle + '.switch', v = 1, dv = 0)
def _buildDrivers(name, xforms, controls, **kwargs): ctrl_orient = kwargs.get('ctrl_orient', None) # Create IK joints joints = createNodeChain(xforms, node_func=partial( pm.createNode, 'joint'), prefix='ikj_') for joint in joints: pm.makeIdentity(joint, apply=True) # Place control curve controls[0].getParent().setTransformation(xforms[-1].getMatrix(ws=True)) if ctrl_orient: pm.rotate(controls[0].getParent(), ctrl_orient) # Create IK chain ik_handle, _ = pm.ikHandle(n="Ik_{}_handle".format(name), sj=joints[0], ee=joints[-1]) ik_handle.setParent(controls[0]) # Constrain end driver joint pm.orientConstraint(controls[0], joints[-1], mo=True) # Hide intermediate nodes for node in joints + [ik_handle]: node.visibility.set(False) return joints
def ExtraControlForJnt( jnts=None ) : if not jnts: jnts = pm.ls( sl=True ) else: jnts = pm.ls( jnts ) for jnt in jnts: # duplicate joint pm.select( clear=True ) newJnt = pm.joint( p = [0,0,0], name= '%s_extra'%jnt.name() ) pm.delete( pm.pointConstraint( jnt, newJnt ) ) pm.delete( pm.orientConstraint( jnt, newJnt ) ) pm.parent( newJnt, jnt ) newJnt.jointOrient.set( jnt.jointOrient.get() ) # create control curve for joint ctrl = CubeCrv( name = '%s_ctrl'%jnt.name() ) pm.delete( pm.pointConstraint( jnt, ctrl ) ) pm.delete( pm.orientConstraint( jnt, ctrl ) ) zeroAndOfs = ZeroGrp( ctrl ) ctrl.translate >> newJnt.translate ctrl.rotate >> newJnt.rotate ctrl.scale >> newJnt.scale # make controls to move with base joints pm.parentConstraint( jnt, zeroAndOfs[0] ) pm.scaleConstraint( jnt, zeroAndOfs[0] )
def orientCtrlGrp(self, grp, percent): """Given grp along self.curve at given param, ensure the grp is oriented right: with the rig's primary axis along the curve's tangent""" param = percent * self.curve.getKnotDomain()[1] pos = self.curve.getPointAtParam(param) grp.translate.set(pos) if percent == 0.0: # just make it the same as the root joint #grp.setMatrix(self.jnts[0].matrix.get()) pmc.delete(pmc.orientConstraint(self.jnts[0], grp, mo=False)) return elif percent == 1.0: # similarly, set matrix to end joint #grp.setMatrix(self.jnts[-1].matrix.get()) pmc.delete(pmc.orientConstraint(self.jnts[-1], grp, mo=False)) return axis = self.jnts[1].translate.get().normal() arc = self.jnts[1].jointOrient.get().normal() pmc.delete( pmc.tangentConstraint(self.curve, grp, aimVector=axis, upVector=arc, worldUpVector=arc, worldUpObject=self.jnts[1])) """
def buildMainControls(self): # Get the ctrl postion ctrlPosition = utils.recalculatePosition(self.jointSystem.positions, self.numHighLevelCtrls) metaCtrls = [] # Iterate though all the position for i in range(self.numHighLevelCtrls): output_window("Build Main Control: {}".format(i)) # Create a control object ctrl = self.createCtrlObj("%s%i" % (self.part, i)) # Set the position ctrl.prnt.translate = list(ctrlPosition[i]) # Lock the scale ctrl.lockScale() metaCtrls.append(ctrl) # Is orientation set to world if not self.ikControlToWorld: # Get the closest joint position closestJoints = libMath.spread(0, len(self.jointSystem) - 1, self.numHighLevelCtrls) for jointPosition, i in zip(closestJoints, range(self.numHighLevelCtrls)): # Is a closest joint a fraction if jointPosition % 1: # Orient between current and next pm.delete(pm.orientConstraint( self.jointSystem.jointList[int(jointPosition)], self.jointSystem.jointList[int(jointPosition) + 1], metaCtrls[i].prnt.pynode)) else: pm.delete(pm.orientConstraint( self.jointSystem.jointList[int(jointPosition)], metaCtrls[i].prnt.pynode)) self.mainCtrls = metaCtrls
def makeFk(sel, inputRoot): currentChain = pm.ls(selection = True, dag = True) if sel == False: currentChain = pm.ls(inputRoot, dag = True) controlList = [] primeList = [] createPad(currentChain[0]) for j, item in enumerate(currentChain): if j != len(currentChain) - 1: index = item.rfind('_') newName = item[:index] + '_ctrl' newControl = pm.circle(nr = [1,0,0], r = 1, n = newName)[0] newPrime = createPrime(item, newControl) pm.orientConstraint(newControl, item, mo = False) controlList.append(newControl) primeList.append(newPrime) for x, item in enumerate(primeList): if x != len(primeList) - 1: pm.parent(primeList[x + 1], controlList[x])
def makeNull(): #pm.melGlobals.initVar( 'string[]', 'KinectSkelNames' ) i=0 for i in range(0,24): pm.spaceLocator(p=(0, 0, 0),n=KinectSkelNames[i]) pm.spaceLocator(p=(0, 0, 0),n="KINECT_HAND") for i in range(0,15): point[i] = [0.0,0.0,0.0] makeSkel() for i in range(0,15): pm.rename('joint'+str(i+1), KinectSkelJoints[i]+'_jt') for i in range(0,15): pm.pointConstraint( KinectSkelJoints[i], KinectSkelJoints[i]+'_jt' ) pm.orientConstraint( KinectSkelJoints[i], KinectSkelJoints[i]+'_jt' ) #Create Camera cam = pm.camera()[1] #print pm.camera(cam, query=True, aspectRatio=True) cam.setAspectRatio(3) print cam.getAspectRatio()
def connect_orientCns(self): """Connection with ori cns Connection definition using orientation constraint. """ self.parent.addChild(self.root) refArray = self.settings["ikrefarray"] if refArray: ref_names = self.get_valid_ref_list(refArray.split(",")) if len(ref_names) == 1: ref = self.rig.findRelative(ref_names[0]) pm.parent(self.ik_cns, ref) else: ref = [] for ref_name in ref_names: ref.append(self.rig.findRelative(ref_name)) ref.append(self.ik_cns) cns_node = pm.orientConstraint(*ref, maintainOffset=True) cns_attr = pm.orientConstraint( cns_node, query=True, weightAliasList=True) for i, attr in enumerate(cns_attr): pm.setAttr(attr, 1.0) node_name = pm.createNode("condition") pm.connectAttr(self.ikref_att, node_name + ".firstTerm") pm.setAttr(node_name + ".secondTerm", i) pm.setAttr(node_name + ".operation", 0) pm.setAttr(node_name + ".colorIfTrueR", 1) pm.setAttr(node_name + ".colorIfFalseR", 0) pm.connectAttr(node_name + ".outColorR", attr)
def setup_outputs(self): reset_joints, joints = self.create.joint.point_base( self.reference_points, name='ikInPlace', orient_type='point_orient') output_reset_joints, output_joints = self.create.joint.point_base( self.reference_points, name='IKOutput', orient_type='point_orient') self.reset_joints = output_reset_joints self.joints = output_joints self.attach_points['attachment_ik_leg'] = self.reset_joints reset_joints.setParent(self.rig_system.joints) self.reset_joints.setParent(self.rig_system.joints) for each_joint, each_driver, output_joint in zip( joints, [self.up_ik.joints[1]] + self.dwn_ik.joints, self.joints): pm.parentConstraint(each_driver, each_joint, mo=True) pm.orientConstraint(each_joint, output_joint, mo=True) self.control.addAttr('toe_break', proxy=str(self.rig_system.settings.toe_break)) self.control.addAttr('tip', proxy=str(self.rig_system.settings.tip)) self.control.addAttr('tipRotation', proxy=str(self.rig_system.settings.tipRotation)) self.control.addAttr('tap', proxy=str(self.rig_system.settings.tap)) self.rm.lock_and_hide_attributes(self.control, bit_string='000111000h') self.control.rotateX >> self.rig_system.settings.in_out self.create.connect.times_factor(self.control.rotateZ, self.rig_system.settings.ball, -57.296) self.control.rotateY >> self.rig_system.settings.tipRotation
def makeAim(self): """Creates the aimConstraints joints for prevLoc to loc""" # each SPAN for i, jnt in enumerate(self.jnts): grp = self.grps[i] loc = self.locs[i] pmc.orientConstraint(loc, jnt, mo=False) if not i: # if root joint, pointConstrain(?) and move along - # next part is for each SPAN only continue prevJnt = self.jnts[i - 1] prevGrp = self.grps[i - 1] prevLoc = self.locs[i - 1] # if empty, getParent returns None, getChildren returns [] if jnt not in prevJnt.getChildren(): pmc.warning("It is recommended that joints be in a heirarchy," " and be selected in heirarchical order.") # get one locator to aim at the other, which produces rotation # values which can be piped into joint rotation axis = jnt.translate.get().normal() arc = jnt.jointOrient.get().normal() wuo = prevGrp #if not i: # wuo = self.ctrls[0] aim = pmc.aimConstraint(loc, prevLoc, aimVector=axis, upVector=arc, worldUpVector=arc, worldUpObject=wuo, wut="objectrotation")
def generateHipCtrls(self, _ikfk=False): self.hip_ctrl = self.generateAlignedControl('main', self.spineJoints[1], 'hip', [0, 90, 90], 6) pm.parentConstraint(self.hip_ctrl, self.spineJoints[1]) self.hipsRotate_ctrl = self.generateAlignedControl( 'main', self.spineJoints[-1], 'hipsRotate', [0, 90, 0], 5) pm.orientConstraint(self.hipsRotate_ctrl[0], self.spineJoints[-1], mo=0) pm.parent(self.hipsRotate_ctrl[0].getParent(), self.hip_ctrl) if _ikfk: pm.addAttr(self.hip_ctrl[0], ln='ikfk_div', nn='-', at='enum', en='Xtra Attrs:', k=0, h=0) pm.setAttr(self.hip_ctrl[0] + '.ikfk_div', cb=1) pm.addAttr(self.hip_ctrl[0], ln='l_ikfk', nn='L Leg IK/FK', at='enum', en='IK:FK', k=1, h=0) pm.addAttr(self.hip_ctrl[0], ln='r_ikfk', nn='R Leg IK/FK', at='enum', en='IK:FK', k=1, h=0)
def point_auto(self, zone, parent): """ Create a simple point control for a joint :param zone: zone of the points (joints) :param parent: parent of the controllers :return: """ pointJoints = [point for point in pm.ls() if re.match('^%s.*%s$' % (zone, self._skinJointNaming), str(point))] # create controllers pointControllers = [] for joint in pointJoints: controller = self._create_controller(str(joint).replace('joint', 'ctr'), 'pole', 2, 10) pm.xform(controller, ws=True, m=pm.xform(joint, ws=True, q=True, m=True)) # hierarchy parent.addChild(controller) pointControllers.append(controller) # roots ARC.createRoots(pointControllers) # conenct to joints for i, joint in enumerate(pointJoints): pm.pointConstraint(pointControllers[i], joint, maintainOffset=False) pm.orientConstraint(pointControllers[i], joint, maintainOffset=False) ARC.DGUtils.connectAttributes(pointControllers[i], joint, ['scale'], 'XYZ')
def bdSwitchIKFK(self): if 'arm' in self.limb: print self.side + ' arm IK -> FK switch' for loc in self.fkArmCons: shadowLoc = pm.ls(self.namespace + self.side + loc + 'LOC')[0] tempLoc = pm.duplicate(shadowLoc) pm.parent(tempLoc,w=True) fkCon = pm.ls(self.namespace + self.side + loc + 'CON',type='transform')[0] tempCnstr = pm.orientConstraint(tempLoc,fkCon) pm.delete([tempCnstr,tempLoc]) self.armSwitchCon.attr('ikFkBlend').set(1) elif 'leg' in self.limb: print self.side + ' leg IK->FK switch ' for loc in self.fkLegCons: shadowLoc = pm.ls(self.namespace + self.side + loc + 'LOC')[0] tempLoc = pm.duplicate(shadowLoc) pm.parent(tempLoc,w=True) fkCon = pm.ls(self.namespace + self.side + loc + 'CON',type='transform')[0] tempCnstr = pm.orientConstraint(tempLoc,fkCon) pm.delete([tempCnstr,tempLoc]) self.legSwitchCon.attr('ikFkBlend').set(1)
def orientConstraintRename(sels): if len(sels) >= 3 or len(sels) <= 1: pm.error('Please select two') part = sels[1].split("_") renameConstraint = '_'.join(['otc', part[1], part[2], part[3]]) pm.orientConstraint(sels[0], sels[1], n=renameConstraint, mo=True, w=1)
def bind(self): self.handle = pmc.ikHandle(sj=self.start_joint, ee=self.end_joint)[0] self.handle.hide() pmc.parent(self.handle, self.ik_control) pmc.poleVectorConstraint(self.pole_control, self.handle) pmc.parentConstraint(self.base_control, self.start_joint, mo=True) pmc.orientConstraint(self.ik_control, self.end_joint, mo=True)
def createBindJnts(jntList, baseName, side): pm.select(deselect=True) for i in range(len(jntList)): jntNode = pm.PyNode(side + jntList[i]) jntPos = jntNode.getTranslation('world') newJnt = pm.joint(name=side + '_' + baseName + str(i) + '_bind_jnt', p=(jntPos[0], jntPos[1], jntPos[2]), rad=2) pm.pointConstraint(side + jntList[i], newJnt) pm.orientConstraint(side + jntList[i], newJnt)
def addC(ctrl, target): ''' Puts a `ctrl` on each child joint of the selected joints Target is a mirror list of the bound joints ''' #expression -e -s "//\njoint5.rotateZ = nurbsCircle21.rotateZ + (nurbsCircle22.rz + nurbsCircle20.rotateZ)*.5;" -o joint5 -ae 1 -uc all expression2; obj = selected()[0] controls = [] groups = [] while obj: c = duplicate(ctrl)[0] c.setParent(obj) c.t.set(0, 0, 0) controls.append(c) spinner = group(em=True) spinner.setParent(obj) spinner.t.set(0, 0, 0) groups.append(spinner) pointConstraint(obj, target) orientConstraint(spinner, target) children = obj.listRelatives(type='joint') if children: obj = children[0] else: obj = None break target = target.listRelatives(type='joint')[0] for i, s in enumerate(groups[2:-2], 2): msg = '{0}.rz = {1[2]}.rz + ( {1[1]}.rz + {1[3]}.rz ) * 0.5 + ( {1[0]}.rz + {1[4]}.rz ) * 0.2;'.format( s, controls[i - 2:i + 3]) expression(s=msg) msg = '{0}.rz = {1[0]}.rz + ( {1[1]}.rz ) * 0.5 + ( {1[2]}.rz ) * 0.2;'.format( groups[0], controls[:3]) expression(s=msg) msg = '{0}.rz = {1[1]}.rz + ( {1[0]}.rz + {1[2]}.rz ) * 0.5 + ( {1[3]}.rz ) * 0.2;'.format( groups[1], controls[:4]) expression(s=msg) msg = '{0}.rz = {1[2]}.rz + ( {1[1]}.rz ) * 0.5 + ( {1[0]}.rz ) * 0.2;'.format( groups[-1], controls[-3:]) expression(s=msg) msg = '{0}.rz = {1[2]}.rz + ( {1[1]}.rz + {1[3]}.rz ) * 0.5 + ( {1[0]}.rz ) * 0.2;'.format( groups[-2], controls[-4:]) expression(s=msg)
def create_waveSystem(self): horizAmp = self.autoJnt.addAttr('horizontalAmplitude', attributeType='float', min=-5, max=5, defaultValue=0, keyable=True) horizWaveLength = self.autoJnt.addAttr('horizontalWaveLength', attributeType='float', min=-.01, max=1, defaultValue=1, keyable=True) vertAmp = self.autoJnt.addAttr('verticalAmplitude', attributeType='float', min=-5, max=5, defaultValue=0, keyable=True) vertWaveLength = self.autoJnt.addAttr('verticalWaveLength', attributeType='float', min=-.01, max=1, defaultValue=1, keyable=True) #horizontal deformer horizontalWave, horizontalWaveHandle = pm.nonLinear( self.ribbonSystem.nurbsPatch, type='wave') horizontalWave.renameNode(name=self.TipName, base="%sWaveDeformerHorizontal_1") horizontalWaveHandle.renameNode(name=self.TipName, base="%sWaveDeformerHorizontal_1") #vertical deformer verticalWave, verticalWaveHandle = pm.nonLinear( self.ribbonSystem.nurbsPatch, type='wave') verticalWave.renameNode(name=self.TipName, base="%sWaveDeformerHorizontal") verticalWaveHandle.renameNode(name=self.TipName, base="%sWaveDeformerHorizontal") pm.delete( pm.orientConstraint(self.fkJnts[0], horizontalWaveHandle, maintainOffset=False)) pm.delete( pm.orientConstraint(self.fkJnts[0], verticalWaveHandle, maintainOffset=False)) horizontalWaveHandle.rx.set(horizontalWaveHandle.rx.get() + 90) horizAmp.connect(horizontalWave.amp) horizWaveLength.connect(horizontalWave.wav) vertAmp.connect(verticalWave.amp) vertWaveLength.connect(verticalWave.wav)
def createFlcs(self,direction,ends): folicles = [] pm.select(cl=1) for i in range(self.numJnt): jnt = self.ikJntList[i] print jnt pm.select(cl=1) flcShape = pm.createNode('follicle', name = self.srf.name() + '_flcShape_' + str(i).zfill(2) ) flcTransform = flcShape.getParent() flcTransform.rename(flcShape.name().replace('flcShape','flc') ) folicles.append(flcTransform) srfShape = pm.listRelatives(self.srf)[0] srfShape.local.connect(flcShape.inputSurface) srfShape.worldMatrix[0].connect(flcShape.inputWorldMatrix) flcShape.outRotate.connect(flcTransform.rotate) flcShape.outTranslate.connect(flcTransform.translate) #flcShape.flipDirection.set(1) cposNode = pm.shadingNode( 'closestPointOnSurface', asUtility = True ,n = jnt.name() + '_cpos') decMtx = pm.shadingNode('decomposeMatrix',asUtility = True, name = jnt.name() + '_dmtx') self.srf.getShape().worldSpace[0].connect(cposNode.inputSurface) decMtx.outputTranslate.connect(cposNode.inPosition) jnt.worldMatrix[0].connect(decMtx.inputMatrix) pm.addAttr(jnt, shortName='jointPosition', longName='jointPosition', defaultValue=0, minValue=0, maxValue=1) jntPos = cposNode.parameterU.get() jnt.jointPosition.set(jntPos) self.cposList.append(cposNode) #cposNode.parameterU >> flcShape.parameterU flcShape.parameterV.set(0.5) pm.orientConstraint(flcTransform,self.rigJntList[i],mo=1) #pm.pointConstraint(flcTransform,self.rigJntList[i],mo=1,weight=0) blendAttr = pm.shadingNode( 'blendTwoAttr', asUtility = True ,n = flcTransform.name() + '_b2a') self.stretchRev.outputX >> blendAttr.attributesBlender jnt.jointPosition >> blendAttr.input[0] cposNode.parameterU >> blendAttr.input[1] blendAttr.output >> flcShape.parameterU pm.select(cl=1) flcGrp = pm.group(folicles,n=self.srf.name() + '_flc_grp') pm.select(cl=1) pm.parent(flcGrp,self.mainGrp) self.flcTransformList = folicles
def makeRibbonSpline(jnts=[], axis="z"): if not jnts: jnts = pmc.ls(sl=True) loft = makeRibbon(jnts=jnts, axis=axis) for i, j in enumerate(jnts): u = 1.0 * i / (len(jnts) - 1.0) foll = makeFollicle(loft, u, 0.5) pmc.orientConstraint(foll.getParent(), j, mo=True)
def run(self): # retrieve mid and root joints self.midJoint = self.endJoint.getParent() self.rootJoint = self.midJoint.getParent() # duplicate joints for ik chain ikJointNameFmt = '{0}_ik' ikjnts = pulse.nodes.duplicateBranch(self.rootJoint, self.endJoint, nameFmt=ikJointNameFmt) for j in ikjnts: # TODO: debug settings for build actions j.v.set(True) self.rootIkJoint = ikjnts[0] self.midIkJoint = ikjnts[1] self.endIkJoint = ikjnts[2] # parent ik joints to root control self.rootIkJoint.setParent(self.rootCtl) # create ik and hook up pole object and controls handle, effector = pm.ikHandle(n="{0}_ikHandle".format( self.endIkJoint), sj=self.rootIkJoint, ee=self.endIkJoint, sol="ikRPsolver") # add twist attr to end control self.endCtl.addAttr('twist', at='double', k=1) self.endCtl.twist >> handle.twist # connect mid ik ctl (pole vector) pm.poleVectorConstraint(self.midCtlIk, handle) # parent ik handle to end control handle.setParent(self.endCtl) # constraint end joint scale and rotation to end control pm.orientConstraint(self.endCtl, self.endIkJoint, mo=True) pm.scaleConstraint(self.endCtl, self.endIkJoint, mo=True) # constraint the original joint branch to the ik joint branch pulse.nodes.fullConstraint(self.rootIkJoint, self.rootJoint) pulse.nodes.fullConstraint(self.midIkJoint, self.midJoint) pulse.nodes.fullConstraint(self.endIkJoint, self.endJoint) # setup ikfk switch # ... # cleanup for jnt in ikjnts: # TODO: lock attrs jnt.v.set(False) handle.v.set(False)
def createFlcs(self, direction, ends): folicles = [] pm.select(cl=1) for i in range(self.numJnt): jnt = self.ikJntList[i] print jnt pm.select(cl=1) flcShape = pm.createNode('follicle', name=self.srf.name() + '_flcShape_' + str(i).zfill(2)) flcTransform = flcShape.getParent() flcTransform.rename(flcShape.name().replace('flcShape', 'flc')) folicles.append(flcTransform) srfShape = pm.listRelatives(self.srf)[0] srfShape.local.connect(flcShape.inputSurface) srfShape.worldMatrix[0].connect(flcShape.inputWorldMatrix) flcShape.outRotate.connect(flcTransform.rotate) flcShape.outTranslate.connect(flcTransform.translate) # flcShape.flipDirection.set(1) cposNode = pm.shadingNode('closestPointOnSurface', asUtility=True, n=jnt.name() + '_cpos') decMtx = pm.shadingNode('decomposeMatrix', asUtility=True, name=jnt.name() + '_dmtx') self.srf.getShape().worldSpace[0].connect(cposNode.inputSurface) decMtx.outputTranslate.connect(cposNode.inPosition) jnt.worldMatrix[0].connect(decMtx.inputMatrix) pm.addAttr(jnt, shortName='jointPosition', longName='jointPosition', defaultValue=0, minValue=0, maxValue=1) jntPos = cposNode.parameterU.get() jnt.jointPosition.set(jntPos) self.cposList.append(cposNode) # cposNode.parameterU >> flcShape.parameterU flcShape.parameterV.set(0.5) pm.orientConstraint(flcTransform, self.rigJntList[i], mo=1) # pm.pointConstraint(flcTransform,self.rigJntList[i],mo=1,weight=0) blendAttr = pm.shadingNode('blendTwoAttr', asUtility=True, n=flcTransform.name() + '_b2a') self.stretchRev.outputX >> blendAttr.attributesBlender jnt.jointPosition >> blendAttr.input[0] cposNode.parameterU >> blendAttr.input[1] blendAttr.output >> flcShape.parameterU pm.select(cl=1) flcGrp = pm.group(folicles, n=self.srf.name() + '_flc_grp') pm.select(cl=1) pm.parent(flcGrp, self.mainGrp) self.flcTransformList = folicles
def create_control(node, name='', shape="", axis="", size=1, point=True, orient=True, scale=False, help=False): node = pm.PyNode(node) if not shape: shape = "circle" if not name: name = "%s_ctrl" %node.name() shapeMELs = { "circle" : "circle -c 0 0 0 -nr 0 1 0 -sw 360 -r 0.5 -d 3 -ut 0 -s 8 -ch 0", "diamond" : "circle -c 0 0 0 -nr 0 1 0 -sw 360 -r 0.5 -d 1 -ut 0 -s 4 -ch 0", "square" : "curve -d 1 -p -0.5 0 0.5 -p -0.5 0 -0.5 -p 0.5 0 -0.5 -p 0.5 0 0.5 -p -0.5 0 0.5 -k 0 -k 1 -k 2 -k 3 -k 4", "global" : "curve -d 3 -p 0 0 0.75 -p 0.25 0 0.5 -p 0.25 0 0.5 -p 0.25 0 0.5 -p 0.375 0 0.5 -p 0.5 0 0.5 -p 0.5 0 0.375 -p 0.5 0 -0.375 -p 0.5 0 -0.5 -p 0.375 0 -0.5 -p -0.375 0 -0.5 -p -0.5 0 -0.5 -p -0.5 0 -0.375 -p -0.5 0 0.375 -p -0.5 0 0.5 -p -0.375 0 0.5 -p -0.25 0 0.5 -p -0.25 0 0.5 -p -0.25 0 0.5 -p 0 0 0.75 -k 0 -k 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 17 -k 17", "local" : "curve -d 3 -p 0 0 0.5 -p 0.125 0 0.375 -p 0.125 0 0.375 -p 0.125 0 0.375 -p 0.25 0 0.375 -p 0.375 0 0.375 -p 0.375 0 0.25 -p 0.375 0 -0.25 -p 0.375 0 -0.375 -p 0.25 0 -0.375 -p -0.25 0 -0.375 -p -0.375 0 -0.375 -p -0.375 0 -0.25 -p -0.375 0 0.25 -p -0.375 0 0.375 -p -0.25 0 0.375 -p -0.125 0 0.375 -p -0.125 0 0.375 -p -0.125 0 0.375 -p 0 0 0.5 -k 0 -k 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 17 -k 17", "root" : "curve -d 1 -p 0 0 0.325 -p -0.0634045 0 0.318755 -p -0.124372 0 0.300261 -p -0.180561 0 0.270228 -p -0.22981 0 0.22981 -p -0.270228 0 0.180561 -p -0.300261 0 0.124372 -p -0.318755 0 0.0634045 -p -0.325 0 0 -p -0.318755 0 -0.0634045 -p -0.300261 0 -0.124372 -p -0.270228 0 -0.180561 -p -0.22981 0 -0.22981 -p -0.180561 0 -0.270228 -p -0.124372 0 -0.300261 -p -0.0634045 0 -0.318755 -p 0 0 -0.325 -p 0.0634045 0 -0.318755 -p 0.124372 0 -0.300261 -p 0.180561 0 -0.270228 -p 0.22981 0 -0.22981 -p 0.270228 0 -0.180561 -p 0.300261 0 -0.124372 -p 0.318755 0 -0.0634045 -p 0.325 0 0 -p 0.318755 0 0.0634045 -p 0.300261 0 0.124372 -p 0.270228 0 0.180561 -p 0.22981 0 0.22981 -p 0.180561 0 0.270228 -p 0.124372 0 0.300261 -p 0.0634045 0 0.318755 -p 0 0 0.325 -p 0 0 -0.325 -p 0 0 -0.25 -p -0.0487726 0 -0.245197 -p -0.095671 0 -0.23097 -p -0.138893 0 -0.207868 -p -0.176777 0 -0.176777 -p -0.207868 0 -0.138893 -p -0.23097 0 -0.095671 -p -0.245197 0 -0.0487726 -p -0.25 0 0 -p -0.325 0 0 -p 0.325 0 0 -p -0.25 0 0 -p -0.245197 0 0.0487726 -p -0.23097 0 0.095671 -p -0.207868 0 0.138893 -p -0.176777 0 0.176777 -p -0.138893 0 0.207868 -p -0.095671 0 0.23097 -p -0.0487726 0 0.245197 -p 0 0 0.25 -p 0.0487726 0 0.245197 -p 0.095671 0 0.23097 -p 0.138893 0 0.207868 -p 0.176777 0 0.176777 -p 0.207868 0 0.138893 -p 0.23097 0 0.095671 -p 0.245197 0 0.0487726 -p 0.25 0 0 -p 0.245197 0 -0.0487726 -p 0.23097 0 -0.095671 -p 0.207868 0 -0.138893 -p 0.176777 0 -0.176777 -p 0.138893 0 -0.207868 -p 0.095671 0 -0.23097 -p 0.0487726 0 -0.245197 -p 0 0 -0.25 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 18 -k 19 -k 20 -k 21 -k 22 -k 23 -k 24 -k 25 -k 26 -k 27 -k 28 -k 29 -k 30 -k 31 -k 32 -k 33 -k 34 -k 35 -k 36 -k 37 -k 38 -k 39 -k 40 -k 41 -k 42 -k 43 -k 44 -k 45 -k 46 -k 47 -k 48 -k 49 -k 50 -k 51 -k 52 -k 53 -k 54 -k 55 -k 56 -k 57 -k 58 -k 59 -k 60 -k 61 -k 62 -k 63 -k 64 -k 65 -k 66 -k 67 -k 68 -k 69", } if help: print "################################" print "- Available Control Shape List -" for key in shapeMELs: print key print "################################" return shapeMEL = "%s -n %s" % (shapeMELs[shape], name) rotations = {'x' : [90, 0 , 0], '-x' : [-90, 0 , 0], 'y' : [0, 90, 0], '-y' : [0, -90, 0], 'z' : [0, 0, 90], '-z' : [0, 0, -90], } try: pm.mel.eval(shapeMEL) ctrl = pm.PyNode(name) ctrl.scale.set(size, size, size) if axis: ctrl.rotate.set(rotations[axis]) pm.makeIdentity(ctrl, apply=True, t=True, r=True, s=True) pm.delete(pm.parentConstraint(node, ctrl, mo=False)) if point : pm.pointConstraint(ctrl, node, mo=True, name="%s_tConst"%node.name()) if orient : pm.orientConstraint(ctrl, node, mo=True, name="%s_rConst"%node.name()) if scale : pm.scaleConstraint(ctrl, node, mo=True, name="%s_sConst"%node.name()) return ctrl except Exception as e: pm.warning("error while creating control %s" %e)
def constrain_to_rig(self, nothing): """Constrain the plebe to the mGear rig using constraints """ # Sanity checking if not pm.objExists(self.template.get('root')): pm.warning("Unable to find '{character}' in scene! ".format( character=self.template.get('root') ), "Check that you have the correct template selected") return False if not pm.objExists('global_C0_ctl'): pm.warning("You need to build the rig first!") return False warnings = False for pairs in self.template.get('joints'): for source, target in pairs.items(): if not pm.objExists(target.get('joint')): warnings = True pm.warning("Joint '{joint}' not found, so it won't be " "connected to the rig.".format( joint=target.get('joint') ) ) continue self.clear_transforms(target.get('joint')) if target.get('constrain')[0] == "1" and target.get('constrain')[1] == "1": pm.parentConstraint( source, target.get('joint'), maintainOffset=True, decompRotationToChild=True ) elif target.get('constrain')[0] == "1": pm.pointConstraint( source, target.get('joint'), maintainOffset=True ) elif target.get('constrain')[1] == "1": pm.orientConstraint( source, target.get('joint'), maintainOffset=True ) if target.get('constrain')[2] == "1": pm.scaleConstraint( source, target.get('joint'), maintainOffset=True ) pm.displayInfo("Done attaching the character to the rig") if warnings: pm.warning("Some joints failed to attach to the rig. " "See the script editor for details!")
def __finalizeFkChain(self): #set up control hierarchy reversedList = list(self.controlsArray) reversedList.reverse() for i in range(len(reversedList)): if i != (len(reversedList)-1):#if not the last control pm.parent (reversedList[i].controlGrp, reversedList[i+1].control) #orientConstraint the bone to the controls for i, c in enumerate(self.controlsArray): pm.orientConstraint(c.control, self.chain[i], mo = 1)
def generateClavCtrls(self): self.l_clav_ctrl = self.generateAlignedControl('l', self.l_armJoints[0], 'clav') pm.orientConstraint(self.l_clav_ctrl, self.l_armJoints[0]) self.r_clav_ctrl = self.generateAlignedControl('r', self.r_armJoints[0], 'clav') pm.orientConstraint(self.r_clav_ctrl, self.r_armJoints[0]) pm.parent(self.l_clav_ctrl[0].getParent(), self.shoulder_ctrl) pm.parent(self.r_clav_ctrl[0].getParent(), self.shoulder_ctrl)
def build(target, spaceName, spaceContainer, rotateTarget, control, space): if not spaceName: spaceName = pdil.simpleName(target) + '_' + pdil.simpleName( rotateTarget) + '_follow' trueTarget = group(em=True, name=pdil.simpleName(target, '{0}_dualFollow'), p=spaceContainer) pdil.dagObj.matchTo(trueTarget, control) pointConstraint(target, rotateTarget, trueTarget, mo=True) orientConstraint(target, rotateTarget, trueTarget, mo=True) return trueTarget, spaceName
def add_space(target, prefix): pin = pm.spaceLocator(name=prefix + "_space_pin") pin.visibility.set(0) pm.delete(pm.parentConstraint(target, pin, mo=False)) grp = pm.group(empty=True, name=prefix + "_space") pm.parent(pin, target, r=True) pm.pointConstraint(pin, grp, mo=0, name=grp.name() + "_tConst") pm.orientConstraint(pin, grp, mo=0, name=grp.name() + "_rConst") return grp
def unique_spine_zero_controller(self): # Create Root Costrain Jnt Unde Hip cotrol # Duplicate zero Jnt tempConst = pm.duplicate(self.joints.zeroJoint, po=True, name=("Const_" + self.joints.zeroJoint )) rootConst_jnt = tempConst[0] pm.parent(rootConst_jnt, self.hipCtrl.drawnNode) pm.pointConstraint(rootConst_jnt, self.joints.zeroJoint) pm.orientConstraint(rootConst_jnt, self.joints.zeroJoint) pm.setAttr(rootConst_jnt.visibility, 0) self._stuff.append(rootConst_jnt)
def __finalizeFkChainOriCnst(self): reversedList = list(self.controlsArray) reversedList.reverse() for i in range(len(reversedList)): if i != (len(reversedList)-1): pm.parent(reversedList[i].controlGrp,reversedList[i+1].control) #orient cnst for i,c in enumerate(self.controlsArray): pm.orientConstraint(c.control,self.chain[i],mo = 1) if self.pointCnst == 1: pm.pointConstraint(c.control,self.chain[i],mo = 1)
def createFootIkBoundJointsConstraints(self): pm.select(cl = True) #Create Constratints #---------------------------------------------------- #foot_ik_bound_j_base pm.orientConstraint(self.foot_ik_base_j_base, self.foot_ik_bound_j_base, mo = True) pm.select(cl = True) #foot_ik_bound_j_2_orientCon self.foot_ik_bound_j_2_orientCon = pm.orientConstraint(self.foot_ik_base_j_2, self.foot_ik_tip_j_2, self.foot_ik_bound_j_2, mo = True) pm.select(cl = True) #foot_ik_bound_j_3_orientCon self.foot_ik_bound_j_3_orientCon = pm.orientConstraint(self.foot_ik_base_j_3, self.foot_ik_tip_j_3, self.foot_ik_bound_j_3, mo = True) pm.select(cl = True) #foot_ik_bound_j_4_orientCon self.foot_ik_bound_j_4_orientCon = pm.orientConstraint(self.foot_ik_base_j_4, self.foot_ik_tip_j_4, self.foot_ik_bound_j_4, mo = True) pm.select(cl = True) #foot_ik_bound_j_5_orientCon self.foot_ik_bound_j_5_orientCon = pm.orientConstraint(self.foot_ik_base_j_5, self.foot_ik_tip_j_5, self.foot_ik_bound_j_5, mo = True) pm.select(cl = True) #foot_ik_bound_j_6_orientCon self.foot_ik_bound_j_6_orientCon = pm.orientConstraint(self.foot_ik_base_j_6, self.foot_ik_tip_j_6, self.foot_ik_bound_j_6, mo = True) pm.select(cl = True) #foot_ik_bound_j_tip pm.orientConstraint(self.foot_ik_tip_j_tip, self.foot_ik_bound_j_tip, mo = True) pm.select(cl = True) #Adjust weights #---------------------------------------------------- #foot_ik_bound_j_2_orientCon pm.setAttr(self.foot_ik_bound_j_2_orientCon.name() +'.' + self.foot_ik_tip_j_2.name() + 'W1' , 0.33) #foot_ik_bound_j_3_orientCon pm.setAttr(self.foot_ik_bound_j_3_orientCon.name() +'.' + self.foot_ik_tip_j_3.name() + 'W1' , 0.66) #foot_ik_bound_j_5_orientCon pm.setAttr(self.foot_ik_bound_j_5_orientCon.name() +'.' + self.foot_ik_base_j_5.name() + 'W0' , 0.66) #foot_ik_bound_j_6_orientCon pm.setAttr(self.foot_ik_bound_j_6_orientCon.name() +'.' + self.foot_ik_base_j_6.name() + 'W0' , 0.33) pm.select(cl = True)
def update_offset(con_node, targets): """ Update offset of given constraint. :param con_node: Constraint PyNode. :param targets: List of PyNode targets (constraints can only be edited with a complete list of the original targets). """ if isinstance(con_node, pmc.nodetypes.ParentConstraint): pmc.parentConstraint(targets, con_node, e=True, maintainOffset=True) elif isinstance(con_node, pmc.nodetypes.PointConstraint): pmc.pointConstraint(targets, con_node, e=True, maintainOffset=True) elif isinstance(con_node, pmc.nodetypes.OrientConstraint): pmc.orientConstraint(targets, con_node, e=True, maintainOffset=True) elif isinstance(con_node, pmc.nodetypes.ScaleConstraint): pmc.scaleConstraint(targets, con_node, e=True, maintainOffset=True)
def addHeadShaperOrientConstraint(ctl): # hierarchy ctl_rev = ctl.getParent() ctg = ctl_rev.getParent() hsOffset = pm.group(em=True, n=ctg+'_headShaperOffset') hsOffset.setParent(ctg, r=True) hsOffset | ctl_rev # get targets and weights consAttr = bnd.listAttr(ud=True) consAttr = [attr for attr in consAttr if 'ctrlW' in attr.name()] consWt = [attr.get() for attr in consAttr] consTgt = [pm.PyNode('_'.join(attr.attrName().split('_')[:3])+'_pri_ctrl') for attr in consAttr] # apply orient constraint for tgt, wt in zip(consTgt, consWt): pm.orientConstraint(tgt, hsOffset, mo=True, w=wt)
def __finalizeFkChainOriCnst(self): reversedList = list(self.controlsArray) reversedList.reverse() for i in range(len(reversedList)): if i != (len(reversedList)-1): pm.parent(reversedList[i][0].getParent(),reversedList[i+1][0]) #orient cnst for num,ctrl in enumerate(self.controlsArray): lockAndHideAttr(ctrl[0],["sx","sy","sz"]) pm.orientConstraint(ctrl,self.chain[num],mo = 1) if self.pointCnst == 1: pm.pointConstraint(ctrl,self.chain[num],mo = 1)
def triangle(self, joint): p0 = Point(-1, 0, -0.5) p1 = Point(0, 0, 1) p2 = Point(1, 0, -0.5) points = [p0, p1, p2, p0] pts = [] for point in points: pts.append(point.getPoint()) pm.curve(per = True, d = 1, p = pts, k = [0, 1, 2, 3]) pos = pm.PyNode("%s" % joint).getTranslation() pm.move(pos) pm.pointConstraint(pm.ls(sl = True)[0], joint) pm.orientConstraint("%s" % str(pm.ls(sl = True)[0]), joint)
def create_space(target, space): if not pm.objExists(space + "_space_pin"): pin = pm.group(empty=True, name=space + "_space_pin") else: pin = pm.PyNode(space + "_space_pin") if not pm.objExists(space + "_space"): spaceGrp = pm.group(empty=True, name=space + "_space") pm.pointConstraint(pin, spaceGrp, mo=0, name=spaceGrp.name() + "_tConst") pm.orientConstraint(pin, spaceGrp, mo=0, name=spaceGrp.name() + "_rConst") else: spaceGrp = pm.PyNode(space + "_space") pm.parent(pin, target, r=True) return spaceGrp
def outputOrient(self, constrained=None, maintainOff=None): if constrained is None and maintainOff is None: return self._outputOrient else: self._outputOrient = pm.orientConstraint(constrained, self.drawnNode, mo=maintainOff)
def lock(*args, **kwargs): if args: pm.select(args) sel = pm.ls(sl=True, o=True ) t = kwargs.get('t', True) r = kwargs.get('r', True) locs=[] for item in sel: loc = pm.spaceLocator() loc.rename( 'lock_'+item ) pm.delete( pm.parentConstraint( item, loc) ) if t: skip = [] for attr, axis in zip(['tx','ty','tz'],['x','y','z']): if pm.Attribute( item + '.' + attr).isLocked(): skip.append(axis) const = pm.pointConstraint(loc, item, skip=skip) pm.parent(const, loc) if r: skip = [] for attr, axis in zip(['rx','ry','rz'],['x','y','z']): if pm.Attribute( item + '.' + attr).isLocked(): skip.append(axis) const = pm.orientConstraint(loc, item, skip=skip) pm.parent(const, loc) locs.append( loc ) if sel: pm.select(locs)
def createBoundJointConstraintsAndConnectVisibility(self): pm.select(cl = True) #bound joint constraint list self.boundJointConstraintList = [] #iterate bound joint list and create orient constraint for each for index in range(len(self.boundJointsList)): pm.select(cl = True) self.boundJointConstraintList.append(pm.orientConstraint(self.ikSplineJointsList[index], self.ikDynamicJointsList[index], self.boundJointsList[index], mo = True)) pm.select(cl = True) #create reverse node self.orientConstraintWeight_reverse = pm.createNode('reverse') pm.select(cl = True) #connect to manip dynamic blend self.manip_dynamic.manualDynamicBlend >> self.orientConstraintWeight_reverse.inputX pm.select(cl = True) #Connect Constraints to manip_dynamic for index in range(len(self.boundJointConstraintList)): pm.select(cl = True) pm.connectAttr(self.orientConstraintWeight_reverse.outputX, self.boundJointConstraintList[index].name() +'.' +self.ikSplineJointsList[index].name() +'W0', f = True) pm.connectAttr(self.manip_dynamic.manualDynamicBlend, self.boundJointConstraintList[index].name() +'.' +self.ikDynamicJointsList[index].name() +'W1', f = True) pm.select(cl = True) #Visibility self.orientConstraintWeight_reverse.outputX >> self.manipIkSplineTopGrp.visibility
def AlignBindNode(self, **kws): ''' Overwrite the default behaviour: Align the newly made BindNode as required for this bind ''' #Parent the BindNode/UpVector Object to the upVectorParent Node #Parent the AimLocator Object to the Source node -used to modify the AimPoint pm.parent(self.BindNode['Root'], self.upVectorParent) pm.parent(self.BindNode['Up'], self.upVectorParent) pm.parent(self.BindNode['AimOffset'], self.SourceNode) #self.BindNode['Root'].scale.set(self.Settings.BaseScale,self.Settings.BaseScale,self.Settings.BaseScale) self.BindNode['Main'].rotateOrder.set(self.SourceNode.rotateOrder.get()) self.BindNode['Root'].rotateOrder.set(self.DestinationNode.rotateOrder.get()) #Aim Alignment pm.aimConstraint(self.BindNode['AimOffset'], self.BindNode['Root'], aimVector=(0,1,0),upVector=(0,0,1),\ worldUpType="object",worldUpObject=self.BindNode['Up']) #Positional Alignment pm.delete(pm.pointConstraint(self.SourceNode, self.BindNode['AimOffset'])) pm.makeIdentity(self.BindNode['AimOffset'], apply=True, t=1, r=1, s=0) pm.delete(pm.pointConstraint(self.upVectorParent, self.BindNode['Root'])) pm.makeIdentity(self.BindNode['Root'], apply=True, t=1, r=0, s=0) pm.delete(pm.pointConstraint(self.upVectorParent, self.BindNode['Up'])) pm.makeIdentity(self.BindNode['Up'], apply=True, t=1, r=0, s=0) pm.delete(pm.pointConstraint(self.DestinationNode, self.BindNode['Root'])) #Rotate Alignment pm.delete(pm.orientConstraint(self.DestinationNode, self.BindNode['Main']))
def LinkBindNode(self): ''' Make the actual driving connections between the Bind and Destination Nodes ''' maintainOffsets = False # Make the Bind Between the Object # if BindTrans and BindRots: # try: # con=pm.parentConstraint(self.BindNode['Main'], self.DestinationNode, mo=maintainOffsets) # con.interpType.set(2) # except: # raise StandardError('ParentConstraint Bind could not be made') if self.Settings.BindTrans: try: pm.pointConstraint(self.BindNode['Main'], self.DestinationNode, mo=maintainOffsets) except: pass if self.Settings.BindRots: try: con = pm.orientConstraint(self.BindNode['Main'], self.DestinationNode, mo=maintainOffsets) con.interpType.set(2) except: pass #Add the BindMarkers so that we can ID these nodes and connections later self.AddBindMarkers(self.DestinationNode, self.BindNode['Root'])
def CreateFKControl(self, _joint, _parent, _moduleContainer): jointName = utils.StripAllNamespaces(_joint)[1] containedNodes = [] name = "%s_fkControl" %jointName controlObjectInstance = controlObject.ControlObject() fkControlInfo = controlObjectInstance.Create(name, "sphere.ma", self, _lod = 1, _translation = False, _rotation = True, _globalScale = False, _spaceSwitching = False) fkControl = fkControlInfo[0] pm.connectAttr("%s.rotateOrder" %_joint, "%s.rotateOrder" %fkControl) orientGrp = pm.group(name = "%s_orientGrp", empty = True, parent = _parent) containedNodes.append(orientGrp) pm.delete(pm.parentConstraint(_joint, orientGrp, maintainOffset = False)) jointParent = pm.listRelatives(_joint, parent = True)[0] orientGrp_parentConstraint = pm.parentConstraint(jointParent, orientGrp, maintainOffset = True, name = "%s_parentConstraint" %orientGrp) orientGrp_scaleConstraint = pm.scaleConstraint(jointParent, orientGrp, maintainOffset = True, name = "%s_scaleConstraint" %orientGrp) pm.parent(fkControl, orientGrp, relative = True) orientConstraint = pm.orientConstraint(fkControl, _joint, maintainOffset = False, name = "%s_orientConstraint" %_joint) containedNodes.extend([orientGrp_parentConstraint, orientGrp_scaleConstraint, orientConstraint]) utils.AddNodeToContainer(_moduleContainer, containedNodes) return fkControl
def placeJoint(position,name='joint',parent=None): joint = pm.joint(name=name, position=(0,0,0)) joint.setTranslation(position, 'world') if parent: pm.delete(pm.orientConstraint(parent,joint)) joint.setParent(parent) return joint