def d(self): # Tool To create the measurement tool when vertexes are selected if self.getType(0) == 'vertex': locators = cmds.ls(type='locator') distances = cmds.ls(type='distanceDimShape') cmds.distanceDimension( startPoint=cmds.pointPosition(self.getSelection()[0]), endPoint=cmds.pointPosition(self.getSelection()[1])) newLocators = set(cmds.ls(type='locator')) - set(locators) newDistances = set( cmds.ls(type='distanceDimShape')) - set(distances) if len(newLocators) == 2: cmds.group(list(newLocators)[0], list(newLocators)[1], list(newDistances)[0], n='measurement') elif len(newLocators) == 1: cmds.group(list(newLocators)[0], list(newDistances)[0], n='measurement') elif self.getType(0) == 'face': cmds.polySubdivideFacet(sbm=1) #starts it off in linear form self.smoothTool() ##elif self.getType(0) == 'mesh': ## self.smoothTool() self.updateToolHUD()
def makeIKWrist(*Args): cm.rename(cm.ls(sl=True), 'R_wrist_IK_CTRL') cm.select('R_wrist_IK_CTRL', 'R_arm_IK_HDL') maya.mel.eval('doCreateParentConstraintArgList 1 { "1","0","0","0","0","0","0","1","","1" };') cm.select('R_wrist_IK_CTRL', 'R_arm_IK_JNT_04') maya.mel.eval('doCreateOrientConstraintArgList 1 { "1","0","0","0","0","0","0","1","","1" };') #maya.mel.eval('setAttr -lock true -keyable false -channelBox false "R_wrist_IK_CTRL.sx";') #maya.mel.eval('setAttr -lock true -keyable false -channelBox false "R_wrist_IK_CTRL.sy";') #maya.mel.eval('setAttr -lock true -keyable false -channelBox false "R_wrist_IK_CTRL.sz";') cm.setAttr('R_wrist_IK_CTRL.sx', lock=True, keyable=False, channelBox=False) cm.setAttr('R_wrist_IK_CTRL.sy', lock=True, keyable=False, channelBox=False) cm.setAttr('R_wrist_IK_CTRL.sz', lock=True, keyable=False, channelBox=False) piv1 = cm.xform('R_arm_IK_JNT_01', q=True, t=True, ws=True) piv3 = cm.xform('R_arm_IK_JNT_04', q=True, t=True, ws=True) cm.distanceDimension(ep=(piv3[0],piv3[1],piv3[2]), sp=(piv1[0],piv1[1], piv1[2])) cm.rename('locator2', 'R_arm_Dictance_LOC') cm.rename('distanceDimensionShape1', 'R_arm_Distance') cm.parent('R_arm_Dictance_LOC', 'R_wrist_IK_CTRL') originalDistance = cm.getAttr('R_arm_Distance.distance') cm.createNode('multiplyDivide', n='R_arm_stretchRatio_Calculator') #cm.connectAttr('R_arm_Distance.distance', 'R_arm_stretchRatio_Calculator.input1.input1X') cm.setAttr('R_arm_stretchRatio_Calculator.input2.input2X', originalDistance) cm.setAttr('R_arm_stretchRatio_Calculator.operation', 2) cm.createNode('condition', n='Condition_distance_greaterThanOrig') cm.setAttr('Condition_distance_greaterThanOrig.secondTerm', originalDistance) cm.connectAttr('R_arm_Distance.distance', 'Condition_distance_greaterThanOrig.firstTerm') cm.setAttr('Condition_distance_greaterThanOrig.operation', 2) cm.setAttr('Condition_distance_greaterThanOrig.colorIfFalseR', originalDistance) cm.connectAttr('R_arm_Distance.distance', 'Condition_distance_greaterThanOrig.colorIfTrueR') cm.connectAttr('Condition_distance_greaterThanOrig.outColor', 'R_arm_stretchRatio_Calculator.input1') #cm.connectAttr('Condition_distance_greaterThanOrig.colorIfTrueR', 'R_arm_stretchRatio_Calculator.input1.input1X') #cm.connectAttr('Condition_distance_greaterThanOrig.colorIfFalseR', 'R_arm_stretchRatio_Calculator.input1.input1X') for i in range(1,4): cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_FK_JNT_0'+str(i)+'.scale.scaleX') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_FK_JNT_0'+str(i)+'.scale.scaleY') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_FK_JNT_0'+str(i)+'.scale.scaleZ') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_IK_JNT_0'+str(i)+'.scale.scaleX') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_IK_JNT_0'+str(i)+'.scale.scaleY') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_IK_JNT_0'+str(i)+'.scale.scaleZ') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_result_JNT_0'+str(i)+'.scale.scaleX') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_result_JNT_0'+str(i)+'.scale.scaleY') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_result_JNT_0'+str(i)+'.scale.scaleZ') print originalDistance print 'IK Wrist complete.'
def buildDistance(name = '', side = ''): compName = "{name}_{side}".format(**locals()) cmds.distanceDimension(startPoint = (5, 5, 5), endPoint = (6, 6, 6)) distanceName = '{compName}_DDM'.format(**locals()) startName = '{compName}_start_DDM_LOC'.format(**locals()) endName = '{compName}_end_DDM_LOC'.format(**locals()) cmds.rename('distanceDimension1', distanceName) cmds.rename('locator1', startName) cmds.rename('locator2', endName) createDefaultMetaData(distanceName, name, side, 'stretchDistance') createDefaultMetaData(startName, name, side, 'stretchStart') createDefaultMetaData(endName, name, side, 'stretchEnd') return distanceName, startName, endName
def createDistanceNodeBetweenObjects (obj1,obj2): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Creates a distance node between objects ARGUMENTS: obj1(string) obj2(string) RETURNS: none >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ """ Creates a distance node between objects """ pos1 = returnWorldSpacePosition (obj1) pos2 = returnWorldSpacePosition (obj2) tmp = mc.distanceDimension( sp=pos1, ep=pos2 ) distBuffer = mc.listRelatives ( [tmp], p=True) distanceObj = mc.rename (distBuffer, (obj1+'_to_'+obj2+'_distMeas') ) #return the stupid locators it makes so we can connect our own stuff distanceStartPoint = (distanceObj+'Shape.startPoint') distanceEndPoint = (distanceObj+'Shape.endPoint') locAttr1connection = (mc.connectionInfo (distanceStartPoint,sourceFromDestination=True)) locAttr2connection = (mc.connectionInfo (distanceEndPoint,sourceFromDestination=True)) locAttr1Stripped = '.'.join(locAttr1connection.split('.')[0:-1]) locAttr2Stripped = '.'.join(locAttr2connection.split('.')[0:-1]) loc1Buffer = (mc.listRelatives (locAttr1Stripped,parent=True)) loc2Buffer = (mc.listRelatives (locAttr2Stripped,parent=True)) #distObj1 = mc.rename (loc1Buffer, (obj1+'_distLoc') ) #distObj2 = mc.rename (loc2Buffer, (obj2+'_distLoc') ) return distanceObj
def disBetweenTwoObjNode(): global locator target = mc.ls(sl=True,tr=True) if(len(target)!=2): mc.warning("Choose Two Point or Object") else: sourceBB = mc.xform(target[0],q=True,bb=True) srcBBCenter = [(sourceBB[0]+sourceBB[3])/2,(sourceBB[1]+sourceBB[4])/2,(sourceBB[2]+sourceBB[5])/2] targetBB = mc.xform(target[1],q=True,bb=True) tarBBCenter = [(targetBB[0]+targetBB[3])/2,(targetBB[1]+targetBB[4])/2,(targetBB[2]+targetBB[5])/2] sourceLocator = mc.spaceLocator() locator.append(sourceLocator[0]) targetLocator = mc.spaceLocator() locator.append(targetLocator[0]) mc.xform(sourceLocator[0],ws=True,t=srcBBCenter) mc.xform(targetLocator[0],ws=True,t=tarBBCenter) mc.select(sourceLocator[0],targetLocator[0]) distanceNode = mc.distanceDimension( sp = srcBBCenter , ep = tarBBCenter) mc.select(target[0],sourceLocator[0]) mel.eval('doCreatePointConstraintArgList 1 { "0","0","0","0","0","0","0","1","","1" };') mc.select(clear = True) mc.select(target[1],targetLocator[0]) mel.eval('doCreatePointConstraintArgList 1 { "0","0","0","0","0","0","0","1","","1" };') mc.select(clear = True)
def LocDisNode(self): spVal = dt.getXform(self.obj1,1) epVal = dt.getXform(self.obj2,1) disNode = cmds.distanceDimension(sp = (spVal.Xval),ep = (epVal.Xval)) disNodeparent = cmds.rename((dt.findParent(disNode).parent),(self.obj1+'_disNode')) disNode = (disNodeparent+'Shape') spEdLoc = cmds.listConnections(disNode,d=1) spEdLoc[0] = cmds.rename(spEdLoc[0],(self.obj1+'_disLoc')) spEdLoc[1] = cmds.rename(spEdLoc[1],(self.obj2+'_disLoc')) ApplyConstrain(self.obj1,spEdLoc[0]).pointCon(0) ApplyConstrain(self.obj2,spEdLoc[1]).pointCon(0) Val = cmds.getAttr(disNode+'.distance') #passing overall length if needed(needed for 2b,3b chain joints) if self.lenght != None: Val = self.lenght self.mdnConnector((disNode+'.distance'), Val) #cmds.connectAttr((disNode+'.distance'),(self.con+'.firstTerm'),f=1) cmds.connectAttr((self.mdnG+'.outputX'),(self.con+'.firstTerm'),f=1) cmds.connectAttr((self.mdnG+'.outputX'),(self.mdn+'.input1X'),f=1) cmds.setAttr(self.con+'.secondTerm',Val) if(self.gCtrl): self.globalScaleConnector(self.gCtrl) #Housekeeping perG = cmds.group( em=True, name= (disNodeparent+'_g')) cmds.parent(spEdLoc,disNodeparent,perG) return self.con
def measure(start_point, end_point): """ Create measure distance between to objects @param start_point: str or list(str), where the measure tool should start from @param end_point: str or list(str), where the measure tool should end @return: str, newly created locator """ if type(start_point) is list: start_point = start_point[0] if type(end_point) is list: end_point = end_point[0] dist = mc.distanceDimension(sp=(0, 0, 0), ep=(1, 1, 1)) sp = mc.listRelatives(start_point, shapes=True)[0] ep = mc.listRelatives(end_point, shapes=True)[0] mc.connectAttr(sp + '.worldPosition', dist + '.startPoint', f=True) mc.connectAttr(ep + '.worldPosition', dist + '.endPoint', f=True) if mc.objExists('locator1'): mc.delete('locator1') if mc.objExists('locator2'): mc.delete('locator2') new_dist_name = mc.rename( mc.listRelatives(dist, shapes=True), str(start_point) + '_to_' + str(end_point) + '_dist') return new_dist_name
def disBetweenTwoVtxNode(): global locator target = mc.ls(sl=True,fl=True) if(len(target)!=2): mc.warning("Choose Two Point or Object") else: sourcePos = mc.xform(target[0],q=True,ws=True,t=True) targetPos = mc.xform(target[1],q=True,ws=True,t=True) sourceLocator = mc.spaceLocator() locator.append(sourceLocator[0]) targetLocator = mc.spaceLocator() locator.append(targetLocator[0]) mc.xform(sourceLocator[0],ws=True,t=sourcePos) mc.xform(targetLocator[0],ws=True,t=targetPos) mc.select(sourceLocator[0],targetLocator[0]) distanceNode = mc.distanceDimension( sp = sourcePos , ep = targetPos ) mc.select(clear=True) mc.select(target[0],sourceLocator[0]) mel.eval('doCreatePointOnPolyConstraintArgList 2 { "0" ,"0" ,"0" ,"1" ,"" ,"1" ,"0" ,"0" ,"0" ,"0" };') mc.select(clear=True) mc.select(target[1],targetLocator[0]) mel.eval('doCreatePointOnPolyConstraintArgList 2 { "0" ,"0" ,"0" ,"1" ,"" ,"1" ,"0" ,"0" ,"0" ,"0" };')
def createDistanceDimensionNode(startLoc, endLoc, lenNodeName, toHide=False): distDimShape = mc.distanceDimension(sp=(0, 0, 0), ep=(0, 0, 0)) mc.connectAttr("{0}.worldPosition".format(startLoc), "{0}.startPoint".format(distDimShape), f=True) mc.connectAttr("{0}.worldPosition".format(endLoc), "{0}.endPoint".format(distDimShape), f=True) distDimParent = mc.listRelatives(distDimShape, p=True) mc.rename(distDimParent, lenNodeName) lenNodeNameShape = mc.listRelatives(lenNodeName, s=True)[0] if toHide: mc.setAttr("{0}.visibility".format(startLoc), False) mc.setAttr("{0}.visibility".format(endLoc), False) mc.setAttr("{0}.visibility".format(lenNodeName), False) toDelete = mc.ls('locator*', type="transform") mc.delete( toDelete ) # we shouldn't have any extra locators at this point, but the distance node automatically creates one return lenNodeNameShape
def getDistance(startObj, endObj): startLoc = "toDeleteStart" endLoc = "toDeleteEnd" mc.spaceLocator(n=startLoc, p=(0, 0, 0)) mc.spaceLocator(n=endLoc, p=(0, 0, 0)) mc.matchTransform(startLoc, startObj, pos=True) mc.matchTransform(endLoc, endObj, pos=True) lenNodeName = "toDelete" distDimShape = mc.distanceDimension(sp=(0, 0, 0), ep=(0, 0, 0)) mc.connectAttr("{0}.worldPosition".format(startLoc), "{0}.startPoint".format(distDimShape), f=True) mc.connectAttr("{0}.worldPosition".format(endLoc), "{0}.endPoint".format(distDimShape), f=True) distDimParent = mc.listRelatives(distDimShape, p=True) mc.rename(distDimParent, lenNodeName) lenNodeNameShape = mc.listRelatives(lenNodeName, s=True)[0] dist = mc.getAttr("{0}.distance".format(lenNodeNameShape)) mc.delete(lenNodeName, startLoc, endLoc) toDelete = mc.ls('locator*', type="transform") mc.delete( toDelete ) # we shouldn't have any extra locators at this point, but the distance node automatically creates one return dist
def createDistanceNodeBetweenObjects (obj1,obj2): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Creates a distance node between objects ARGUMENTS: obj1(string) obj2(string) RETURNS: none >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ """ Creates a distance node between objects """ pos1 = returnWorldSpacePosition (obj1) pos2 = returnWorldSpacePosition (obj2) tmp = mc.distanceDimension( sp=pos1, ep=pos2 ) distBuffer = mc.listRelatives ( [tmp], p=True) distanceObj = mc.rename (distBuffer, (obj1+'_to_'+obj2+'_distMeas') ) #return the stupid locators it makes so we can connect our own stuff distanceStartPoint = (distanceObj+'Shape.startPoint') distanceEndPoint = (distanceObj+'Shape.endPoint') locAttr1connection = (mc.connectionInfo (distanceStartPoint,sourceFromDestination=True)) locAttr2connection = (mc.connectionInfo (distanceEndPoint,sourceFromDestination=True)) locAttr1Stripped = '.'.join(locAttr1connection.split('.')[0:-1]) locAttr2Stripped = '.'.join(locAttr2connection.split('.')[0:-1]) loc1Buffer = (mc.listRelatives (locAttr1Stripped,parent=True)) loc2Buffer = (mc.listRelatives (locAttr2Stripped,parent=True)) distObj1 = mc.rename (loc1Buffer, (obj1+'_distLoc') ) distObj2 = mc.rename (loc2Buffer, (obj2+'_distLoc') )
def setup_dof(target, camera, f_stop): cmds.setAttr(camera + ".depthOfField", 1) # create a locator parented to the camera cam_matrix = cmds.xform(camera, q=True, m=True, ws=True) cam_locator = cmds.spaceLocator() cmds.xform(cam_locator, m=cam_matrix, ws=True) cmds.select(cam_locator, camera, r=True) cmds.parent() # create a locator parented to the target target_matrix = cmds.xform(target, q=True, m=True, ws=True) target_locator = cmds.spaceLocator() cmds.xform(target_locator, m=target_matrix, ws=True) cmds.select(target_locator, target, r=True) cmds.parent() distance_node = cmds.distanceDimension(cam_locator, target_locator) cmds.connectAttr(distance_node + ".distance", camera + ".focusDistance") f_stop_multiplier = 1.0 while f_stop < 1.0: f_stop *= 2.0 f_stop_multiplier /= 2.0 cmds.setAttr(camera + ".fStop", f_stop) cmds.setAttr(camera + ".focusRegionScale", f_stop_multiplier)
def d (self): # Tool To create the measurement tool when vertexes are selected if self.getType(0) == 'vertex': locators = cmds.ls(type = 'locator') distances = cmds.ls(type = 'distanceDimShape') cmds.distanceDimension(startPoint = cmds.pointPosition( self.getSelection()[0]) ,endPoint= cmds.pointPosition( self.getSelection()[1] )) newLocators = set(cmds.ls(type='locator')) - set(locators) newDistances = set(cmds.ls(type='distanceDimShape')) - set(distances) if len(newLocators) == 2: cmds.group(list(newLocators)[0], list(newLocators)[1] , list(newDistances)[0], n = 'measurement') elif len(newLocators) == 1: cmds.group(list(newLocators)[0], list(newDistances)[0], n = 'measurement') elif self.getType(0) == 'face': cmds.polySubdivideFacet(sbm=1) #starts it off in linear form self.smoothTool() ##elif self.getType(0) == 'mesh': ## self.smoothTool() self.updateToolHUD()
def add_measurement(self): # add length segment hip_pos = cmds.xform(self.jnt_list[0], q=1, ws=1, t=1) knee_pos = cmds.xform(self.jnt_list[1], q=1, ws=1, t=1) ankle_pos = cmds.xform(self.jnt_list[2], q=1, ws=1, t=1) foot_pos = cmds.xform(self.jnt_list[3], q=1, ws=1, t=1) straighten_len = ((knee_pos[0]-ankle_pos[0]) ** 2+(knee_pos[1]-ankle_pos[1]) ** 2+(knee_pos[2]-ankle_pos[2]) ** 2) ** 0.5+ \ ((foot_pos[0]-ankle_pos[0]) ** 2+(foot_pos[1]-ankle_pos[1]) ** 2+(foot_pos[2]-ankle_pos[2]) ** 2) ** 0.5+ \ ((hip_pos[0]-knee_pos[0]) ** 2+(hip_pos[1]-knee_pos[1]) ** 2+(hip_pos[2]-knee_pos[2]) ** 2) ** 0.5 # create measurement measure_shape = cmds.distanceDimension(sp=hip_pos, ep=foot_pos) locs = cmds.listConnections(measure_shape) measure_node = cmds.listRelatives(measure_shape, parent=1, type='transform') length_node = '{}length_node'.format(self.name) hip_loc = '{}hip_node'.format(self.name) ankle_loc = '{}ankle_node'.format(self.name) cmds.rename(measure_node, length_node) cmds.rename(locs[0], hip_loc) cmds.rename(locs[1], ankle_loc) stretch_node = cmds.shadingNode('multiplyDivide', asUtility=1, name='{}stretch_node'.format( self.name)) cmds.setAttr(stretch_node + '.operation', 2) cmds.setAttr(stretch_node + '.input2X', straighten_len) cmds.connectAttr(length_node + '.distance', stretch_node + '.input1X') condition_node = cmds.shadingNode('condition', asUtility=1, name='{}condition_node'.format( self.name)) cmds.connectAttr(stretch_node + '.outputX', condition_node + '.firstTerm') cmds.setAttr(condition_node + '.secondTerm', 1) cmds.setAttr(condition_node + '.operation', 2) # greater than cmds.connectAttr(stretch_node + '.outputX', condition_node + '.colorIf1R') cmds.setAttr(condition_node + '.colorIfFalseR', 1) for joint in [ self.jnt_list[0], self.jnt_list[1], self.jnt_list[2], self.jnt_helper_list[0], self.jnt_helper_list[1], self.jnt_helper_list[2] ]: cmds.connectAttr(condition_node + '.outColorR', joint + '.scaleX') cmds.setAttr(length_node + '.visibility', 0) cmds.setAttr(hip_loc + '.visibility', 0) cmds.setAttr(ankle_loc + '.visibility', 0) outliner.batch_parent([length_node, hip_loc, ankle_loc], self.ctrl_grp) cmds.parentConstraint(self.ctrl_list[0], hip_loc) cmds.parentConstraint(self.ctrl_list[3], ankle_loc, mo=1)
def measureWheelDistance(wheel, dist1, dist2): '''Distance node to find wheel diameter.''' name = '{}_{}_DIST'.format(utils.side(wheel), utils.description(wheel)) distance = cmds.distanceDimension(startPoint=dist1, endPoint=dist2) distance = cmds.rename('distanceDimension1', name) # returns dynamic distance node, driven by baseLocators() return distance
def distance_node(self, start, end): """Creates a distance node and returns all the nodes involved in the distance node, the distance node and the start and end locators. Creates the distance node at remote location to prevent from hitting existing locators. @param start: the start point @param end: the end point @type start: list @type end: list @return: the distance node and the start and end locators """ cmds.distanceDimension(sp=[9998, 9998, 9998], ep=[9999, 9999, 9999]) dist = cmds.ls(sl=True)[1] start_loc = cmds.listConnections('%s.startPoint' % dist)[0] end_loc = cmds.listConnections('%s.endPoint' % dist)[0] cmds.xform(start_loc, ws=True, t=start) cmds.xform(end_loc, ws=True, t=end) return dist, start_loc, end_loc
def BuildSnappableKnee(self): # distance Thigh_To_Pole self.Thigh_To_Pole = cmds.distanceDimension(sp=self.StartPos, ep=self.polePos) self.Thigh_To_PoleDistanceObjs = cmds.listConnections( self.Thigh_To_Pole, destination=False) cmds.rename(self.Thigh_To_Pole, "Thigh_To_Pole_Distance") self.Thigh_To_Pole = "Thigh_To_Pole_Distance" Thigh_To_Pole_Distance_Parent = cmds.listRelatives(self.Thigh_To_Pole, parent=True) cmds.rename(Thigh_To_Pole_Distance_Parent, "Thigh_To_Pole_Dis_Trans") # distance Pole_To_Foot self.Pole_To_Foot = cmds.distanceDimension(sp=self.polePos, ep=self.EndPos) self.Pole_To_FootDistanceObjs = cmds.listConnections(self.Pole_To_Foot, destination=False) cmds.rename(self.Pole_To_Foot, "Pole_To_Foot_Distance") self.Pole_To_Foot = "Pole_To_Foot_Distance" Pole_To_Foot_Distance_Parent = cmds.listRelatives(self.Pole_To_Foot, parent=True) cmds.rename(Pole_To_Foot_Distance_Parent, "Pole_To_Foot_Dis_Trans") # Stretch to polyvector # todo:修改骨骼链 if self.isNoFilpKneeEnable: # 如果开启的话,是需要放到 pv 的骨骼链 cmds.connectAttr('%s.%s' % ("distance", self.Thigh_To_Pole), '%s.translateX' % BlendNode, f=True) cmds.connectAttr('%s.%s' % ("distance", self.Pole_To_Foot), '%s.translateX' % BlendNode, f=True) else: # 如果没有开启的话,是放到 ik 的骨骼链 cmds.connectAttr('%s.%s' % ("distance", self.Thigh_To_Pole), '%s.translateX' % BlendNode, f=True) cmds.connectAttr('%s.%s' % ("distance", self.Pole_To_Foot), '%s.translateX' % BlendNode, f=True) pass
def add_measurement(self): # add length segment shoulder_pos = cmds.xform(self.jnt_list[0], q=1, ws=1, t=1) elbow_pos = cmds.xform(self.jnt_list[1], q=1, ws=1, t=1) wrist_pos = cmds.xform(self.jnt_list[2], q=1, ws=1, t=1) straighten_len = ((shoulder_pos[0]-elbow_pos[0]) ** 2+(shoulder_pos[1]-elbow_pos[1]) ** 2+(shoulder_pos[2]-elbow_pos[2]) ** 2) ** 0.5+ \ ((wrist_pos[0]-elbow_pos[0]) ** 2+(wrist_pos[1]-elbow_pos[1]) ** 2+(wrist_pos[2]-elbow_pos[2]) ** 2) ** 0.5 # create measurement measure_shape = cmds.distanceDimension(sp=shoulder_pos, ep=wrist_pos) locs = cmds.listConnections(measure_shape) measure_node = cmds.listRelatives(measure_shape, parent=1, type='transform') length_node = '{}length_node'.format(self.name) shoulder_loc = '{}shoulder_node'.format(self.name) elbow_loc = '{}elbow_node'.format(self.name) cmds.rename(measure_node, length_node) cmds.rename(locs[0], shoulder_loc) cmds.rename(locs[1], elbow_loc) stretch_node = cmds.shadingNode('multiplyDivide', asUtility=1, name='{}stretch_node'.format( self.name)) cmds.setAttr(stretch_node + '.operation', 2) cmds.setAttr(stretch_node + '.input2X', straighten_len) cmds.connectAttr(length_node + '.distance', stretch_node + '.input1X') condition_node = cmds.shadingNode('condition', asUtility=1, name='{}condition_node'.format( self.name)) cmds.connectAttr(stretch_node + '.outputX', condition_node + '.firstTerm') cmds.setAttr(condition_node + '.secondTerm', 1) cmds.setAttr(condition_node + '.operation', 2) # Greater than cmds.connectAttr(stretch_node + '.outputX', condition_node + '.colorIf1R') cmds.setAttr(condition_node + '.colorIfFalseR', 1) cmds.connectAttr(condition_node + '.outColorR', self.jnt_list[0] + '.scaleX') cmds.connectAttr(condition_node + '.outColorR', self.jnt_list[1] + '.scaleX') cmds.setAttr(length_node + '.visibility', 0) cmds.setAttr(shoulder_loc + '.visibility', 0) cmds.setAttr(elbow_loc + '.visibility', 0) outliner.batch_parent([length_node, shoulder_loc, elbow_loc], self.ctrl_grp) cmds.parentConstraint(self.ctrl_list[0], shoulder_loc) cmds.parentConstraint(self.ctrl_list[3], elbow_loc, mo=1)
def create_follow_focus(): sel_nodes = cmds.ls(sl=True) if sel_nodes: for node in sel_nodes: if cmds.nodeType(cmds.listRelatives(node)) == 'camera': cam_shape = cmds.listRelatives(shapes=True) camera_position = cmds.camera(sel_nodes[0], p=True, q=True) camera_position[2] = int(camera_position[2]) - 10 distance_node_shape = cmds.distanceDimension( sp=(0, 0, 456), ep=camera_position) distance_node_loc_cam, distance_node_loc_focal = cmds.listConnections( distance_node_shape) distance_node_loc_cam = cmds.rename(distance_node_loc_cam, sel_nodes[0] + "FFCam_LOC") distance_node_loc_focal = cmds.rename( distance_node_loc_focal, sel_nodes[0] + "FFFocalPt_LOC") distance_node = cmds.rename( cmds.listRelatives(distance_node_shape, p=True), sel_nodes[0] + "FFDistance_DIST") # Set color of the focus plane locator cmds.setAttr(distance_node_loc_focal + ".overrideEnabled", 1) cmds.setAttr(distance_node_loc_focal + ".overrideColor", 18) cmds.parentConstraint(sel_nodes[0], distance_node_loc_cam, maintainOffset=False) cmds.aimConstraint(sel_nodes[0], distance_node_loc_focal, maintainOffset=False) # Lock and hide translation and rotation for cam locator lock_attributes = ['.tx', '.ty', '.tz', '.rx', '.ry', '.rz'] for attr in lock_attributes: cmds.setAttr(distance_node_loc_cam + attr, lock=True, keyable=False, channelBox=False) cmds.group(distance_node_loc_cam, distance_node_loc_focal, distance_node, n=sel_nodes[0] + "FollowFocus_GRP") for shape in cam_shape: cmds.connectAttr(distance_node + '.distance', shape + '.focusDistance') else: cmds.warning("No cameras are selected") else: cmds.warning("Nothing is selected")
def create_ik_stretch(self, alljoints, getbones): getDistances=[] for nextControl, eachControl in enumerate(alljoints[:-1]): current_item = eachControl next_item = alljoints[(nextControl+1)%len(alljoints)] curTran = cmds.xform(current_item, q=True, ws=1, t=True) nextTran = cmds.xform(next_item, q=True, ws=1, t=True) selDistance=cmds.distanceDimension(sp=(curTran[0], curTran[1], curTran[2]), ep=(nextTran[0], nextTran[1], nextTran[2]))#create distance measure getlocs=cmds.listConnections(selDistance) cmds.pointConstraint(current_item,getlocs[0],mo=0, w=1 )#DO NOT PARENT CONSTRAIN. it will create cycle loop. cmds.pointConstraint(next_item,getlocs[1],mo=0, w=1 ) getDist=cmds.getAttr(selDistance+".distance")#get the distance getDistances.append(getDist) cmds.delete(getlocs) fullDistance=sum(getDistances) getIKEffector=cmds.listRelatives(getbones, ad=1, typ="ikEffector")#find effector getIKHandle=cmds.listConnections(getIKEffector[0], d=1, t="ikHandle")#now i can find ikhandle selDistance=cmds.distanceDimension(sp=(0, 0 ,0), ep=(1, 1 ,1))#create distance measure getIKLocators=cmds.listConnections(selDistance)#get the distance locators to point constrain cmds.pointConstraint(getbones,getIKLocators[0],mo=0, w=1 )#DO NOT PARENT CONSTRAIN. it will create cycle loop. cmds.pointConstraint(getIKHandle[0],getIKLocators[1],mo=0, w=1 ) getDistance=cmds.getAttr(selDistance+".distance")#get the distance MultDivNode=cmds.shadingNode( "multiplyDivide", au=1, n=getbones+'_md') ConditionNode=cmds.shadingNode( "condition", au=1, n=getbones+"_cond") cmds.setAttr(str(MultDivNode)+".operation", 2)#change to divide cmds.setAttr(str(ConditionNode)+".operation", 2)#change to greater than cmds.connectAttr(selDistance+".distance", MultDivNode+".input1.input1"+scaleAxis, f=1)#set default length on input of divide cmds.connectAttr(selDistance+".distance", ConditionNode+".firstTerm", f=1)#set default on first term when greater than cmds.connectAttr(MultDivNode+".output.output"+scaleAxis, ConditionNode+".colorIfTrue.colorIfTrueR", f=1)#divide outputscaleX to color is greater than cmds.setAttr(ConditionNode+".secondTerm", fullDistance)#set default length on second term of greaterThan cmds.setAttr(MultDivNode+".input2"+scaleAxis, fullDistance)#set default length on second input of divide cmds.rename(getIKLocators[0], getbones+'_bdloc') cmds.rename(getIKLocators[1], getbones+'_edloc') getpartransform=cmds.listRelatives(selDistance, ap=1, typ="transform") cmds.rename(getpartransform[0], getbones+'_dis') for each in alljoints[1:]: cmds.connectAttr(ConditionNode+".outColor.outColorR",each+".scale.scale"+scaleAxis, f=1)#set divide on scale X of each bone except for last bone conditionNode=str(ConditionNode)+".operation" return conditionNode
def makeDistance(name='distance', suffixStart='start', suffixEnd='end'): cmds.select(cl=True) dShape = cmds.distanceDimension(sp=(-100, -100, -100), ep=(-100, -99, -100)) dNode_raw = util.nameReformat(cmds.listRelatives(dShape, p=True)) startLoc_raw = util.findFromAttr(dShape, 'startPoint', fromSource=True) endLoc_raw = util.findFromAttr(dShape, 'endPoint', fromSource=True) dNode = cmds.rename(dNode_raw, util.getUniqueName(name)) startLoc = cmds.rename( startLoc_raw, util.getUniqueName('{0}_{1}'.format(name, suffixStart))) endLoc = cmds.rename(endLoc_raw, util.getUniqueName('{0}_{1}'.format(name, suffixEnd))) return dNode, startLoc, endLoc
def distToClosestPoint(mySphere, myLocator): obj, dag = dagObjFromName(mySphere) meshFn = om2.MFnMesh(dag) point = locatorToPoint(myLocator) locpos = cmds.xform(myLocator, q=1, rp=1, ws=1) resultPoint = meshFn.getClosestPoint(point, om2.MSpace.kWorld)[0] resultPos = [resultPoint[0], resultPoint[1], resultPoint[2]] space = cmds.distanceDimension(sp=locpos, ep=resultPos) dis = cmds.getAttr("distanceDimension1" + ".distance") cmds.delete("distanceDimension1") if cmds.objExists("locator1"): cmds.delete("locator1") return dis
def divineJoint(): locList = cmds.ls(sl=True) parentLOC = locList[0] childLOC = locList[1] sel_sLOC = cmds.xform(parentLOC, q=True, t=True) sel_eLOC = cmds.xform(childLOC, q=True, t=True) distMaker = cmds.distanceDimension(sp=(sel_sLOC[0], sel_sLOC[1], sel_sLOC[2]), ep=(sel_eLOC[0], sel_eLOC[1], sel_eLOC[2])) cmds.rename(distMaker, 'distance1') distanceValue = cmds.getAttr('distance1.distance') ######## jointNumber ########## jn = cmds.intFieldGrp('jointNumber', q=1, value=1) jNUM = jn[0] ############################### #aim Xaxis focus LOC aimLocator = cmds.spaceLocator() cmds.xform(aimLocator, t=(sel_eLOC[0], sel_eLOC[1], sel_eLOC[2])) parentJoint = cmds.joint(p=(sel_sLOC[0], sel_sLOC[1], sel_sLOC[2])) cmds.ungroup(aimLocator) cmds.aimConstraint(aimLocator, parentJoint, wut=0) cmds.delete(aimLocator) #parentJoint zeroOut y = cmds.xform(parentJoint, q=1, ro=1) cmds.joint(parentJoint, e=1, o=(y[0], y[1], y[2])) cmds.xform(parentJoint, ro=(0, 0, 0)) for i in range(1, jNUM + 1): iFloating = i * 1.0 dvPlace = iFloating / jNUM transValue = distanceValue * dvPlace dpJoint = cmds.duplicate(parentJoint, rr=1) #jointOrient x = cmds.xform(dpJoint, q=1, ro=1) cmds.joint(dpJoint, e=1, o=(y[0], y[1], y[2])) cmds.xform(dpJoint, ro=(0, 0, 0)) cmds.select(dpJoint) cmds.move(transValue, 0, 0, r=1, os=1, wd=1) cmds.delete('distanceDimension1')
def createDistanceObjectsBetweenObjectList (objList): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Pass an list of objects into it, it creates distance dimension objects between them while naming and grouping them ARGUMENTS: objList - list of objects to measure between RETURNS: distanceObjList(list) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ cnt = 0 locatorPositionList = [] cnt = (len(objList) - 1) firstTermCnt = 0 secondTermCnt =1 distanceObjList = [] coreNameList = [] if mc.objExists ('measure_grp'): pass else: tmp = mc.group (empty=True, name='measure_grp') mc.xform (tmp, os=True, piv= (0,0,0)) for obj in objList: """return its positional data""" tempPos = mc.xform (obj,q=True, ws=True, rp=True) locatorPositionList.append (tempPos) tmp = obj.split('_') coreNameList.append (tmp[0]) while cnt > 0: distanceObj = mc.distanceDimension( sp=locatorPositionList[firstTermCnt], ep=locatorPositionList[secondTermCnt] ) tmp = mc.listRelatives ( [distanceObj], p=True) tmp = mc.rename (tmp, (coreNameList[firstTermCnt]+'_to_'+coreNameList[secondTermCnt]+'_distMeas') ) distanceObjList.append (tmp) firstTermCnt +=1 secondTermCnt +=1 cnt -= 1 mc.parent (tmp,'measure_grp') if (cnt == 0): break return distanceObjList
def locsToSide(sideAB, sideVertsList, *args): if smartBridgeDict['main_mesh'] == 'nomesh': meshSplit = sideVertsList[0].split('.') smartBridgeDict['main_mesh'] = meshSplit[0] sideVertsAmt = len(sideVertsList) fstSelVertLoc = cmds.pointPosition(smartBridgeDict[sideAB]['fstVtx']) for selVtx in sideVertsList: crtSelVertLoc = cmds.pointPosition(selVtx) newDstCreate = cmds.distanceDimension( sp=(fstSelVertLoc[0], fstSelVertLoc[1], fstSelVertLoc[2]), ep=(crtSelVertLoc[0], crtSelVertLoc[1], crtSelVertLoc[2])) cmds.select(newDstCreate, hierarchy=True) couldBeDstDimShape = cmds.ls(sl=True, fl=True) for couldBe in couldBeDstDimShape: couldBeAttr = cmds.listAttr(couldBe) if 'distance' in couldBeAttr: newDst = cmds.getAttr(couldBe + '.distance') dstTempDict[selVtx] = newDst dispLoc1 = cmds.listConnections(couldBe + '.endPoint') dispLoc2 = cmds.listConnections(couldBe + '.startPoint') cmds.delete(dispLoc1, dispLoc2, couldBeDstDimShape) sideVertsList.sort(key=vertsDstSort) print(dstTempDict) print(sideVertsList) locNo = 0 cmds.group(em=True, name=sideAB + '_grp') for sideVert in sideVertsList: locNo += 1 spaceLoc = sideAB + '_' + str(locNo) + '_loc' cmds.spaceLocator(name=spaceLoc) sideVertLoc = cmds.pointPosition(sideVert) cmds.setAttr(spaceLoc + '.translateX', sideVertLoc[0]) cmds.setAttr(spaceLoc + '.translateY', sideVertLoc[1]) cmds.setAttr(spaceLoc + '.translateZ', sideVertLoc[2]) cmds.parent(spaceLoc, sideAB + '_grp') smartBridgeDict[sideAB]['vertsNo'] = locNo pm.mel.dR_DoCmd("modeObject") cmds.select(clear=True)
def scStretchyIk(partList, partJoints, ikHandleName, *args): # Empty list to store nodes generated in scStretchyIk ikNodes = [] cmds.select(d=True) pjntLen = len(partJoints) sjnt = partJoints[0] ejnt = partJoints[1] sjPos = cmds.xform(sjnt, q=True, t=True, ws=True) ejPos = cmds.xform(ejnt, q=True, t=True, ws=True) # Create the ik solver ikH = cmds.ikHandle(n=ikHandleName, sj=sjnt, ee=ejnt, sol="ikRPsolver") cmds.setAttr(ikH[0] + '.visibility', 0) suffix = partJoints[0].partition('_')[2] # Stretch ---------------------------------------------------------- mdEStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_EStretch_' + suffix) cmds.select(d=True) # NOTE: I need to change disDim transform name disDim = cmds.distanceDimension(sp=(sjPos), ep=(ejPos)) cmds.setAttr('distanceDimension1.visibility', 0) cmds.connectAttr(disDim + '.distance', mdEStretch + '.input1X') #cmds.rename('distanceDimension1', 'disDimNode_Stretch_Shape' + suffix) cmds.rename('distanceDimension1', 'disDimNode_Stretch_' + suffix) # Determine the length of the joint chain in default position endLen = cmds.getAttr(partJoints[1] + '.ty') cmds.setAttr(mdEStretch + '.input2X', endLen) #Finally, we output our new values into the translateX of the knee and ankle joints. cmds.connectAttr(mdEStretch + '.outputX', ejnt + '.ty') ikNodes.append([ikH[0], mdEStretch, 'disDimNode_Stretch_' + suffix]) return ikNodes
def scStretchyIk(partList, partJoints, ikHandleName, *args): # Empty list to store nodes generated in scStretchyIk ikNodes = [] cmds.select(d=True) pjntLen = len(partJoints) sjnt = partJoints[0] ejnt = partJoints[1] sjPos = cmds.xform(sjnt, q=True, t=True, ws=True) ejPos = cmds.xform(ejnt, q=True, t=True, ws=True) # Create the ik solver ikH = cmds.ikHandle(n= ikHandleName, sj=sjnt, ee=ejnt, sol = "ikRPsolver") cmds.setAttr(ikH[0] +'.visibility', 0) suffix = partJoints[0].partition('_')[2] # Stretch ---------------------------------------------------------- mdEStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_EStretch_' + suffix) cmds.select(d=True) # NOTE: I need to change disDim transform name disDim = cmds.distanceDimension(sp=(sjPos), ep=(ejPos)) cmds.setAttr('distanceDimension1.visibility', 0) cmds.connectAttr(disDim + '.distance', mdEStretch + '.input1X') #cmds.rename('distanceDimension1', 'disDimNode_Stretch_Shape' + suffix) cmds.rename('distanceDimension1', 'disDimNode_Stretch_' + suffix) # Determine the length of the joint chain in default position endLen = cmds.getAttr(partJoints[1] + '.ty') cmds.setAttr(mdEStretch + '.input2X', endLen) #Finally, we output our new values into the translateX of the knee and ankle joints. cmds.connectAttr( mdEStretch + '.outputX', ejnt + '.ty') ikNodes.append([ikH[0], mdEStretch, 'disDimNode_Stretch_' + suffix]) return ikNodes
def createPlane(self): # First we find the distance between the two locators. t1 = cmds.getAttr("%s.translate" % self.locators[0][0]) t2 = cmds.getAttr("%s.translate" % self.locators[1][0]) distMeasure = cmds.distanceDimension(sp=(t1[0][0], t1[0][1], t1[0][2]), ep=(t2[0][0], t2[0][1], t2[0][2])) self.distance = cmds.getAttr("%s.distance" % distMeasure) cmds.delete(cmds.pickWalk(distMeasure, direction="up")) # Then we create a plane, freeze its transforms, and delete its construction history. plane = cmds.nurbsPlane(name=self.name + "_GEO", width=self.distance, lengthRatio=(1.0 / self.joints), patchesU=self.joints, axis=(0, 0, 1)) cmds.rotate(0, 0, 90, plane[0]) cmds.makeIdentity(plane[0], apply=True, translate=True, rotate=True, scale=True) cmds.delete(plane, constructionHistory=True) del plane[1] return plane[0]
def setup_dof(target, camera, f_stop): cmds.setAttr(camera + '.depthOfField', 1) # create a locator parented to the camera cam_matrix = cmds.xform(camera, q=True, m=True, ws=True) cam_locator = cmds.spaceLocator() cmds.xform(cam_locator, m=cam_matrix, ws=True) cmds.select(cam_locator, camera, r=True) cmds.parent() # create a locator parented to the target target_matrix = cmds.xform(target, q=True, m=True, ws=True) target_locator = cmds.spaceLocator() cmds.xform(target_locator, m=target_matrix, ws=True) cmds.select(target_locator, target, r=True) cmds.parent() distance_node = cmds.distanceDimension(cam_locator, target_locator) cmds.connectAttr(distance_node + '.distance', camera + '.focusDistance') cmds.setAttr(camera + '.fStop', f_stop)
def createStretchyIk(self, ikJnts, ikKneeJnt, footCtrl, ikBallJnt, part, *args): print "I CSIK" pHip = ikJnts[0] pKnee = ikKneeJnt pAnkle = ikJnts[1] pBall = ikBallJnt ikJntArray = (pHip, pAnkle) """ First we will handle all the stretchy nodes """ """ Create locators for defining the distance between joints""" stretchPoints = [] stretchPositions = [] for jnt in ikJntArray: lctrName = jnt.replace("Jnt_", "LctrPos_") lctrPos = cmds.xform(jnt, q=True, ws=True, t=True) stretchPositions.append(lctrPos) distNamePrefix = pHip.replace("Jnt_", "disB_") distN = cmds.distanceDimension( sp=(stretchPositions[0]), ep=(stretchPositions[1]) ) distNode = distNamePrefix cmds.rename(distN, distNamePrefix) disdimCon = cmds.listConnections(distNode) for locator in disdimCon: stretchPoints.append(locator) """ Create nodes for stretchy """ mdivNamePrefix = pHip.replace("Jnt_", "mDiv_") mdivNode = cmds.shadingNode("multiplyDivide", asUtility=True, n=mdivNamePrefix) conNamePrefix = pHip.replace("Jnt_", "conN_") conNode = cmds.shadingNode("condition", asUtility=True, n=conNamePrefix) """ Pont constrain stretchPoints[0] to hip and stretchPoints[1] to ankle """ cmds.pointConstraint(pHip, stretchPoints[0], mo=True) cmds.parent(stretchPoints[1], footCtrl[0]) """ Connect stPoint[0].translate to distNode.point1.XYZ """ #cmds.connectAttr(stretchPoints[0]+".translate", distNode+".point1") """ Connect stPoint[1].translate to distNode.point2.XYZ """ #cmds.connectAttr(stretchPoints[1]+".translate", distNode+".point2") """ Connect the distNode.distance to conNode.firstTerm""" cmds.connectAttr(distNode+".distance", conNode+".firstTerm") """ Connect distNode.distance to mdivNode.input1X """ cmds.connectAttr(distNode+".distance", mdivNode+".input1X") """ Connect mdivNode.output1X to conNode.colorIfTrueR """ cmds.connectAttr(mdivNode+".outputX", conNode+".colorIfTrue.colorIfTrueR") """ Set mdivNode to "divide" and conNode to "greater than or equal" """ cmds.setAttr( mdivNode+".operation", 2) cmds.setAttr(conNode+".operation", 3) """ Connect conNode.outColorR to scale of hip and knee bones """ if part == 1: cmds.setAttr(footCtrl[0]+".l1_stretch", 62) cmds.connectAttr(conNode+".outColorR", pHip+".scaleX") #cmds.connectAttr(conNode+".outColorR", pKnee+".scaleX") #cmds.connectAttr(conNode+".outColorR", pAnkle+".scaleY") """ Stretch attr connected to conNode.secondTerm and mdivNode.input2X """ """ For Hip 0.250 """ cmds.connectAttr(footCtrl[0]+".l1_stretch", conNode+".secondTerm") cmds.connectAttr(footCtrl[0]+".l1_stretch", mdivNode+".input2X") if part == 2: cmds.setAttr(footCtrl[0]+".l1_stretch", 62) cmds.connectAttr(conNode+".outColorR", pHip+".scaleX") #cmds.connectAttr(conNode+".outColorR", pKnee+".scaleX") #cmds.connectAttr(conNode+".outColorR", pAnkle+".scaleY") """ Stretch attr connected to conNode.secondTerm and mdivNode.input2X """ """ For Hip 0.250 """ cmds.setAttr(footCtrl[0]+".l2_stretch", 62) cmds.connectAttr(footCtrl[0]+".l2_stretch", conNode+".secondTerm") cmds.connectAttr(footCtrl[0]+".l2_stretch", mdivNode+".input2X")
def createStretchyIk(control, ikHandleName, pvName, suffix, jnt_info, lyt_info, *args): rootPos = cmds.xform(jnt_info[0], q=True, t=True, ws=True) midPos = cmds.xform(jnt_info[1], q=True, t=True, ws=True) endPos = cmds.xform(jnt_info[2], q=True, t=True, ws=True) # Create the ik solver cmds.ikHandle(n= ikHandleName, sj=jnt_info[0], ee=jnt_info[2], sol = "ikRPsolver") # Stretch ---------------------------------------------------------- #Start by creating all of the nodes we will need for the stretch. adlStretch = cmds.shadingNode("addDoubleLinear", asUtility=True, n='adlNode_RStretch_' + suffix) clmpStretch = cmds.shadingNode("clamp", asUtility=True, n='clampNode_Stretch_' + suffix) mdLStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_RStretch_' + suffix) mdKStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_MStretch_' + suffix) mdAStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_EStretch_' + suffix) cmds.select(d=True) disDim = cmds.distanceDimension(sp=(rootPos), ep=(endPos)) cmds.rename('distanceDimension1', 'disDimNode_Stretch_' + suffix) cmds.rename('locator1', 'lctrDis_Root_' + suffix) cmds.rename('locator2', 'lctrDis_End_' + suffix) # TODO: Need to save these for later # cmds.parent('lctrDis_hip', 'jnt_pelvis') cmds.parent('lctrDis_End_' + suffix, control[1]) # Determine the length of the joint chain in default position rootLen = cmds.getAttr(jnt_info[1] + '.tx') endLen = cmds.getAttr(jnt_info[2] + '.tx') chainLen = (rootLen + endLen) cmds.setAttr(adlStretch + '.input2', chainLen) cmds.setAttr(mdLStretch + '.input2X', chainLen) cmds.setAttr(mdKStretch + '.input2X', rootLen) cmds.setAttr(mdAStretch + '.input2X', endLen) # The clamp node lets us control the amount of stretch. cmds.connectAttr(control[1] + '.stretch', adlStretch + '.input1') cmds.connectAttr(adlStretch + '.output', clmpStretch + '.maxR') cmds.setAttr (clmpStretch + '.minR', chainLen) cmds.setAttr (mdLStretch + '.operation', 2) # Connect the distance dimension so we always know the current length of the leg. cmds.connectAttr('disDimNode_Stretch_' + suffix +'.distance', clmpStretch + '.inputR') #Now we feed the total value into a multiply divide so we can distribute the value to our joints. cmds.connectAttr(clmpStretch + '.outputR', mdLStretch + '.input1X') cmds.connectAttr(mdLStretch + '.outputX', mdKStretch + '.input1X') cmds.connectAttr(mdLStretch + '.outputX', mdAStretch + '.input1X') #Finally, we output our new values into the translateX of the knee and ankle joints. cmds.connectAttr(mdKStretch + '.outputX', jnt_info[1]+ '.tx') cmds.connectAttr( mdAStretch + '.outputX', jnt_info[2] + '.tx') # Create a pv ---------------------------------------------- cmds.spaceLocator(n=pvName) cmds.xform(pvName, t=rootPos, ws=True) # Pv constrain the ik cmds.poleVectorConstraint (pvName, ikHandleName, weight=1) cmds.select(d=True) #Create a plusMinusAverage utility #Create a multiplyDivide utility pmaTwist = cmds.shadingNode("plusMinusAverage", asUtility=True, n='pmaNode_twist_' + suffix) # Set PMA to subtract cmds.setAttr(pmaTwist + ".operation", 2) mDivTwst = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_twist_' + suffix) cmds.connectAttr(control[1]+'.twist', mDivTwst+'.input1X') cmds.connectAttr(control[1]+'.ry', mDivTwst+'.input1Y') # TODO: I need a pelvis or a better solution #cmds.connectAttr('jnt_pelvis.ry', 'mdNode_LegTwist.input1Z') cmds.setAttr(mDivTwst+'.input2X', -1) cmds.setAttr(mDivTwst+'.input2Y', -1) cmds.setAttr(mDivTwst+'.input2Z', -1) cmds.connectAttr(mDivTwst+'.input1X', pmaTwist+'.input1D[0]') cmds.connectAttr(mDivTwst+'.input1Y', pmaTwist+'.input1D[1]') # Calculate twist offset blueprintJoints = [] for obj in lyt_info: blueprintJoints.append(obj[0]) offset = matchTwistAngle(ikHandleName+".twist", jnt_info, blueprintJoints) # Make a buffer between the control and the ik twist cmds.setAttr(control[1]+'.twist_offset', offset) cmds.connectAttr(control[1]+'.twist_offset', pmaTwist+'.input1D[2]') cmds.connectAttr(pmaTwist+'.output1D', ikHandleName+'.twist')
def make_stretchy_ik(ik_handle, stretchy_name='temp', attribute_holder=None): ''' Creates two measure tools and use them to determine when the joints should be scaled up causing a stretchy effect. Parameters: ik_handle (string) : Name of the IK Handle (joints will be extracted from it) stretchy_name (string): Name to be used when creating system (optional, if not provided it will be "temp") attribute_holder (string): The name of an object. If it exists, custom attributes will be added to it. These attributes allow the user to control whether or not the system is active, as well as its operation. For a more complete stretchy system you have to provide a valid object in this parameter as without it volume preservation is skipped Returns: list (list): A list with the end locator one (to be attached to the IK control) the stretchy_grp (system elements) and the end_ik_jnt (joint under the ikHandle) ''' def caculate_distance(pos_a_x, pos_a_y, pos_a_z, pos_b_x, pos_b_y, pos_b_z): ''' Calculates the magnitude (in this case distance) between two objects Parameters: pos_a_x (float): Position X for object A pos_a_y (float): Position Y for object A pos_a_z (float): Position Z for object A pos_b_x (float): Position X for object B pos_b_y (float): Position Y for object B pos_b_z (float): Position Z for object B Returns: magnitude (float): Distance between two objects ''' dx = pos_a_x - pos_b_x dy = pos_a_y - pos_b_y dz = pos_a_z - pos_b_z return math.sqrt( dx*dx + dy*dy + dz*dz ) def int_to_en(num): ''' Given an int32 number, returns an English word for it. Parameters: num (int) and integer to be converted to English words. Returns: number (string): The input number as words ''' d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen', 20 : 'twenty', 30 : 'thirty', 40 : 'forty', 50 : 'fifty', 60 : 'sixty', 70 : 'seventy', 80 : 'eighty', 90 : 'ninety' } k = 1000 m = k * 1000 b = m * 1000 t = b * 1000 assert(0 <= num) if (num < 20): return d[num] if (num < 100): if num % 10 == 0: return d[num] else: return d[num // 10 * 10] + '-' + d[num % 10] if (num < k): if num % 100 == 0: return d[num // 100] + ' hundred' else: return d[num // 100] + ' hundred and ' + int_to_en(num % 100) if (num < m): if num % k == 0: return int_to_en(num // k) + ' thousand' else: return int_to_en(num // k) + ' thousand, ' + int_to_en(num % k) if (num < b): if (num % m) == 0: return int_to_en(num // m) + ' million' else: return int_to_en(num // m) + ' million, ' + int_to_en(num % m) if (num < t): if (num % b) == 0: return int_to_en(num // b) + ' billion' else: return int_to_en(num // b) + ' billion, ' + int_to_en(num % b) if (num % t == 0): return int_to_en(num // t) + ' trillion' else: return int_to_en(num // t) + ' trillion, ' + int_to_en(num % t) raise AssertionError('num is too large: %s' % str(num)) ########## Start of Make Stretchy Function ########## ik_handle_joints = cmds.ikHandle(ik_handle, q=True, jointList=True) children_last_jnt = cmds.listRelatives(ik_handle_joints[-1], children=True, type='joint') or [] # Find end joint end_ik_jnt = '' if len(children_last_jnt) == 1: end_ik_jnt = children_last_jnt[0] elif len(children_last_jnt) > 1: # Find Joint Closest to ikHandle jnt_magnitude_pairs = [] for jnt in children_last_jnt: ik_handle_ws_pos = cmds.xform(ik_handle, q=True, t=True, ws=True) jnt_ws_pos = cmds.xform(jnt, q=True, t=True, ws=True) mag = caculate_distance(ik_handle_ws_pos[0], ik_handle_ws_pos[1], ik_handle_ws_pos[2], jnt_ws_pos[0], jnt_ws_pos[1], jnt_ws_pos[2]) jnt_magnitude_pairs.append([jnt, mag]) # Find Lowest Distance curent_jnt = jnt_magnitude_pairs[1:][0] curent_closest = jnt_magnitude_pairs[1:][1] for pair in jnt_magnitude_pairs: if pair[1] < curent_closest: curent_closest = pair[1] curent_jnt = pair[0] end_ik_jnt = curent_jnt distance_one = cmds.distanceDimension(sp=(1,random.random()*10,1), ep=(2,random.random()*10,2) ) distance_one_transform = cmds.listRelatives(distance_one, parent=True, f=True) or [][0] distance_one_locators = cmds.listConnections(distance_one) cmds.delete(cmds.pointConstraint(ik_handle_joints[0], distance_one_locators[0])) cmds.delete(cmds.pointConstraint(ik_handle, distance_one_locators[1])) # Rename Distance One Nodes distance_node_one = cmds.rename(distance_one_transform, stretchy_name + "_stretchyTerm_strechyDistance") start_loc_one = cmds.rename(distance_one_locators[0], stretchy_name + "_stretchyTerm_start") end_loc_one = cmds.rename(distance_one_locators[1], stretchy_name + "_stretchyTerm_end") distance_nodes = {} # [distance_node_transform, start_loc, end_loc, ik_handle_joint] index = 0 for index in range(len(ik_handle_joints)): distance_node = cmds.distanceDimension(sp=(1,random.random()*10,1), ep=(2,random.random()*10,2) ) distance_node_transform = cmds.listRelatives(distance_node, parent=True, f=True) or [][0] distance_node_locators = cmds.listConnections(distance_node) distance_node = cmds.rename(distance_node, stretchy_name + '_defaultTerm' + int_to_en(index+1).capitalize() + '_strechyDistanceShape' ) distance_node_transform = cmds.rename(distance_node_transform, stretchy_name + '_defaultTerm' + int_to_en(index+1).capitalize() + '_strechyDistance' ) start_loc = cmds.rename(distance_node_locators[0], stretchy_name + '_defaultTerm' + int_to_en(index+1).capitalize() + '_start') end_loc = cmds.rename(distance_node_locators[1], stretchy_name + '_defaultTerm' + int_to_en(index+1).capitalize() + '_end') cmds.delete(cmds.pointConstraint(ik_handle_joints[index], start_loc)) if index < (len(ik_handle_joints)-1): cmds.delete(cmds.pointConstraint(ik_handle_joints[index+1], end_loc)) else: cmds.delete(cmds.pointConstraint(end_ik_jnt, end_loc)) distance_nodes[distance_node] = [distance_node_transform, start_loc, end_loc, ik_handle_joints[index]] index += 1 # Organize Basic Hierarchy stretchy_grp = cmds.group(name=stretchy_name + "_stretchy_grp", empty=True, world=True) cmds.parent( distance_node_one, stretchy_grp ) cmds.parent( start_loc_one, stretchy_grp ) cmds.parent( end_loc_one, stretchy_grp ) # Connect, Colorize and Organize Hierarchy default_distance_sum_node = cmds.createNode('plusMinusAverage', name=stretchy_name + "_defaultTermSum_plus") index = 0 for node in distance_nodes: cmds.connectAttr('%s.distance' % node, '%s.input1D' % default_distance_sum_node + '[' + str(index) + ']') for obj in distance_nodes.get(node): if cmds.objectType(obj) != 'joint': change_outliner_color(obj, (1,.5,.5)) cmds.parent(obj, stretchy_grp) index += 1 # Outliner Color for obj in [distance_node_one,start_loc_one,end_loc_one]: change_outliner_color(obj,(.5,1,.2)) # Connect Nodes nonzero_stretch_condition_node = cmds.createNode('condition', name=stretchy_name + "_strechyNonZero_condition") nonzero_multiply_node = cmds.createNode('multiplyDivide', name=stretchy_name + "_onePctDistCondition_multiply") cmds.connectAttr('%s.output1D' % default_distance_sum_node, '%s.input1X' % nonzero_multiply_node) cmds.setAttr( nonzero_multiply_node + ".input2X", 0.01) cmds.connectAttr('%s.outputX' % nonzero_multiply_node, '%s.colorIfTrueR' % nonzero_stretch_condition_node) cmds.connectAttr('%s.outputX' % nonzero_multiply_node, '%s.secondTerm' % nonzero_stretch_condition_node) cmds.setAttr( nonzero_stretch_condition_node + ".operation", 5) stretch_normalization_node = cmds.createNode('multiplyDivide', name=stretchy_name + "_distNormalization_divide") cmds.connectAttr('%s.distance' % distance_node_one, '%s.firstTerm' % nonzero_stretch_condition_node) cmds.connectAttr('%s.distance' % distance_node_one, '%s.colorIfFalseR' % nonzero_stretch_condition_node) cmds.connectAttr('%s.outColorR' % nonzero_stretch_condition_node, '%s.input1X' % stretch_normalization_node) cmds.connectAttr('%s.output1D' % default_distance_sum_node, '%s.input2X' % stretch_normalization_node) cmds.setAttr( stretch_normalization_node + ".operation", 2) stretch_condition_node = cmds.createNode('condition', name=stretchy_name + "_strechyAutomation_condition") cmds.setAttr( stretch_condition_node + ".operation", 3) cmds.connectAttr('%s.outColorR' % nonzero_stretch_condition_node, '%s.firstTerm' % stretch_condition_node) # Distance One cmds.connectAttr('%s.output1D' % default_distance_sum_node, '%s.secondTerm' % stretch_condition_node) cmds.connectAttr('%s.outputX' % stretch_normalization_node, '%s.colorIfTrueR' % stretch_condition_node) # Constraints cmds.pointConstraint (ik_handle_joints[0], start_loc_one) for node in distance_nodes: if distance_nodes.get(node)[3] == ik_handle_joints[0:][0]: start_loc_condition = cmds.pointConstraint (ik_handle_joints[0], distance_nodes.get(node)[1]) # Attribute Holder Setup if attribute_holder: if cmds.objExists(attribute_holder): cmds.pointConstraint(attribute_holder, end_loc_one) cmds.addAttr(attribute_holder , ln='stretch', at='double', k=True, minValue=0, maxValue=1) cmds.setAttr(attribute_holder + ".stretch", 1) cmds.addAttr(attribute_holder , ln='squash', at='double', k=True, minValue=0, maxValue=1) cmds.addAttr(attribute_holder , ln='stretchFromSource', at='bool', k=True) cmds.addAttr(attribute_holder , ln='saveVolume', at='double', k=True, minValue=0, maxValue=1) cmds.addAttr(attribute_holder , ln='baseVolumeMultiplier', at='double', k=True, minValue=0, maxValue=1) cmds.setAttr(attribute_holder + ".baseVolumeMultiplier", .5) cmds.addAttr(attribute_holder , ln='minimumVolume', at='double', k=True, minValue=0.01, maxValue=1) cmds.addAttr(attribute_holder , ln='maximumVolume', at='double', k=True, minValue=0) cmds.setAttr(attribute_holder + ".minimumVolume", .4) cmds.setAttr(attribute_holder + ".maximumVolume", 2) cmds.setAttr(attribute_holder + ".stretchFromSource", 1) # Stretch From Body from_body_reverse_node = cmds.createNode('reverse', name=stretchy_name + '_stretchFromSource_reverse') cmds.connectAttr('%s.stretchFromSource' % attribute_holder, '%s.inputX' % from_body_reverse_node) cmds.connectAttr('%s.outputX' % from_body_reverse_node, '%s.w0' % start_loc_condition[0]) # Squash squash_condition_node = cmds.createNode('condition', name=stretchy_name + "_squashAutomation_condition") cmds.setAttr(squash_condition_node + ".secondTerm", 1) cmds.setAttr(squash_condition_node + ".colorIfTrueR", 1) cmds.setAttr(squash_condition_node + ".colorIfFalseR", 3) cmds.connectAttr('%s.squash' % attribute_holder, '%s.firstTerm' % squash_condition_node) cmds.connectAttr('%s.outColorR' % squash_condition_node, '%s.operation' % stretch_condition_node) # Stretch activation_blend_node = cmds.createNode('blendTwoAttr', name=stretchy_name + "_strechyActivation_blend") cmds.setAttr(activation_blend_node + ".input[0]", 1) cmds.connectAttr('%s.outColorR' % stretch_condition_node, '%s.input[1]' % activation_blend_node) cmds.connectAttr('%s.stretch' % attribute_holder, '%s.attributesBlender' % activation_blend_node) for jnt in ik_handle_joints: cmds.connectAttr('%s.output' % activation_blend_node, '%s.scaleX' % jnt) # Save Volume save_volume_condition_node = cmds.createNode('condition', name=stretchy_name + "_saveVolume_condition") volume_normalization_divide_node = cmds.createNode('multiplyDivide', name=stretchy_name + "_volumeNormalization_divide") volume_value_divide_node = cmds.createNode('multiplyDivide', name=stretchy_name + "_volumeValue_divide") xy_divide_node = cmds.createNode('multiplyDivide', name=stretchy_name + "_volumeXY_divide") volume_blend_node = cmds.createNode('blendTwoAttr', name=stretchy_name + "_volumeActivation_blend") volume_clamp_node = cmds.createNode('clamp', name=stretchy_name + "_volumeLimits_clamp") volume_base_blend_node = cmds.createNode('blendTwoAttr', name=stretchy_name + "_volumeBase_blend") cmds.setAttr(save_volume_condition_node + ".secondTerm", 1) cmds.setAttr(volume_normalization_divide_node + ".operation", 2) # Divide cmds.setAttr(volume_value_divide_node + ".operation", 2) # Divide cmds.setAttr(xy_divide_node + ".operation", 2) # Divide cmds.connectAttr('%s.outColorR' % nonzero_stretch_condition_node, '%s.input2X' % volume_normalization_divide_node) # Distance One cmds.connectAttr('%s.output1D' % default_distance_sum_node, '%s.input1X' % volume_normalization_divide_node) cmds.connectAttr('%s.outputX' % volume_normalization_divide_node, '%s.input2X' % volume_value_divide_node) cmds.connectAttr('%s.outputX' % stretch_normalization_node, '%s.input1X' % volume_value_divide_node) cmds.connectAttr('%s.outputX' % volume_value_divide_node, '%s.input2X' % xy_divide_node) cmds.connectAttr('%s.outputX' % stretch_normalization_node, '%s.input1X' % xy_divide_node) cmds.setAttr(volume_blend_node + ".input[0]", 1) cmds.connectAttr('%s.outputX' % xy_divide_node, '%s.input[1]' % volume_blend_node) cmds.connectAttr('%s.saveVolume' % attribute_holder, '%s.attributesBlender' % volume_blend_node) cmds.connectAttr('%s.output' % volume_blend_node, '%s.inputR' % volume_clamp_node) cmds.connectAttr('%s.outputR' % volume_clamp_node, '%s.colorIfTrueR' % save_volume_condition_node) cmds.connectAttr('%s.stretch' % attribute_holder, '%s.firstTerm' % save_volume_condition_node) cmds.connectAttr('%s.minimumVolume' % attribute_holder, '%s.minR' % volume_clamp_node) cmds.connectAttr('%s.maximumVolume' % attribute_holder, '%s.maxR' % volume_clamp_node) # Base Multiplier cmds.setAttr(volume_base_blend_node + ".input[0]", 1) cmds.connectAttr('%s.outColorR' % save_volume_condition_node, '%s.input[1]' % volume_base_blend_node) cmds.connectAttr('%s.baseVolumeMultiplier' % attribute_holder, '%s.attributesBlender' % volume_base_blend_node) # Connect to Joints cmds.connectAttr('%s.output' % volume_base_blend_node, '%s.scaleY' % ik_handle_joints[0]) cmds.connectAttr('%s.output' % volume_base_blend_node, '%s.scaleZ' % ik_handle_joints[0]) for jnt in ik_handle_joints[1:]: cmds.connectAttr('%s.outColorR' % save_volume_condition_node, '%s.scaleY' % jnt) cmds.connectAttr('%s.outColorR' % save_volume_condition_node, '%s.scaleZ' % jnt) else: for jnt in ik_handle_joints: cmds.connectAttr('%s.outColorR' % stretch_condition_node, '%s.scaleX' % jnt) else: for jnt in ik_handle_joints: cmds.connectAttr('%s.outColorR' % stretch_condition_node, '%s.scaleX' % jnt) return [end_loc_one, stretchy_grp, end_ik_jnt]
def Stretch_Arm_R(): Gett_translateX_ForeArm_R=cmds.getAttr("J_ForeArm_Neutral_R.translateX") Gett_translateX_Hand_Neutral_R=cmds.getAttr("J_Hand_Neutral_R.translateX") Sum_ForeArm_Hand_Trans=Gett_translateX_ForeArm_R+Gett_translateX_Hand_Neutral_R DD_Arm_R=cmds.distanceDimension(sp=(0, 0, 0), ep=(1, 0, 0) ) #cleate DD_Arm_R# cmds.rename('locator1','Ini_Stretch_Arm_R') cmds.rename('locator2','End_Stretch_Arm_R') Rename_DD_Arm_R=cmds.rename('distanceDimension1','distanceDimension_Stretch_Master_Arm_R') cmds.select(cl=True) cmds.select('Ini_Stretch_Arm_R') Z_Ini_Stretch_Arm_R=cmds.group(n='Z_Ini_Stretch_Arm_R') cmds.select(cl=True) Get_Trans_Rot('End_Stretch_Arm_R') Z_End_Stretch_Arm_R=cmds.group(n='Z_End_Stretch_Arm_R',em=True) Set_Trans_Rot(Z_End_Stretch_Arm_R) cmds.parent('End_Stretch_Arm_R',Z_End_Stretch_Arm_R) cmds.select(cl=True) Get_Trans_Rot('J_Arm_Neutral_R') Set_Trans_Rot(Z_Ini_Stretch_Arm_R) Get_Trans_Rot('J_Hand_Neutral_R') Set_Trans_Rot(Z_End_Stretch_Arm_R) cmds.parent(Z_End_Stretch_Arm_R,'R_IK_Arm_CTL') cmds.parent(Z_Ini_Stretch_Arm_R,'R_FK_Arm_CTL') cmds.select(cl=True) Gett_Distance_Stretch_Arm_R=cmds.getAttr('distanceDimension_Stretch_Master_Arm_R.distance') Names_Nodes=['MD_Stretch_Arm_R','BC_Stretch_Arm_R','C_Stretch_Arm_R'] Nodes=['multiplyDivide','blendColors','condition'] num=0 for Node in Names_Nodes: Create_Note=cmds.shadingNode(Nodes[num],au=True,n=Node) cmds.select(cl=True) num=num+1 cmds.setAttr ('MD_Stretch_Arm_R.operation',2, k=True) cmds.setAttr ('MD_Stretch_Arm_R.input2X',-Sum_ForeArm_Hand_Trans, k=True) cmds.setAttr ('BC_Stretch_Arm_R.color2R',1) cmds.setAttr ('C_Stretch_Arm_R.operation',2, k=True) cmds.setAttr ('C_Stretch_Arm_R.secondTerm',-Sum_ForeArm_Hand_Trans, k=True) def Connect(Name,Name2,Attr1,Attr2): cmds.connectAttr(Name+Attr1,Name2+Attr2) Connect('distanceDimension_Stretch_Master_Arm_R','MD_Stretch_Arm_R','.distance','.input1X') Connect('R_SwitchArm_CTL','BC_Stretch_Arm_R','.Stretch','.blender') Connect('MD_Stretch_Arm_R','BC_Stretch_Arm_R','.outputX','.color1R') Connect('BC_Stretch_Arm_R','C_Stretch_Arm_R','.outputR','.colorIfTrueR') Connect('distanceDimension_Stretch_Master_Arm_R','C_Stretch_Arm_R','.distance','.firstTerm') Connect('C_Stretch_Arm_R','J_Arm_IK_R','.outColorR','.scaleX') Connect('C_Stretch_Arm_R','J_ForeArm_IK_R','.outColorR','.scaleX') select_Arm=cmds.select('J_Arm_Neutral_R','J_ForeArm_Neutral_R')#Switch_FK_IK_Arm_R sel = cmds.ls (sl=True) cmds.select (cl=True) MD_switch_fk_ik = cmds.shadingNode ("multiplyDivide", asUtility=True, n="MD_Arm_Stretch_FK_IK_R") cmds.setAttr(MD_switch_fk_ik+'.operation',2) cmds.setAttr(MD_switch_fk_ik+'.input2X',10) cmds.connectAttr ('R_SwitchArm_CTL.Switch_FK_IK', MD_switch_fk_ik + ".input1X") Milista=[]#listA VACIA QUE RECIBIRA ROS NOMBRES _Neutral_R for J in sel:#FOR PARA EN BASE A RA selECCION(JOINTS) SE clEAN blendColors Y SE CONECTE ER multiplyDivide A ROS BRENDS N = J.split("_Neutral_R")[0] New_N=N.split("J_")[1] BC_rotate = cmds.shadingNode ("blendColors", asUtility=True, n="BS_" + New_N+"_stretch_R") cmds.select (cl=True) cmds.connectAttr (BC_rotate + ".output", J + ".scale") cmds.connectAttr (MD_switch_fk_ik + ".outputX", BC_rotate + ".blender") list.append(Milista,N)#AGREGA ER NOMBRE DER JOINT SIN NOMBRE DER SISTEMA A RA listA Milista def fun1(Var1):#FUNCION PARA AGREGAR STRING A ROS NOMBRES QUE EXISTEN EN Milista list.append (Milista, Milista[0] + Var1) list.append (Milista, Milista[1] + Var1) fun1('_FK_R') fun1('_IK_R') def fun(Var,Var2):#FUNCION PARA CONECTAR ROS JOINTS FK,IK A ROS BREND colols cmds.connectAttr (Milista[2]+ "."+Var, "BS_Arm_"+Var2+"_R.color2") cmds.connectAttr (Milista[4]+ "."+Var, "BS_Arm_"+Var2+"_R.color1") cmds.connectAttr (Milista[3]+ "."+Var, "BS_ForeArm_"+Var2+"_R.color2") cmds.connectAttr (Milista[5]+ "."+Var, "BS_ForeArm_"+Var2+"_R.color1") fun('scale','stretch') cmds.parent('distanceDimension_Stretch_Master_Arm_R','hidden') cmds.hide('distanceDimension_Stretch_Master_Arm_R') cmds.hide('Ini_Stretch_Arm_R') cmds.hide('End_Stretch_Arm_R') cmds.select(cl=True)
def generateDistanceDimension(self, posA, posB): cmds.distanceDimension(sp = (self.posA[0], self.posA[1], self.posA[2]), ep = (self.posB[0], self.posB[1], self.posB[2]))
def makeIKWrist(*Args): cm.rename(cm.ls(sl=True), 'R_wrist_IK_CTRL') cm.select('R_wrist_IK_CTRL', 'R_arm_IK_HDL') maya.mel.eval( 'doCreateParentConstraintArgList 1 { "1","0","0","0","0","0","0","1","","1" };' ) cm.select('R_wrist_IK_CTRL', 'R_arm_IK_JNT_04') maya.mel.eval( 'doCreateOrientConstraintArgList 1 { "1","0","0","0","0","0","0","1","","1" };' ) #maya.mel.eval('setAttr -lock true -keyable false -channelBox false "R_wrist_IK_CTRL.sx";') #maya.mel.eval('setAttr -lock true -keyable false -channelBox false "R_wrist_IK_CTRL.sy";') #maya.mel.eval('setAttr -lock true -keyable false -channelBox false "R_wrist_IK_CTRL.sz";') cm.setAttr('R_wrist_IK_CTRL.sx', lock=True, keyable=False, channelBox=False) cm.setAttr('R_wrist_IK_CTRL.sy', lock=True, keyable=False, channelBox=False) cm.setAttr('R_wrist_IK_CTRL.sz', lock=True, keyable=False, channelBox=False) piv1 = cm.xform('R_arm_IK_JNT_01', q=True, t=True, ws=True) piv3 = cm.xform('R_arm_IK_JNT_04', q=True, t=True, ws=True) cm.distanceDimension(ep=(piv3[0], piv3[1], piv3[2]), sp=(piv1[0], piv1[1], piv1[2])) cm.rename('locator2', 'R_arm_Dictance_LOC') cm.rename('distanceDimensionShape1', 'R_arm_Distance') cm.parent('R_arm_Dictance_LOC', 'R_wrist_IK_CTRL') originalDistance = cm.getAttr('R_arm_Distance.distance') cm.createNode('multiplyDivide', n='R_arm_stretchRatio_Calculator') #cm.connectAttr('R_arm_Distance.distance', 'R_arm_stretchRatio_Calculator.input1.input1X') cm.setAttr('R_arm_stretchRatio_Calculator.input2.input2X', originalDistance) cm.setAttr('R_arm_stretchRatio_Calculator.operation', 2) cm.createNode('condition', n='Condition_distance_greaterThanOrig') cm.setAttr('Condition_distance_greaterThanOrig.secondTerm', originalDistance) cm.connectAttr('R_arm_Distance.distance', 'Condition_distance_greaterThanOrig.firstTerm') cm.setAttr('Condition_distance_greaterThanOrig.operation', 2) cm.setAttr('Condition_distance_greaterThanOrig.colorIfFalseR', originalDistance) cm.connectAttr('R_arm_Distance.distance', 'Condition_distance_greaterThanOrig.colorIfTrueR') cm.connectAttr('Condition_distance_greaterThanOrig.outColor', 'R_arm_stretchRatio_Calculator.input1') #cm.connectAttr('Condition_distance_greaterThanOrig.colorIfTrueR', 'R_arm_stretchRatio_Calculator.input1.input1X') #cm.connectAttr('Condition_distance_greaterThanOrig.colorIfFalseR', 'R_arm_stretchRatio_Calculator.input1.input1X') for i in range(1, 4): cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_FK_JNT_0' + str(i) + '.scale.scaleX') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_FK_JNT_0' + str(i) + '.scale.scaleY') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_FK_JNT_0' + str(i) + '.scale.scaleZ') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_IK_JNT_0' + str(i) + '.scale.scaleX') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_IK_JNT_0' + str(i) + '.scale.scaleY') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_IK_JNT_0' + str(i) + '.scale.scaleZ') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_result_JNT_0' + str(i) + '.scale.scaleX') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_result_JNT_0' + str(i) + '.scale.scaleY') cm.connectAttr('R_arm_stretchRatio_Calculator.output.outputX', 'R_arm_result_JNT_0' + str(i) + '.scale.scaleZ') print originalDistance print 'IK Wrist complete.'
def makePlait(*pArgs): _depth = cm.intSliderGrp('subdivisionCurve', q=True, v=True) _width = cm.floatSliderGrp('braidWidth', q=True, v=True) #_depth*=2 _width*=2 cm.rename('braid_CRV') cm.rebuildCurve(cm.ls(sl=True), ch=True, rpo=True, rt=False, end=True, kr=False, kcp=False, kep=True, kt=False, s=_depth, tol=0.01) piv1 = cm.xform('braid_CRV.cv[0]', q=True, t=True, ws=True) piv3 = cm.xform('braid_CRV.cv['+str(_depth)+']', q=True, t=True, ws=True) cm.distanceDimension(ep=(piv3[0],piv3[1],piv3[2]), sp=(piv1[0],piv1[1], piv1[2])) dist = cm.getAttr('distanceDimension1.distance') moveY = float(dist)/float(_depth/2.0) #1.2 if _depth%2!=0: _depth+=1 switch=1 for i in range(0, _depth): switch*=-1 if i%3==0 and switch>0: cm.select('braid_CRV.ep['+str(i+1)+']', add=True) cm.select('braid_CRV.ep['+str(i+2)+']', add=True) cm.move(_width, 0, 0, r=True, os=True) cm.select(deselect=True) for i in range(0, _depth): switch*=-1 if i%3==0 and switch<0: cm.select('braid_CRV.ep['+str(i+1)+']', add=True) cm.select('braid_CRV.ep['+str(i+2)+']', add=True) cm.move(-_width, 0, 0, r=True, os=True) cm.select(deselect=True) for i in range(0, _depth): if i%3==0: cm.select('braid_CRV.ep['+str(i+1)+']', add=True) cm.move(0, 0, _width*2, r=True, os=True) cm.select(deselect=True) for i in range(0, _depth): if i%3==0: cm.select('braid_CRV.ep['+str(i+2)+']', add=True) cm.move(0, 0, -_width*2, r=True, os=True) cm.polyCylinder(n='polyCircle', sx=5, sy=0, sz=1) cm.select('polyCircle.f[0:9]') cm.delete() piv = cm.xform('braid_CRV.cv[0]', q=True, t=True, ws=True) cm.move(piv[0], piv[1], piv[2], 'polyCircle', ws=True, a=True) float(moveY) cm.scale(float(moveY*0.1), float(moveY*0.1), float(moveY*0.05), 'polyCircle', os=True) cm.select('polyCircle.f[0:4]', add=True) maya.mel.eval('polyExtrudeFacet -constructionHistory 1 -keepFacesTogether 1 -pvx 0.09549146891 -pvy 21.69501618 -pvz -25.49619563 -divisions 1 -twist 0 -taper 1 -off 0 -thickness 0 -smoothingAngle 30 -inputCurve braid_CRV polyCircle.f[0:4];') cm.setAttr('polyExtrudeFace1.divisions', 50) #make unique maya.mel.eval('polyNormal -normalMode 0 -userNormalMode 0 -ch 1 polyCircle;') cm.duplicate('polyCircle', n='polyCircle2') cm.move(0, float(moveY), 0, 'polyCircle2', r=True) # cm.move(0, float(_depth/moveY), 0, 'polyCircle2', r=True) cm.duplicate('polyCircle2', n='polyCircle3') cm.move(0, float(moveY), 0, 'polyCircle3', r=True) #cm.move(0, float(_depth/moveY), 0, 'polyCircle3', r=True) print _depth cm.polyUnite('polyCircle*', n='DONE_braid') maya.mel.eval('DeleteHistory;') cm.rename('braid_CRV', 'DONE_braid') cm.delete('distanceDimension1', 'locator1', 'locator2')
def createStretchyIk(ikjnt_info, rjnt_info, control, ikHandleName, pvName, instance, twistCompensate, pmas, pvMA, saxis, settingsControl, *args): # Find the stretch axis suffix = ikHandleName.replace('ikh_', '') rootPos = cmds.xform(ikjnt_info[0], q=True, t=True, ws=True) midPos = cmds.xform(ikjnt_info[1], q=True, t=True, ws=True) endPos = cmds.xform(ikjnt_info[2], q=True, t=True, ws=True) # Create the ik solver ikSolverName = ikHandleName.replace('IKH', 'ikSol') ikSol = cmds.ikSolver( st='ikRPsolver', ep=0.0, n=ikSolverName ) ikh = cmds.ikHandle(n=ikHandleName, sj=ikjnt_info[0], ee=ikjnt_info[2], s="sticky", sol=ikSol) ikSol = cmds.ikHandle(ikh[0], q=True, sol=True) # Stretch ---------------------------------------------------------- #Start by creating all of the nodes we will need for the stretch. conRStretch = cmds.shadingNode("condition", asUtility=True, n='conNode_RStretch_' + suffix) conEStretch = cmds.shadingNode("condition", asUtility=True, n='conNode_EStretch_' + suffix) mdGMStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_GoffsetStretchM_' + suffix) mdGRStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_GoffsetStretchR_' + suffix) mdGEStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_GoffsetStretchE_' + suffix) mdMStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_MStretch_' + suffix) mdRStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_RStretch_' + suffix) mdEStretch = cmds.shadingNode("multiplyDivide", asUtility=True, n='mdNode_EStretch_' + suffix) btaTglStretch = cmds.shadingNode("blendTwoAttr", asUtility=True, n='btaNode_TglStretch_' + suffix) btaRStretch = cmds.shadingNode("blendTwoAttr", asUtility=True, n='btaNode_RStretch_' + suffix) btaEStretch = cmds.shadingNode("blendTwoAttr", asUtility=True, n='btaNode_EStretch_' + suffix) pmaRStretch = cmds.shadingNode("plusMinusAverage", asUtility=True, n='pmaNode_RStretch_' + suffix) pmaEStretch = cmds.shadingNode("plusMinusAverage", asUtility=True, n='pmaNode_EStretch_' + suffix) ucMStretch = cmds.shadingNode("unitConversion", asUtility=True, n='ucNode_MStretch_' + suffix) ucRStretch = cmds.shadingNode("unitConversion", asUtility=True, n='ucNode_RStretch_' + suffix) ucEStretch = cmds.shadingNode("unitConversion", asUtility=True, n='ucNode_EStretch_' + suffix) shadingnodelist = [conRStretch, conEStretch, mdMStretch, mdRStretch, mdEStretch, btaTglStretch, btaRStretch, btaEStretch, pmaRStretch, pmaEStretch, ucMStretch, ucRStretch, ucEStretch, mdGMStretch, mdGRStretch, mdGEStretch] # Set operations for nodes cmds.setAttr(mdGMStretch + '.operation', 2) cmds.setAttr(mdGRStretch + '.operation', 2) cmds.setAttr(mdGEStretch + '.operation', 2) cmds.setAttr(mdMStretch + '.operation', 2) cmds.setAttr(mdEStretch + '.operation', 1) cmds.setAttr(mdRStretch + '.operation', 1) cmds.setAttr(conRStretch + '.operation', 2) cmds.setAttr(conEStretch + '.operation', 2) cmds.setAttr(pmaRStretch + '.operation', 1) cmds.setAttr(pmaEStretch + '.operation', 1) cmds.select(d=True) lctrR = cmds.spaceLocator(n='lctrDis_Root_' + suffix) cmds.xform(lctrR[0], ws=True, t=rootPos) lctrE = cmds.spaceLocator(n='lctrDis_End_' + suffix) cmds.xform(lctrE[0], ws=True, t=endPos) lctrM = cmds.spaceLocator(n='lctrDis_Mid_' + suffix) cmds.xform(lctrM[0], ws=True, t=midPos) lctrlist = [lctrR, lctrE, lctrM] for l in lctrlist: cmds.setAttr(l[0] + '.visibility', 0) # Disdim for total chain length cmds.select(lctrR, lctrE) cmds.distanceDimension(sp=(rootPos), ep=(endPos)) cmds.rename('distanceDimensionShape1', 'disDimNode_MStretch_' + suffix + '_Shape') cmds.rename('distanceDimension1', 'disDimNode_MStretch_' + suffix) shadingnodelist.append('disDimNode_MStretch_' + suffix) con = cmds.listConnections('disDimNode_MStretch_' + suffix + '_Shape' + '.endPoint', p=True)[0] if con != None: cmds.disconnectAttr(con, 'disDimNode_MStretch_' + suffix + '_Shape' + '.endPoint') con = cmds.listConnections('disDimNode_MStretch_' + suffix + '_Shape' + '.startPoint', p=True)[0] if con != None: cmds.disconnectAttr(con, 'disDimNode_MStretch_' + suffix + '_Shape' + '.startPoint') cmds.connectAttr(lctrR[0] + 'Shape.worldPosition[0]', 'disDimNode_MStretch_' + suffix + '_Shape' + '.startPoint', f=True) cmds.connectAttr(lctrE[0] + 'Shape.worldPosition[0]', 'disDimNode_MStretch_' + suffix + '_Shape' + '.endPoint', f=True) # Disdim for first 2 joints cmds.select(d=True) cmds.distanceDimension(sp=(rootPos), ep=(midPos)) cmds.rename('distanceDimensionShape1', 'disDimNode_RStretch_' + suffix + '_Shape') cmds.rename('distanceDimension1', 'disDimNode_RStretch_' + suffix) shadingnodelist.append('disDimNode_RStretch_' + suffix) con = cmds.listConnections('disDimNode_RStretch_' + suffix + '_Shape' + '.endPoint', p=True)[0] if con != None: cmds.disconnectAttr(con, 'disDimNode_RStretch_' + suffix + '_Shape' + '.endPoint') con = cmds.listConnections('disDimNode_RStretch_' + suffix + '_Shape' + '.startPoint', p=True)[0] if con != None: cmds.disconnectAttr(con, 'disDimNode_RStretch_' + suffix + '_Shape' + '.startPoint') cmds.connectAttr(lctrR[0] + 'Shape.worldPosition[0]', 'disDimNode_RStretch_' + suffix + '_Shape' + '.startPoint', f=True) cmds.connectAttr(lctrM[0] + 'Shape.worldPosition[0]', 'disDimNode_RStretch_' + suffix + '_Shape' + '.endPoint', f=True) # Disdim for second set joints cmds.select(d=True) cmds.distanceDimension(sp=(midPos), ep=(endPos)) cmds.rename('distanceDimensionShape1', 'disDimNode_EStretch_' + suffix + '_Shape') cmds.rename('distanceDimension1', 'disDimNode_EStretch_' + suffix) shadingnodelist.append('disDimNode_EStretch_' + suffix) con = cmds.listConnections('disDimNode_EStretch_' + suffix + '_Shape' + '.endPoint', p=True)[0] if con != None: cmds.disconnectAttr(con, 'disDimNode_EStretch_' + suffix + '_Shape' + '.endPoint') con = cmds.listConnections('disDimNode_EStretch_' + suffix + '_Shape' + '.startPoint', p=True)[0] if con != None: cmds.disconnectAttr(con, 'disDimNode_EStretch_' + suffix + '_Shape' + '.startPoint') cmds.connectAttr(lctrM[0] + 'Shape.worldPosition[0]', 'disDimNode_EStretch_' + suffix + '_Shape' + '.startPoint', f=True) cmds.connectAttr(lctrE[0] + 'Shape.worldPosition[0]', 'disDimNode_EStretch_' + suffix + '_Shape' + '.endPoint', f=True) cmds.parent('lctrDis_End_' + suffix, control[1]) rootLen = cmds.getAttr(ikjnt_info[1] + saxis) endLen = cmds.getAttr(ikjnt_info[2] + saxis) chainLen = (rootLen + endLen) negval = False cmds.setAttr(ucMStretch + '.conversionFactor', 1) cmds.setAttr(ucRStretch + '.conversionFactor', 1) cmds.setAttr(ucEStretch + '.conversionFactor', 1) if chainLen < 0: negval = True #cmds.setAttr(ucMStretch + '.conversionFactor', -1) cmds.setAttr(ucRStretch + '.conversionFactor', -1) cmds.setAttr(ucEStretch + '.conversionFactor', -1) # Make node connections cmds.connectAttr('disDimNode_MStretch_' + suffix +'.distance', mdGMStretch + '.input1X') cmds.connectAttr(mdGMStretch + '.outputX', btaTglStretch + '.input[0]') if cmds.attributeQuery('stretch', node=control[1], exists=True): cmds.connectAttr(control[1] + '.stretch', btaTglStretch + '.attributesBlender') if cmds.attributeQuery('stretch', node=settingsControl[1], exists=True) == True and cmds.attributeQuery('stretch', node=settingsControl[1], enum=True) == True: cmds.connectAttr(settingsControl[1] + '.stretch', btaTglStretch + '.attributesBlender') if cmds.attributeQuery('stretch', node=settingsControl[1], exists=True) == True and cmds.attributeQuery('stretch', node=settingsControl[1], enum=True) == False: revikfk = cmds.shadingNode("reverse", asUtility=True, n='rev_' + instance + '_stretch') cmds.connectAttr(settingsControl[1] + '.stretch', revikfk + '.inputX') cmds.connectAttr(revikfk + '.outputX', btaTglStretch + '.attributesBlender') cmds.connectAttr(btaTglStretch +'.output', ucMStretch + '.input') cmds.connectAttr(ucMStretch + '.output', mdMStretch + '.input1X') cmds.connectAttr(ucMStretch + '.output', conRStretch + '.firstTerm') cmds.connectAttr(ucMStretch + '.output', conEStretch + '.firstTerm') cmds.connectAttr(mdMStretch + '.outputX', mdRStretch + '.input1X') cmds.connectAttr(mdMStretch + '.outputX', mdEStretch + '.input1X') cmds.connectAttr(mdRStretch + '.outputX', conRStretch + '.colorIfTrueR') cmds.connectAttr(mdEStretch + '.outputX', conEStretch + '.colorIfTrueR') cmds.connectAttr('disDimNode_RStretch_' + suffix +'.distance', mdGRStretch + '.input1X') cmds.connectAttr(mdGRStretch + '.outputX', ucRStretch + '.input') cmds.connectAttr(ucRStretch + '.output', btaRStretch + '.input[1]') cmds.connectAttr('disDimNode_EStretch_' + suffix +'.distance', mdGEStretch + '.input1X') cmds.connectAttr(mdGEStretch + '.outputX', ucEStretch + '.input') cmds.connectAttr(ucEStretch + '.output', btaEStretch + '.input[1]') cmds.connectAttr(conRStretch +'.outColorR', btaRStretch + '.input[0]') cmds.connectAttr(conEStretch +'.outColorR', btaEStretch + '.input[0]') cmds.connectAttr(btaRStretch + '.output', pmaRStretch + '.input1D[0]') cmds.connectAttr(btaEStretch + '.output', pmaEStretch + '.input1D[0]') # Set node attributes for chain length cmds.setAttr(btaTglStretch + '.input[1]', 0) cmds.setAttr(mdRStretch + '.input2X', rootLen) cmds.setAttr(mdEStretch + '.input2X', endLen) if negval == True: cmds.setAttr(conRStretch + '.secondTerm', chainLen * -1) cmds.setAttr(conEStretch + '.secondTerm', chainLen * -1) cmds.setAttr(mdMStretch + '.input2X', chainLen * -1) else: cmds.setAttr(conRStretch + '.secondTerm', chainLen) cmds.setAttr(conEStretch + '.secondTerm', chainLen) cmds.setAttr(mdMStretch + '.input2X', chainLen) cmds.setAttr(conRStretch + '.colorIfFalseR', rootLen) cmds.setAttr(conEStretch + '.colorIfFalseR', endLen) # Connect to ik jnt tx cmds.connectAttr(pmaRStretch + '.output1D', ikjnt_info[1] + saxis) cmds.connectAttr(pmaEStretch + '.output1D', ikjnt_info[2] + saxis) # Connect control attributes if cmds.attributeQuery('pv_lock', node=control[1], exists=True): cmds.connectAttr(control[1] + '.pv_lock', btaRStretch + '.attributesBlender') cmds.connectAttr(control[1] + '.pv_lock', btaEStretch + '.attributesBlender') if cmds.attributeQuery('Pv_Lock', node=control[1], exists=True): cmds.connectAttr(settingsControl[1] + '.Pv_Lock', btaRStretch + '.attributesBlender') cmds.connectAttr(settingsControl[1] + '.Pv_Lock', btaEStretch + '.attributesBlender') if cmds.attributeQuery('Root_Length', node=control[1], exists=True): cmds.connectAttr(control[1] + '.Root_Length', pmaRStretch + '.input1D[1]') cmds.connectAttr(control[1] + '.End_Length', pmaEStretch + '.input1D[1]') if cmds.attributeQuery('Root_Length', node=settingsControl[1], exists=True): cmds.connectAttr(settingsControl[1] + '.Root_Length', pmaRStretch + '.input1D[1]') cmds.connectAttr(settingsControl[1] + '.End_Length', pmaEStretch + '.input1D[1]') else: pass # Calculate twist offset offset = matchTwistAngle(ikHandleName+".twist", ikjnt_info, rjnt_info) cmds.setAttr(ikHandleName+".twist", offset) cmds.poleVectorConstraint(pvName, ikHandleName, weight=1) cmds.parent(lctrM, pvName) for item in shadingnodelist: try: cmds.setAttr(item + '.visibility', 0) except: pass cmds.setAttr(ikh[0] + '.visibility', 0) cmds.setAttr(lctrR[0]+ '.visibility', 0) cmds.setAttr(lctrE[0]+ '.visibility', 0) return(ikh[0], lctrR[0], shadingnodelist, lctrE[0], ikSol)
def create_arm_leg ( part = 'arm', side = '_l_' ): if mc.objExists( Controllers.CHEST ): print "SPINE ALREADY exists" else: create_neck () if side == '_l_': if part == 'arm': pv_ctl = Controllers.ARM_PV_LEFT ik_ctl = Controllers.ARM_LEFT shoulder_jnt = ArmLeftJoint.SHOULDER clavicle_end = ArmLeftJoint.CLAVICLE_END else: pv_ctl = Controllers.LEG_PV_LEFT ik_ctl = Controllers.LEG_LEFT shoulder_jnt = LegLeftJoint.THIGH else: if part == 'arm': pv_ctl = Controllers.ARM_PV_RIGHT ik_ctl = Controllers.ARM_RIGHT shoulder_jnt = ArmRightJoint.SHOULDER clavicle_end = ArmRightJoint.CLAVICLE_END else: pv_ctl = Controllers.LEG_PV_RIGHT ik_ctl = Controllers.LEG_RIGHT shoulder_jnt = LegRightJoint.THIGH name = part + side ########################## # # IK Rig ik_arm = rd.duplicate_bones ( shoulder_jnt, 'JNT1', 'IKJ' ) arm_group = mc.group ( empty = True, name = name + 'holder_GRP' ) mc.parent ( ik_arm[0], arm_group ) mc.parent ( arm_group, Controllers.GLOBAL ) mc.select ( arm_group, replace = True ) mc.addAttr ( longName = 'global_scale_solver', attributeType = 'float' ) mc.connectAttr ( Controllers.GLOBAL + '.Scale', arm_group + '.global_scale_solver' ) arm_ctl = rd.create_ctrl( obj_type = 'cube', name = ik_ctl, size = Scales.IK, color = Colors.RED, option_attr = True, obj_pos = ik_arm[2] ) mc.parent ( arm_ctl, arm_group ) rd.parent_group( arm_ctl, arm_ctl.replace ( 'CTL', 'up_CTL_GRP' ) ) rd.parent_group ( arm_ctl, arm_ctl.replace ( 'CTL', 'CTL_GRP' ) ) rd.add_attr( arm_ctl, 'parent_hand_to', attr_type = 'enum', enum = ['global', 'hip', 'chest', 'head', 'object'] ) rd.add_attr( arm_ctl, 'stretch', attr_type = 'bool' ) rd.add_attr( arm_ctl, 'roll' ) mc.setAttr ( arm_ctl + '.roll', 0 ) arm_ik_old = mc.ikHandle ( name = arm_ctl.replace ( 'CTL', 'IKH' ), startJoint = ik_arm[0], endEffector = ik_arm[2], solver = 'ikRPsolver' ) mc.rename ( arm_ik_old[1], arm_ik_old[0].replace ( 'IKH', 'EFF' ) ) arm_ik = arm_ik_old[0] mc.connectAttr ( arm_ctl + '.roll', arm_ik + '.twist' ) mc.parent ( arm_ik, arm_ctl ) pv_loc = rd.create_pv() mc.move ( 62.266315, 0, 0, relative = True, objectSpace = True, worldSpaceDistance = True ) mc.parent ( pv_loc, arm_group ) pv_gp = rd.parent_group ( pv_loc, pv_loc.replace ( 'pv_LOC', 'pv_GRP' ) ) mc.select ( arm_ik, add = True ) pv_ctl = rd.create_ctrl( 'sphere', pv_ctl, Scales.PV, Colors.RED, obj_pos = pv_loc ) mc.poleVectorConstraint ( pv_ctl, arm_ik ) mc.parent ( pv_ctl, pv_gp ) mc.delete ( pv_loc ) ########################## # # FK Rig fk_arm = rd.duplicate_bones ( shoulder_jnt, 'JNT1', 'FKJ' ) print 'FK ARM' print fk_arm arm_fk_loc = mc.rename ( mc.spaceLocator()[0], part + side + 'origin_LOC' ) rd.get_position ( arm_fk_loc, fk_arm[0], 0, 1, 0 ) if part == '_l_': mc.pointConstraint ( clavicle_end, arm_fk_loc ) mc.parent ( arm_fk_loc, arm_group ) if side == '_l_': if part == 'arm': arm_fk_ctl = ik_ctl.replace ( 'CTL', 'shoulder_CTL') else: arm_fk_ctl = ik_ctl.replace ( 'CTL', 'thigh_CTL') else: if part == 'arm': arm_fk_ctl = ik_ctl.replace ( 'CTL', 'shoulder_CTL') else: arm_fk_ctl = ik_ctl.replace ( 'CTL', 'thigh_CTL') arm_fk_ctl = rd.create_ctrl ( 'circle', arm_fk_ctl, Scales.FK, Colors.BLUE, option_attr = 1, obj_pos = fk_arm[0] ) rd.add_attr( arm_fk_ctl, 'Stretch' ) rd.add_attr( arm_fk_ctl, 'Gimbal_CTL_Vis', attr_type = 'bool' ) rd.add_attr( arm_fk_ctl, 'Arm_Orient_By', attr_type = 'enum', enum = ['chest','global'] ) mc.setAttr ( arm_fk_ctl + '.Stretch', 1 ) arm_fk_gimbal_ctl = rd.create_ctrl ( 'circle', arm_fk_ctl.replace ( '_CTL', '_gimbal_CTL' ), Scales.GIMBAL, Colors.YELLOW, obj_pos = fk_arm[0] ) mc.parent ( arm_fk_gimbal_ctl, arm_fk_loc ) mc.connectAttr ( arm_fk_ctl + '.Gimbal_CTL_Vis', arm_fk_gimbal_ctl + 'Shape.visibility' ) rd.parent_group ( arm_fk_gimbal_ctl, arm_fk_gimbal_ctl.replace ( '_gimbal_CTL', '_GRP' ) ) mc.parent ( arm_fk_ctl, arm_fk_gimbal_ctl ) if side == '_l_': elbow_fk_ctl = ik_ctl.replace ( 'CTL', 'elbow_CTL') else: elbow_fk_ctl = ik_ctl.replace ( 'CTL', 'elbow_CTL') elbow_fk_ctl = rd.create_ctrl ( 'circle', elbow_fk_ctl, Scales.FK, Colors.BLUE, option_attr = 1, obj_pos = fk_arm[1] ) rd.add_attr( elbow_fk_ctl, 'Stretch' ) mc.setAttr ( elbow_fk_ctl + '.Stretch', 1 ) elbow_fk_ctl_group = rd.parent_group ( elbow_fk_ctl, elbow_fk_ctl.replace ( '_CTL', '_CTL_GRP' ) ) mc.parent ( elbow_fk_ctl_group, arm_fk_ctl ) mc.parent ( fk_arm[0], arm_group ) print 'FK ARM [0]' print ( fk_arm[0] ) mc.connectAttr ( arm_fk_ctl + '.Stretch', fk_arm[0] + '.scaleX' ) mc.orientConstraint ( elbow_fk_ctl, fk_arm[1] ) mc.connectAttr ( elbow_fk_ctl + '.Stretch', fk_arm[1] + '.scaleX' ) mc.pointConstraint ( fk_arm[1], elbow_fk_ctl_group ) ########################## # # Arm IK/FK blend Rig blend_arm = rd.duplicate_bones ( shoulder_jnt, 'JNT1', 'BLD' ) mc.parent ( blend_arm[0], arm_group ) ik_fk_switch = [] ik_fk_switch.append ( mc.orientConstraint ( ik_arm[0], fk_arm[0], blend_arm[0] )) ik_fk_switch.append ( mc.parentConstraint ( ik_arm[1], fk_arm[1], blend_arm[1] )) ik_fk_switch.append ( mc.parentConstraint ( ik_arm[2], fk_arm[2], blend_arm[2] )) ########################## # # Ribbons arm_fol_group = mc.group ( name = part + side + 'holder_arm_GRP', empty = True ) ribbon_ctrl = rd.create_ctrl( 'circle', part + side + 'ribbon_CTL', Scales.RIBBON_CTRL, Colors.YELLOW, option_attr = True, obj_pos = blend_arm[1] ) rd.add_attr(ribbon_ctrl, 'Elbow_lock', 'float', min_max = 'both', min_val = 0 , max_val = 1) mc.setAttr ( ribbon_ctrl + '.Elbow_lock', 0) ribbon_ctrl_group = rd.parent_group ( ribbon_ctrl, ribbon_ctrl.replace ( 'CTL', 'GRP' ) ) mc.parent ( ribbon_ctrl_group, arm_fol_group ) ribbon_constraint = mc.parentConstraint ( blend_arm[1], pv_ctl, ribbon_ctrl_group ) node = mc.createNode ( 'reverse', name = ribbon_ctrl.replace ( '_CTL', '_RVS' ) ) mc.connectAttr ( ribbon_ctrl + '.Elbow_lock', node + '.inputX' ) slot_1 = mc.listConnections ( ribbon_constraint[0] + '.target[0].targetParentMatrix', d = 0, s = 1 ) slot_2 = mc.listConnections ( ribbon_constraint[0] + '.target[1].targetParentMatrix', d = 0, s = 1 ) mc.connectAttr ( ribbon_ctrl + '.Elbow_lock' , ribbon_constraint[0] + '.' + slot_2[0] + 'W1' ) mc.connectAttr ( node + '.outputX' , ribbon_constraint[0] + '.' + slot_1[0] + 'W0' ) if part == 'arm': member01 = '_shoulder_' member02 = '_elbow_' else: member01 = '_thigh_' member02 = '_knee_' rd.create_ribbon(part, side, member01, blend_arm[0], ribbon_ctrl, arm_fol_group, Scales.RIBBON, Colors.YELLOW) rd.create_ribbon(part, side, member02, ribbon_ctrl, blend_arm[2], arm_fol_group, Scales.RIBBON, Colors.YELLOW) ########################## # # Ik fk blend ik_loc = mc.spaceLocator( name = part + side + 'ik_fk_blend_LOC' )[0] mc.parent ( ik_loc, arm_group ) rd.add_attr( ik_loc, 'ik', min_max = 'both', min_val = 0, max_val = 1 ) rd.add_attr( ik_loc, 'fk', min_max = 'both', min_val = 0, max_val = 1 ) node = mc.createNode ( 'reverse', name = ik_loc + '_RVS' ) mc.connectAttr ( ik_loc + '.ik', node + '.inputX' ) mc.connectAttr ( node + '.outputX', ik_loc + '.fk' ) mc.setAttr ( ik_loc + '.fk', lock = True ) for obj in ik_fk_switch : slot_1 = mc.listConnections ( obj[0] + '.target[0].targetParentMatrix', d = 0, s = 1 ) slot_2 = mc.listConnections ( obj[0] + '.target[1].targetParentMatrix', d = 0, s = 1 ) mc.connectAttr ( ik_loc + '.ik' , obj[0] + '.' + slot_1[0] + 'W0' ) mc.connectAttr ( ik_loc + '.fk' , obj[0] + '.' + slot_2[0] + 'W1' ) ########################## # # Ik stretch if part == 'arm': if side == '_l_': num = 209 else: num = 210 else: if side == '_l_': num = 211 else: num = 212 dim = mc.distanceDimension( startPoint = [0, num, 0], endPoint = [0, num, 1]) mc.parent ( dim, arm_group ) locs = mc.listConnections( dim, source = True ) print 'LOCS ========' print locs mc.rename ( locs[0], part + side + 'Stretch_01_LOC' ) mc.rename ( locs[1], part + side + 'Stretch_02_LOC' ) dim = mc.rename ( dim, part + side + 'DIST' ) mdn_01 = mc.createNode ( 'multiplyDivide', name = part + side + '01_MDN' ) mdn_02 = mc.createNode ( 'multiplyDivide', name = part + side + '02_MDN') cnd_01 = mc.createNode ( 'condition', name = part + side + '01_CND' ) cnd_02 = mc.createNode ( 'condition', name = part + side + '02_CND' ) mc.connectAttr ( dim + '.distance', mdn_01 + '.input1X' ) mc.setAttr ( mdn_01 + '.input2X', mc.getAttr ( ik_arm[1] + '.translateX' ) + mc.getAttr ( ik_arm[2] + '.translateX' ) ) mc.setAttr ( mdn_01 + '.operation', 2 ) mc.connectAttr ( mdn_01 + '.outputX', mdn_02 + '.input1X' ) mc.connectAttr ( arm_group + '.global_scale_solver', mdn_02 + '.input2X' ) mc.setAttr ( mdn_02 + '.operation', 2 ) mc.connectAttr ( mdn_02 + '.outputX', cnd_01 + '.firstTerm' ) mc.setAttr ( cnd_01 + '.secondTerm', 1 ) mc.setAttr ( cnd_01 + '.operation', 2 ) mc.connectAttr ( mdn_02 + '.outputX', cnd_01 + '.colorIfTrueR' ) mc.setAttr ( cnd_01 + '.colorIfFalseR', 1 ) mc.connectAttr ( ik_ctl + '.stretch', cnd_02 + '.firstTerm' ) mc.setAttr ( cnd_02 + '.secondTerm', 1 ) mc.setAttr ( cnd_02 + '.operation', 0 ) mc.setAttr ( cnd_02 + '.colorIfFalseR', 1 ) mc.connectAttr ( cnd_01 + '.outColorR', cnd_02 + '.colorIfTrueR' ) mc.connectAttr ( cnd_02 + '.outColorR', ik_arm[0] + '.scaleX' ) mc.connectAttr ( cnd_02 + '.outColorR', ik_arm[1] + '.scaleX' )
def quadromatic(self, function, orientation): print function print orientation listObjs = mc.ls(sl=True) selSize = len(listObjs) num = 0 armJNames = ["scap", "shoulder", "elbow", "wrist", "hand"] legJNames = ["hip", "knee", "calf", "ankle", "toe"] try: if orientation == "left": orientString = "l_" if orientation == "right": orientString = "r_" except: print "No left or right directive entered" if function == "spine": print "spine function activated" for i in range(0, selSize, 1): mc.rename(listObjs[i], "spine" + "% d_jnt" % num) num += 1 lastJointNum = selSize-1 mc.ikHandle(sj="spine_0_jnt", ee="spine_" + "% d_jnt" % lastJointNum, sol="ikSplineSolver", ccv=True, ns=3, n="spine_ik") mc.rename("curve1", "spine_crv") mc.select(cl=True) mc.joint(n="spineBase_jntCtrl", rad=1.5) pointy1 = mc.pointConstraint("spine_0_jnt", "spineBase_jntCtrl") mc.delete(pointy1) mc.select(cl=True) mc.joint(n="spineEnd_jntCtrl", rad=1.5) pointy2 = mc.pointConstraint("spine_" + "% d_jnt" % lastJointNum, "spineEnd_jntCtrl") mc.delete(pointy2) mc.select("spineBase_jntCtrl") mc.select("spineEnd_jntCtrl", tgl=True) mc.select("spine_crv", tgl=True) mc.skinCluster() upperbodyFrontCtrl = mc.circle(n="upperbodyFront_ctrl", r=4) pointy3 = mc.pointConstraint("spineBase_jntCtrl",upperbodyFrontCtrl) mc.delete(pointy3) mc.select(upperbodyFrontCtrl) mc.makeIdentity("upperbodyFront_ctrl", a=True, t=True, r=True, s=True) mc.parentConstraint(upperbodyFrontCtrl, "spineBase_jntCtrl") upperbodyBackCtrl = mc.circle(n="upperbodyBack_ctrl", r=4) pointy4 = mc.pointConstraint("spineEnd_jntCtrl", upperbodyBackCtrl) mc.delete(pointy4) mc.select(upperbodyBackCtrl) mc.makeIdentity("upperbodyBack_ctrl", a=True, t=True, r=True, s=True) mc.parentConstraint(upperbodyBackCtrl, "spineEnd_jntCtrl") upperbodyGroupCtrl = mc.circle(n="upperbody_ctrl") mc.select(upperbodyGroupCtrl) mc.scale(16, 26, 16) mc.select(upperbodyGroupCtrl) mc.rotate(90, 0, 0, r=False) tempParent = mc.pointConstraint("spineBase_jntCtrl", "spineEnd_jntCtrl", upperbodyGroupCtrl) mc.delete(tempParent) mc.makeIdentity(upperbodyGroupCtrl, a=True, t=True, r=True, s=True) mc.parent(upperbodyFrontCtrl, upperbodyGroupCtrl) mc.parent(upperbodyBackCtrl, upperbodyGroupCtrl) if function == "arm": for i in range(0, selSize, 1): print armJNames[i] mc.rename(listObjs[i],orientString + armJNames[i] + "_jnt") num+=1 #Adding some Iks mc.ikHandle(sj=orientString + armJNames[0] + "_jnt", ee=orientString + armJNames[2] + "_jnt", sol="ikRPsolver", n=orientString + "upperarm_ik") mc.ikHandle(sj=orientString + armJNames[2] + "_jnt", ee=orientString + armJNames[3] + "_jnt", sol="ikSCsolver", n=orientString + "armhock_ik") mc.ikHandle(sj=orientString + armJNames[3] + "_jnt", ee=orientString + armJNames[4] + "_jnt", sol="ikSCsolver", n=orientString + "finger_ik") #Making some Curves, arranging them mc.curve(n=orientString+"hand_ctrl", p=[[0.5, 0.825, -0.75], [0.5, -0.001, -0.75], [-0.5, -0.001, -0.75], [-0.5, -0.001, 0.714], [0.5, -0.001, 0.714], [0.5, 0.546, 0.714], [-0.5, 0.546, 0.714], [-0.5, 0.825, -0.75], [0.5, 0.825, -0.75], [0.5, 0.546, 0.714], [0.5, -0.001, 0.714], [0.5, -0.001, -0.75], [-0.5, -0.001, -0.75], [-0.5, 0.825, -0.75], [-0.5, 0.546, 0.714], [-0.5, -0.001, 0.714]],d=1) mc.pointConstraint(orientString + armJNames[4] + "_jnt", orientString + armJNames[3] + "_jnt", orientString+"hand_ctrl", n="temp") mc.move(0, orientString+"hand_ctrl", y=True, r=False) handEndLoc = mc.spaceLocator() handStartLoc = mc.spaceLocator() mc.matchTransform(handEndLoc, orientString + armJNames[4] + "_jnt") mc.matchTransform(handStartLoc, orientString + armJNames[3] + "_jnt") handMeasureNode = mc.distanceDimension(handEndLoc, handStartLoc) handScaleFactor = mc.getAttr(handMeasureNode + ".distance") mc.scale(handScaleFactor, handScaleFactor, handScaleFactor, orientString+"hand_ctrl") mc.delete("temp") mc.delete(handMeasureNode) mc.delete(handEndLoc) mc.delete(handStartLoc) mc.circle(n=orientString+"handBall_ctrl") mc.matchTransform(orientString+"handBall_ctrl", orientString + armJNames[2] + "_jnt", rot=False) mc.rotate(-90,0,0, orientString+"handBall_ctrl", r=False) mc.makeIdentity(orientString+"hand_ctrl", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString+"handBall_ctrl", a=True, t=True, r=True, s=True) #Now the Locators, parenting them correctly and then positioning them appropriately mc.spaceLocator(n=orientString + "handHindHeelRoll_LOC") mc.spaceLocator(n=orientString + "handHindfingerRoll_LOC") mc.parent(orientString +"handHindfingerRoll_LOC", orientString +"handHindHeelRoll_LOC") mc.spaceLocator(n=orientString + "handHindTipRoll_LOC") mc.parent(orientString + "handHindTipRoll_LOC", orientString +"handHindfingerRoll_LOC") mc.spaceLocator(n=orientString + "handHindBallRoll_LOC") mc.parent(orientString + "handHindBallRoll_LOC", orientString +"handHindfingerRoll_LOC") mc.matchTransform(orientString + "handHindHeelRoll_LOC", orientString + armJNames[2] + "_jnt", rot=False, scl=False) mc.move(0, orientString + "handHindHeelRoll_LOC", y=True, r=False) mc.matchTransform(orientString + "handHindfingerRoll_LOC", orientString + armJNames[4] + "_jnt", rot=False, scl=False) mc.matchTransform(orientString + "handHindTipRoll_LOC", orientString + armJNames[3] + "_jnt", rot=False, scl=False) mc.matchTransform(orientString + "handHindBallRoll_LOC", orientString + armJNames[3] + "_jnt", rot=False, scl=False) #Parenting Everything! mc.parent(orientString + "armhock_ik", orientString+"hand_ctrl") mc.parent(orientString + "handHindHeelRoll_LOC", orientString+"hand_ctrl") mc.parent(orientString + "upperarm_ik", orientString+"handBall_ctrl") mc.parent(orientString+"handBall_ctrl", orientString + "handHindTipRoll_LOC") mc.parent(orientString + "finger_ik", orientString + "handHindBallRoll_LOC") mc.makeIdentity(orientString + "handHindHeelRoll_LOC", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString + "handHindfingerRoll_LOC", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString + "handHindTipRoll_LOC", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString + "handHindBallRoll_LOC", a=True, t=True, r=True, s=True) #Finally, set up new attributes on the hand control and connect them to the locator rotations mc.addAttr(orientString+"hand_ctrl", at='float', ln="HeelRoll", h=False, w=True) mc.setAttr(orientString+"hand_ctrl.HeelRoll", k=True, typ="float") mc.addAttr(orientString+"hand_ctrl", at='float', ln="fingerRoll", h=False, w=True) mc.setAttr(orientString+"hand_ctrl.fingerRoll", k=True, typ="float") mc.addAttr(orientString+"hand_ctrl", at='float', ln="TipRoll", h=False, w=True) mc.setAttr(orientString+"hand_ctrl.TipRoll", k=True, typ="float") mc.connectAttr(orientString+"hand_ctrl.HeelRoll", orientString + "handHindHeelRoll_LOC.rotateX") mc.connectAttr(orientString+"hand_ctrl.fingerRoll", orientString + "handHindfingerRoll_LOC.rotateX") mc.connectAttr(orientString+"hand_ctrl.TipRoll", orientString + "handHindBallRoll_LOC.rotateX") if function == "leg": for i in range(0, selSize, 1): mc.rename(listObjs[i],orientString + legJNames[i] + "_jnt") num+=1 #Adding some Iks mc.ikHandle(sj=orientString + legJNames[0] + "_jnt", ee=orientString + legJNames[2] + "_jnt", sol="ikRPsolver", n=orientString + "upperLeg_ik") mc.ikHandle(sj=orientString + legJNames[2] + "_jnt", ee=orientString + legJNames[3] + "_jnt", sol="ikSCsolver", n=orientString + "leghock_ik") mc.ikHandle(sj=orientString + legJNames[3] + "_jnt", ee=orientString + legJNames[4] + "_jnt", sol="ikSCsolver", n=orientString + "toe_ik") #Now the Locators, parenting them correctly and then positioning them appropriately mc.spaceLocator(n=orientString + "footHindHeelRoll_LOC") mc.spaceLocator(n=orientString + "footHindToeRoll_LOC") mc.parent(orientString +"footHindToeRoll_LOC", orientString +"footHindHeelRoll_LOC") mc.spaceLocator(n=orientString + "footHindTipRoll_LOC") mc.parent(orientString + "footHindTipRoll_LOC", orientString +"footHindToeRoll_LOC") mc.spaceLocator(n=orientString + "footHindBallRoll_LOC") mc.parent(orientString + "footHindBallRoll_LOC", orientString +"footHindToeRoll_LOC") mc.matchTransform(orientString + "footHindHeelRoll_LOC", orientString + legJNames[2] + "_jnt", rot=False, scl=False) mc.move(0, orientString + "footHindHeelRoll_LOC", y=True, r=False) mc.matchTransform(orientString + "footHindToeRoll_LOC", orientString + legJNames[4] + "_jnt", rot=False, scl=False) mc.matchTransform(orientString + "footHindTipRoll_LOC", orientString + legJNames[3] + "_jnt", rot=False, scl=False) mc.matchTransform(orientString + "footHindBallRoll_LOC", orientString + legJNames[3] + "_jnt", rot=False, scl=False) #Making some Curves, arranging them mc.curve(n=orientString+"foot_ctrl", p=[[0.5, 0.825, -0.75], [0.5, -0.001, -0.75], [-0.5, -0.001, -0.75], [-0.5, -0.001, 0.714], [0.5, -0.001, 0.714], [0.5, 0.546, 0.714], [-0.5, 0.546, 0.714], [-0.5, 0.825, -0.75], [0.5, 0.825, -0.75], [0.5, 0.546, 0.714], [0.5, -0.001, 0.714], [0.5, -0.001, -0.75], [-0.5, -0.001, -0.75], [-0.5, 0.825, -0.75], [-0.5, 0.546, 0.714], [-0.5, -0.001, 0.714]],d=1) mc.pointConstraint(orientString + legJNames[4] + "_jnt", orientString + legJNames[3] + "_jnt", orientString+"foot_ctrl", n="temp") mc.move(0, orientString+"foot_ctrl", y=True, r=False) footEndLoc = mc.spaceLocator() footStartLoc = mc.spaceLocator() mc.matchTransform(footEndLoc, orientString + legJNames[4] + "_jnt") mc.matchTransform(footStartLoc, orientString + legJNames[3] + "_jnt") measureNode = mc.distanceDimension(footEndLoc, footStartLoc) scaleFactor = mc.getAttr(measureNode + ".distance") mc.scale(scaleFactor, scaleFactor, scaleFactor, orientString+"foot_ctrl") mc.delete("temp") mc.delete(measureNode) mc.delete(footEndLoc) mc.delete(footStartLoc) mc.rotate(0,0,0, orientString+"foot_ctrl", r=False) mc.circle(n=orientString+"footBall_ctrl") mc.matchTransform(orientString+"footBall_ctrl", orientString + legJNames[2] + "_jnt", rot=False) mc.rotate(-90,0,0, orientString+"footBall_ctrl", r=False) mc.makeIdentity(orientString+"footBall_ctrl", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString+"foot_ctrl", a=True, t=True, r=True, s=True) #Parenting Everything! mc.parent(orientString + "leghock_ik", orientString+"foot_ctrl") mc.parent(orientString + "footHindHeelRoll_LOC", orientString+"foot_ctrl") mc.parent(orientString + "upperLeg_ik", orientString+"footBall_ctrl") mc.parent(orientString+"footBall_ctrl", orientString + "footHindTipRoll_LOC") mc.parent(orientString + "toe_ik", orientString + "footHindBallRoll_LOC") mc.makeIdentity(orientString + "footHindHeelRoll_LOC", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString + "footHindToeRoll_LOC", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString + "footHindTipRoll_LOC", a=True, t=True, r=True, s=True) mc.makeIdentity(orientString + "footHindBallRoll_LOC", a=True, t=True, r=True, s=True) #Finally, set up new attributes on the foot control and connect them to the locator rotations mc.addAttr(orientString+"foot_ctrl", at='float', ln="HeelRoll", h=False, w=True) mc.setAttr(orientString+"foot_ctrl.HeelRoll", k=True, typ="float") mc.addAttr(orientString+"foot_ctrl", at='float', ln="ToeRoll", h=False, w=True) mc.setAttr(orientString+"foot_ctrl.ToeRoll", k=True, typ="float") mc.addAttr(orientString+"foot_ctrl", at='float', ln="TipRoll", h=False, w=True) mc.setAttr(orientString+"foot_ctrl.TipRoll", k=True, typ="float") mc.connectAttr(orientString+"foot_ctrl.HeelRoll", orientString + "footHindHeelRoll_LOC.rotateX") mc.connectAttr(orientString+"foot_ctrl.ToeRoll", orientString + "footHindToeRoll_LOC.rotateX") mc.connectAttr(orientString+"foot_ctrl.TipRoll", orientString + "footHindBallRoll_LOC.rotateX") #Set up a knee controller mc.curve(n=orientString+"knee_ctrl", p=[[-1.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 0.0, -1.0], [-1.0, 0.0, 1.0]],d=1) tempPC = mc.pointConstraint(orientString + legJNames[1] + "_jnt", orientString+"knee_ctrl") mc.delete(tempPC) mc.move(5 * scaleFactor/2, orientString + "knee_ctrl", z=True, r=False) mc.poleVectorConstraint( orientString+"knee_ctrl", orientString + "upperLeg_ik") if function == "tail": #TAIL FUNCTION IS A WORK IN PROGRESS for i in range(0, selSize, 1): mc.rename(listObjs[i], "tail" + "% d_jnt" % num) num += 1
########################### ### MEASUREMENT TOOL ### ########################### import maya.cmds as cmds sl = cmds.ls(selection=True, flatten = True) oldLocators = cmds.ls(type = 'locator') oldDistances = cmds.ls(type = 'distanceDimShape') item1 = cmds.pointPosition( sl[0] ) item2 = cmds.pointPosition( sl[1] ) cmds.distanceDimension( startPoint = item1, endPoint= item2 ) newLocators = set(cmds.ls(type='locator')) - set(oldLocators) newDistances = set(cmds.ls(type='distanceDimShape')) - set(oldDistances) if len(newLocators) == 2: cmds.group(list(newLocators)[0], list(newLocators)[1] , list(newDistances)[0], n = 'measurement') elif len(newLocators) == 1: cmds.group(list(newLocators)[0], list(newDistances)[0], n = 'measurement') ########################### ### PLAYBLAST HUD3 ### ########################### import maya.cmds as cmds cmds.window(t='Playblast') icon = cmds.internalVar(upd = True) + 'icons/JR_icons/folder.jpg' mainLayout = cmds.columnLayout(w = 180, h = 80) rowColumnLayout = cmds.rowColumnLayout(nc = 3, cw = [(1, 50), (2, 60), (3, 60)] , columnOffset = [(1, 'both', 5), (2, 'both', 5), (3, 'both', 5)] ) # first section relates to 1 and 2 columb widths cmds.radioCollection() cmds.text( label='Frame:', align = 'left' ) cmds.radioButton( label='1080' ) cmds.radioButton( label='720' ) cmds.radioCollection() cmds.text( label='Format:', align = 'left' )
def SundayBetweenToolBuild(mode): sel = cmds.ls(selection = True) source = sel[0] target = [] type = None if mode == 'joint': if cmds.nodeType(sel[0]) == 'joint': target = cmds.listRelatives(source, children = True) type = 'joint' if target == None: print 'Joint has no children' return None else: print 'Not a joint' return None cmds.nodeType(sel[0]) == 'joint' if len(sel) < 2: print 'Not enough objects selected' return None for i in range(1, len(sel)): target.append(sel[i]) if cmds.objExists('Sunday_JointBox_Distance_GRP') == False: distanceHeadGroup = cmds.group(empty = True, name = 'Sunday_JointBox_Distance_GRP') cmds.setAttr(distanceHeadGroup + '.visibility', 0) else: distanceHeadGroup = 'Sunday_JointBox_Distance_GRP' buildObjects = [] betweenType = cmds.optionMenu('SundayControllerToolBetweenBuildType', query = True, value = True) for curTarget in target: if betweenType == 'Last Selected Object': if len(sel) > 2: if curTarget == sel[len(sel) - 1]: print sel[len(sel) - 1] break if type == 'joint': while cmds.nodeType(curTarget) == 'transform': curTarget = cmds.listRelatives(curTarget, children = True) continue len(sel) < 2 dummy = cmds.polyCube() tpCon = cmds.pointConstraint(source, dummy) sourcePos = cmds.xform(dummy, query = True, worldSpace = True, translation = True) cmds.delete(tpCon) tpCon = cmds.pointConstraint(curTarget, dummy) curTargetPos = cmds.xform(dummy, query = True, worldSpace = True, translation = True) cmds.delete(tpCon) cmds.delete(dummy) distanceShape = cmds.distanceDimension(sp = sourcePos, ep = curTargetPos) distance = cmds.getAttr(distanceShape + '.distance') locators = cmds.listConnections(distanceShape) distanceGrp = cmds.group(empty = True, parent = distanceHeadGroup, name = distanceShape + 'Distance_GRP') cmds.parent(distanceShape, distanceGrp) cmds.parent(locators, distanceGrp) cmds.parentConstraint(source, locators[0], maintainOffset = True) cmds.parentConstraint(curTarget, locators[1], maintainOffset = True) if betweenType == 'Box': betweenObj = cmds.polyCube(name = 'Sunday_JointBox')[0] cmds.xform(betweenObj, pivots = (-4.62069e+18, 0, 0)) cmds.move(4.60268e+18, 0, 0, betweenObj) mel.eval('FreezeTransformations;') elif betweenType == 'Cylinder': betweenObj = cmds.polyCylinder(name = 'Sunday_JointCylinder', height = 1)[0] cmds.rotate(0, 0, 90, betweenObj) mel.eval('FreezeTransformations;') cmds.xform(betweenObj, pivots = (-4.62069e+18, 0, 0)) cmds.move(4.60268e+18, 0, 0, betweenObj) mel.eval('FreezeTransformations;') elif betweenType == 'Helix (Spring)': betweenObj = cmds.polyHelix(name = 'Sunday_JointHelix', height = 1, radius = 4.57692e+18)[0] cmds.rotate(0, 0, 90, betweenObj) mel.eval('FreezeTransformations;') cmds.xform(betweenObj, pivots = (-4.62069e+18, 0, 0)) cmds.move(4.60268e+18, 0, 0, betweenObj) mel.eval('FreezeTransformations;') elif betweenType == 'Last Selected Object': betweenObj = cmds.duplicate(sel[len(sel) - 1], smartTransform = True)[0] cmds.select(betweenObj) mel.eval('FreezeTransformations;') mel.eval('CenterPivot;') bb = cmds.polyEvaluate(boundingBox = True) cmds.xform(betweenObj, pivots = (0, bb[1][0], 0)) cmds.move(0, bb[1][1], 0, betweenObj) mel.eval('FreezeTransformations;') cmds.rotate(0, 0, -90, betweenObj) mel.eval('FreezeTransformations;') bb = cmds.polyEvaluate(boundingBox = True) cmds.scale(1 / bb[0][1], 1, 1) mel.eval('FreezeTransformations;') buildObjects.append(betweenObj) constraintGrp = cmds.group(empty = True, parent = distanceGrp, name = distanceShape + 'Constraint_GRP') pCon = cmds.pointConstraint(source, betweenObj) cmds.parent(pCon, constraintGrp) aCon = cmds.aimConstraint(curTarget, betweenObj) cmds.parent(aCon, constraintGrp) cmds.connectAttr(distanceShape + '.distance', betweenObj + '.scaleX', force = True) objScale = cmds.textField('SundayControllerToolBetweenWidthScale', query = True, text = True) cmds.setAttr(betweenObj + '.scaleY', float(objScale)) cmds.setAttr(betweenObj + '.scaleZ', float(objScale)) if cmds.checkBox('SundayControllerToolBetweenDynamicScaleCheckBox', query = True, value = True) == False: cmds.delete(locators) continue len(sel) < 2 if cmds.checkBox('SundayControllerToolBetweenSelectObjectsCheckBox', query = True, value = True) == True: cmds.select(buildObjects) else: cmds.select(sel) return buildObjects
def createStretchyIk(self, ikJnts, ikKneeJnt, footCtrl, ikBallJnt, part, *args): print "I CSIK" pHip = ikJnts[0] pKnee = ikKneeJnt pAnkle = ikJnts[1] pBall = ikBallJnt ikJntArray = (pHip, pAnkle) """ First we will handle all the stretchy nodes """ """ Create locators for defining the distance between joints""" stretchPoints = [] stretchPositions = [] for jnt in ikJntArray: lctrName = jnt.replace("Jnt_", "LctrPos_") lctrPos = cmds.xform(jnt, q=True, ws=True, t=True) stretchPositions.append(lctrPos) distNamePrefix = pHip.replace("Jnt_", "disB_") distN = cmds.distanceDimension(sp=(stretchPositions[0]), ep=(stretchPositions[1])) distNode = distNamePrefix cmds.rename(distN, distNamePrefix) disdimCon = cmds.listConnections(distNode) for locator in disdimCon: stretchPoints.append(locator) """ Create nodes for stretchy """ mdivNamePrefix = pHip.replace("Jnt_", "mDiv_") mdivNode = cmds.shadingNode("multiplyDivide", asUtility=True, n=mdivNamePrefix) conNamePrefix = pHip.replace("Jnt_", "conN_") conNode = cmds.shadingNode("condition", asUtility=True, n=conNamePrefix) """ Pont constrain stretchPoints[0] to hip and stretchPoints[1] to ankle """ cmds.pointConstraint(pHip, stretchPoints[0], mo=True) cmds.parent(stretchPoints[1], footCtrl[0]) """ Connect stPoint[0].translate to distNode.point1.XYZ """ #cmds.connectAttr(stretchPoints[0]+".translate", distNode+".point1") """ Connect stPoint[1].translate to distNode.point2.XYZ """ #cmds.connectAttr(stretchPoints[1]+".translate", distNode+".point2") """ Connect the distNode.distance to conNode.firstTerm""" cmds.connectAttr(distNode + ".distance", conNode + ".firstTerm") """ Connect distNode.distance to mdivNode.input1X """ cmds.connectAttr(distNode + ".distance", mdivNode + ".input1X") """ Connect mdivNode.output1X to conNode.colorIfTrueR """ cmds.connectAttr(mdivNode + ".outputX", conNode + ".colorIfTrue.colorIfTrueR") """ Set mdivNode to "divide" and conNode to "greater than or equal" """ cmds.setAttr(mdivNode + ".operation", 2) cmds.setAttr(conNode + ".operation", 3) """ Connect conNode.outColorR to scale of hip and knee bones """ if part == 1: cmds.setAttr(footCtrl[0] + ".l1_stretch", 62) cmds.connectAttr(conNode + ".outColorR", pHip + ".scaleX") #cmds.connectAttr(conNode+".outColorR", pKnee+".scaleX") #cmds.connectAttr(conNode+".outColorR", pAnkle+".scaleY") """ Stretch attr connected to conNode.secondTerm and mdivNode.input2X """ """ For Hip 0.250 """ cmds.connectAttr(footCtrl[0] + ".l1_stretch", conNode + ".secondTerm") cmds.connectAttr(footCtrl[0] + ".l1_stretch", mdivNode + ".input2X") if part == 2: cmds.setAttr(footCtrl[0] + ".l1_stretch", 62) cmds.connectAttr(conNode + ".outColorR", pHip + ".scaleX") #cmds.connectAttr(conNode+".outColorR", pKnee+".scaleX") #cmds.connectAttr(conNode+".outColorR", pAnkle+".scaleY") """ Stretch attr connected to conNode.secondTerm and mdivNode.input2X """ """ For Hip 0.250 """ cmds.setAttr(footCtrl[0] + ".l2_stretch", 62) cmds.connectAttr(footCtrl[0] + ".l2_stretch", conNode + ".secondTerm") cmds.connectAttr(footCtrl[0] + ".l2_stretch", mdivNode + ".input2X")
def __init__(self, character): #before you switch, create a locator for the neck position neckLoc = cmds.spaceLocator(name = "roto_neck_locator")[0] constraintNeckLoc = cmds.parentConstraint(character + ":neck_01_fk_anim", neckLoc)[0] cmds.delete(constraintNeckLoc) constraint = cmds.orientConstraint("spine_01", character + ":spine_01_anim")[0] cmds.setKeyframe(character + ":spine_01_anim") cmds.delete(constraint) constraint = cmds.orientConstraint(character + ":twist_splineIK_spine_03", character + ":spine_03_anim", skip = ["y", "z"])[0] cmds.setKeyframe(character + ":spine_03_anim.rx") cmds.delete(constraint) constraint = cmds.orientConstraint(character + ":chest_ik_anim", character + ":spine_05_anim", skip = ["y", "z"])[0] cmds.setKeyframe(character + ":spine_05_anim.rx") cmds.delete(constraint) #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# # # #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# #create (rotate) Y dist locators for the spine spineStartPointY = cmds.xform(character + ":twist_splineIK_spine_05", q = True, ws = True, t = True)[0] spineEndPointY = cmds.xform(character + ":spine_05_anim", q = True, ws = True, t = True)[0] spineDistY = cmds.distanceDimension( sp = (spineStartPointY, 0, 0), ep = (spineEndPointY, 0, 0)) spineDistYParent = cmds.listRelatives(spineDistY, parent = True)[0] spineLocs = cmds.listConnections(spineDistY) spineStartLocY = spineLocs[0] spineEndLocY = spineLocs[1] cmds.pointConstraint(character + ":twist_splineIK_spine_05", spineStartLocY, skip = ["y", "z"], mo = True) cmds.pointConstraint(character + ":spine_05_anim", spineEndLocY, skip = ["y", "z"], mo = True) #get the distance. if distance is greater than .05, then modify rotations currentYDist = cmds.getAttr(spineDistY + ".distance") self.checkDistance(character, spineDistY, currentYDist, currentYDist, ".ry", "spine_03_anim") try: cmds.delete(spineDistYParent) cmds.delete(spineStartLocY) cmds.delete(spineEndLocY) except: pass #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# # # #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# #create (rotate) Z dist locators for the spine spineStartPointZ = cmds.xform(character + ":twist_splineIK_spine_05", q = True, ws = True, t = True)[1] spineEndPointZ = cmds.xform(character + ":spine_05_anim", q = True, ws = True, t = True)[1] spineDistZ = cmds.distanceDimension( sp= (0, spineStartPointZ,0), ep=(0, spineEndPointZ, 0) ) spineDistZParent = cmds.listRelatives(spineDistZ, parent = True)[0] spineZLocs = cmds.listConnections(spineDistZ) spineStartLocZ = spineZLocs[0] spineEndLocZ = spineZLocs[1] cmds.pointConstraint(character + ":twist_splineIK_spine_05", spineStartLocZ, skip = ["x", "z"], mo = True) cmds.pointConstraint(character + ":spine_05_anim", spineEndLocZ, skip = ["x", "z"], mo = True) currentZDist = cmds.getAttr(spineDistZ + ".distance") self.checkDistance(character, spineDistZ, currentZDist, currentZDist, ".rz", "spine_03_anim") try: cmds.delete(spineDistZParent) cmds.delete(spineStartLocZ) cmds.delete(spineEndLocZ) except: pass #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# # # #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# cmds.setAttr(character + ":Rig_Settings.spine_ik", 0) cmds.setAttr(character + ":Rig_Settings.spine_fk", 1) #create (rotate) Y dist locators for the neck neckStartPointY = cmds.xform(neckLoc, q = True, ws = True, t = True)[0] neckEndPointY = cmds.xform(character + ":neck_01_fk_anim", q = True, ws = True, t = True)[0] neckDistY = cmds.distanceDimension( sp= (neckStartPointY,0, 0), ep=(neckEndPointY, 0, 0) ) neckDistYParent = cmds.listRelatives(neckDistY, parent = True)[0] neckYLocs = cmds.listConnections(neckDistY) neckStartLocY = neckYLocs[0] neckEndLocY = neckYLocs[1] cmds.pointConstraint(neckLoc, neckStartLocY, skip = ["y", "z"], mo = True) cmds.pointConstraint(character + ":neck_01_fk_anim", neckEndLocY, skip = ["y", "z"], mo = True) currentNeckYDist = cmds.getAttr(neckDistY + ".distance") self.checkDistance(character, neckDistY, currentNeckYDist, currentNeckYDist, ".ry", "spine_05_anim") try: cmds.delete(neckDistYParent) cmds.delete(neckStartLocY) cmds.delete(neckEndLocY) except: pass #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# # # #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# cmds.setAttr(character + ":Rig_Settings.spine_ik", 0) cmds.setAttr(character + ":Rig_Settings.spine_fk", 1) #create (rotate) Z dist locators for the neck neckStartPointZ = cmds.xform(neckLoc, q = True, ws = True, t = True)[1] neckEndPointZ = cmds.xform(character + ":neck_01_fk_anim", q = True, ws = True, t = True)[1] neckDistZ = cmds.distanceDimension( sp= (0, neckStartPointZ,0), ep=(0, neckEndPointZ, 0) ) neckDistZParent = cmds.listRelatives(neckDistZ, parent = True)[0] neckZLocs = cmds.listConnections(neckDistZ) neckStartLocZ = neckZLocs[0] neckEndLocZ = neckZLocs[1] cmds.pointConstraint(neckLoc, neckStartLocZ, skip = ["x", "z"], mo = True) cmds.pointConstraint(character + ":neck_01_fk_anim", neckEndLocZ, skip = ["x", "z"], mo = True) currentNeckZDist = cmds.getAttr(neckDistZ + ".distance") self.checkDistance(character, neckDistZ, currentNeckZDist, currentNeckZDist, ".rz", "spine_05_anim") try: cmds.delete(neckDistZParent) cmds.delete(neckStartLocZ) cmds.delete(neckEndLocZ) except: pass #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# # # #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# cmds.delete(neckLoc)
def measureBoundingBox(geo): ''' Create visual distance dimensions for the specified geometry or geometry group. @param geo: Geometry or geometry group to create distance dimensions for. @type geo: str ''' # Check Geo if not mc.objExists(geo): raise Exception('Geometry "'+geo+'" does not exist!!') # ============================== # - Create Distance Dimensions - # ============================== del_locs = [] # Height hDimensionShape = mc.distanceDimension(sp=(0,0,0),ep=(1,1,1)) locs = mc.listConnections(hDimensionShape,s=True,d=False) or [] del_locs += locs hDimension = mc.listRelatives(hDimensionShape,p=True)[0] hDimension = mc.rename(hDimension,geo+'_height_measure') # Width wDimensionShape = mc.distanceDimension(sp=(0,0,0),ep=(1,1,1)) locs = mc.listConnections(wDimensionShape,s=True,d=False) or [] del_locs += locs wDimension = mc.listRelatives(wDimensionShape,p=True)[0] wDimension = mc.rename(wDimension,geo+'_width_measure') # Depth dDimensionShape = mc.distanceDimension(sp=(0,0,0),ep=(1,1,1)) locs = mc.listConnections(dDimensionShape,s=True,d=False) or [] del_locs += locs dDimension = mc.listRelatives(dDimensionShape,p=True)[0] dDimension = mc.rename(dDimension,geo+'_depth_measure') # Group measure_grp = mc.group([hDimension,wDimension,dDimension],n=geo+'_measure_grp') # =============================== # - Connect Distance Dimensions - # =============================== # Height mc.connectAttr(geo+'.boundingBoxMin',hDimension+'.startPoint',f=True) addHeightNode = mc.createNode('plusMinusAverage',n=geo+'_height_plusMinusAverage') mc.connectAttr(geo+'.boundingBoxMin',addHeightNode+'.input3D[0]',f=True) mc.connectAttr(geo+'.boundingBoxSizeY',addHeightNode+'.input3D[1].input3Dy',f=True) mc.connectAttr(addHeightNode+'.output3D',hDimension+'.endPoint',f=True) # Width mc.connectAttr(geo+'.boundingBoxMin',wDimension+'.startPoint',f=True) addWidthNode = mc.createNode('plusMinusAverage',n=geo+'_width_plusMinusAverage') mc.connectAttr(geo+'.boundingBoxMin',addWidthNode+'.input3D[0]',f=True) mc.connectAttr(geo+'.boundingBoxSizeX',addWidthNode+'.input3D[1].input3Dx',f=True) mc.connectAttr(addWidthNode+'.output3D',wDimension+'.endPoint',f=True) # Depth mc.connectAttr(geo+'.boundingBoxMin',dDimension+'.startPoint',f=True) addDepthNode = mc.createNode('plusMinusAverage',n=geo+'_depth_plusMinusAverage') mc.connectAttr(geo+'.boundingBoxMin',addDepthNode+'.input3D[0]',f=True) mc.connectAttr(geo+'.boundingBoxSizeZ',addDepthNode+'.input3D[1].input3Dz',f=True) mc.connectAttr(addDepthNode+'.output3D',dDimension+'.endPoint',f=True) # Delete Unused Locators if del_locs: mc.delete(del_locs) # Return Result return measure_grp
def ikfkStretch(JNTS=[], LOCS=[]): IKH = cmds.ikHandle(n="HAND_IKH", sj=JNTS[0], ee=JNTS[2], sol='ikRPsolver') PVC = cmds.poleVectorConstraint(LOCS[1], IKH[0], n='HAND_PVC') cmds.parent(PVC, LOCS[2]) cmds.parent(JNTS[0], LOCS[0]) hipPos = cmds.xform(JNTS[0], q=True, ws=True, t=True) anklePos = cmds.xform(IKH[0], q=True, ws=True, t=True) pelvisPos = cmds.xform(LOCS[0], q=True, ws=True, t=True) cmds.addAttr(LOCS[2], shortName='Twist', longName='Twist', defaultValue=0, k=True) PMA = str( cmds.shadingNode("plusMinusAverage", asUtility=True, n='HAND_TWIST_PMA')) NMD = str( cmds.shadingNode("multiplyDivide", asUtility=True, n='HAND_TWIST_NMD')) cmds.connectAttr(str(LOCS[2]) + '.Twist', NMD + '.input1X') cmds.connectAttr(str(LOCS[2]) + '.ry', NMD + '.input1Y') cmds.connectAttr(str(LOCS[0]) + '.ry', NMD + '.input1Z') cmds.setAttr(NMD + '.input2X', -1) cmds.setAttr(NMD + '.input2Y', -1) cmds.setAttr(NMD + '.input2Z', -1) cmds.connectAttr(NMD + '.input1X', PMA + '.input1D[0]') cmds.connectAttr(NMD + '.input1Y', PMA + '.input1D[1]') cmds.connectAttr(PMA + '.output1D', IKH[0] + '.twist') ADL = str( cmds.shadingNode("addDoubleLinear", asUtility=True, n='HAND_STRETCH_ADL')) CMP = str(cmds.shadingNode("clamp", asUtility=True, n='HAND_STRETCH_CMP')) NMD_HAND_CNT = str( cmds.shadingNode("multiplyDivide", asUtility=True, n='HAND_STRETCHCNT_NMD')) NMD_RODILLA = str( cmds.shadingNode("multiplyDivide", asUtility=True, n='HAND_STRETCHRODILLA_NMD')) NMD_MUNIECA = str( cmds.shadingNode("multiplyDivide", asUtility=True, n='HAND_STRETCHMUNIECA_NMD')) cmds.addAttr(LOCS[2], shortName='Stretch', longName='Stretch', defaultValue=0, k=True) hipPos = cmds.xform(JNTS[0], q=True, ws=True, t=True) anklePos = cmds.xform(IKH[0], q=True, ws=True, t=True) disDim = cmds.distanceDimension(sp=(hipPos), ep=(anklePos)) disDim = cmds.rename(disDim, 'HAND_STRETCH_DDN') kneeLen = cmds.getAttr(str(LOCS[0]) + '.tx') ankleLen = cmds.getAttr(str(LOCS[2]) + '.tx') legLen = (kneeLen + ankleLen) cmds.setAttr(ADL + '.input2', legLen) cmds.setAttr(NMD_HAND_CNT + '.input2X', legLen) cmds.setAttr(NMD_RODILLA + '.input2X', kneeLen) cmds.setAttr(NMD_MUNIECA + '.input2X', ankleLen) cmds.connectAttr(str(LOCS[2]) + '.Stretch', ADL + '.input1') cmds.setAttr(CMP + ".minR", 12.800084) cmds.setAttr(NMD_HAND_CNT + ".operation", 2) cmds.connectAttr(disDim + '.distance', CMP + '.inputR') cmds.connectAttr(ADL + '.output', CMP + '.maxR') cmds.connectAttr(CMP + '.outputR', NMD_HAND_CNT + '.input1X') cmds.connectAttr(NMD_HAND_CNT + '.outputX', NMD_RODILLA + '.input1X') cmds.connectAttr(NMD_HAND_CNT + '.outputX', NMD_MUNIECA + '.input1X') cmds.connectAttr(NMD_RODILLA + '.outputX', str(JNTS[1]) + '.tx') cmds.connectAttr(NMD_MUNIECA + '.outputX', str(JNTS[2]) + '.tx') CDN = str( cmds.shadingNode("condition", asUtility=True, n='HAND_STRETCH_CDN')) cmds.connectAttr(disDim + '.distance', CDN + '.firstTerm')
def rpStretchy(self,*args): # # Full length distance dimension node # #Get world space of ik_1 and ik_end joints, used to place distDimension node locators ikBaseJntPos = mc.xform(self.joints[0],query=True,t=True,ws=True) ikEndJntPos = mc.xform(self.joints[1],query=True,t=True,ws=True) #Create distanceDimensionShape node. Create locators at locations that do not have locators. fullLen_DDNodeShape = mc.distanceDimension( sp=[1,0,0], ep=[0,1,0] ) #Get created locators names temp = mc.listConnections(fullLen_DDNodeShape) temp1 = temp[0] temp2 = temp[1] #Rename locators mc.rename(temp1,('%s%sfullLen_start'%(self.prefix,temp1) ) ) mc.rename(temp2,('%s%sfullLen_end'%(self.prefix,temp2) ) ) #Rename Distance Dimension node temp = mc.pickWalk(fullLen_DDNodeShape,direction='up') mc.rename(temp[0],('%s%sfullLen_DDnode'%(self.prefix,temp[0]) ) ) #Store names fullLenLoc_start = '%s%sfullLen_start'%(self.prefix,temp1) fullLenLoc_end = '%s%sfullLen_end'%(self.prefix,temp2) fullLen_DDNode = '%s%sfullLen_DDnode'%(self.prefix,temp[0]) fullLen_DDNodeShape = '%s%sfullLen_DDnodeShape'%(self.prefix,temp[0]) #Now, snap the locators to the right position. mc.move(ikBaseJntPos[0],ikBaseJntPos[1],ikBaseJntPos[2],fullLenLoc_start,moveXYZ=True) mc.move(ikEndJntPos[0],ikEndJntPos[1],ikEndJntPos[2],fullLenLoc_end,moveXYZ=True) distGrp = self.prefix + '_distGrp' mc.group(em=True,n=distGrp) mc.parent(fullLenLoc_start,fullLenLoc_end,fullLen_DDNode,distGrp) mc.setAttr(distGrp + '.visibility',0) #point constraint locators fullLenDD_startLoc_PC = mc.pointConstraint(self.joints[0], fullLenLoc_start,mo=False) fullLenDD_endLoc_PC = mc.pointConstraint(self.ikHandle, fullLenLoc_end,mo=False) #Get dimension value origLen = mc.getAttr(fullLen_DDNodeShape + '.distance') # # Now, lets create the stretchy expression for one knee scenario # if self.kneeNum == 1: topJntLength = mc.getAttr('%s.translate%s'%(self.jointChain[1],self.axisVal) ) btmJntLength = mc.getAttr('%s.translate%s'%(self.jointChain[2],self.axisVal) ) fullLength = topJntLength + btmJntLength fullLength = abs(fullLength) # Absolute values because distance should never be negative topJntLength = abs(topJntLength) btmJntLength = abs(btmJntLength) driver = fullLen_DDNodeShape + '.distance' #Create SDKs if self.bAlong == 'positive': mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=fullLength,at=('translate%s'%self.axisVal),v=topJntLength) mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=(fullLength*5),at=('translate%s'%self.axisVal),v=(topJntLength*5) ) mc.setDrivenKeyframe(self.jointChain[2],cd=driver,dv=fullLength,at=('translate%s'%self.axisVal),v=btmJntLength) mc.setDrivenKeyframe(self.jointChain[2],cd=driver,dv=(fullLength*5),at=('translate%s'%self.axisVal),v=(btmJntLength*5) ) if self.bAlong == 'negative': mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=-fullLength,at=('translate%s'%self.axisVal),v=topJntLength) mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=-(fullLength*5),at=('translate%s'%self.axisVal),v=(topJntLength*5) ) mc.setDrivenKeyframe(self.jointChain[2],cd=driver,dv=-fullLength,at=('translate%s'%self.axisVal),v=btmJntLength) mc.setDrivenKeyframe(self.jointChain[2],cd=driver,dv=-(fullLength*5),at=('translate%s'%self.axisVal),v=(btmJntLength*5) ) mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=0,at=('translate%s'%self.axisVal),v=topJntLength ) mc.setDrivenKeyframe(self.jointChain[2],cd=driver,dv=0,at=('translate%s'%self.axisVal),v=btmJntLength ) print "Don't forget to make the SDK curves linear and infinite." # # Now, lets create the stretchy expression for two knee scenario # if self.kneeNum == 2: topJntLength = mc.getAttr('%s.translate%s'%(self.jointChain[1],self.axisVal) ) midJntLength = mc.getAttr('%s.translate%s'%(self.jointChain[2],self.axisVal) ) btmJntLength = mc.getAttr('%s.translate%s'%(self.jointChain[3],self.axisVal) ) fullLength = topJntLength + midJntLength + btmJntLength driver = fullLen_DDNodeShape + '.distance' #Create SDKs if self.bAlong == 'positive': mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=fullLength,at=('translate%s'%self.axisVal),v=topJntLength) mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=(fullLength*5),at=('translate%s'%self.axisVal),v=(topJntLength*5) ) mc.setDrivenKeyframe(self.jointChain[3],cd=driver,dv=fullLength,at=('translate%s'%self.axisVal),v=btmJntLength) mc.setDrivenKeyframe(self.jointChain[3],cd=driver,dv=(fullLength*5),at=('translate%s'%self.axisVal),v=(btmJntLength*5) ) if self.bAlong == 'negative': mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=-fullLength,at=('translate%s'%self.axisVal),v=topJntLength) mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=-(fullLength*5),at=('translate%s'%self.axisVal),v=(topJntLength*5) ) mc.setDrivenKeyframe(self.jointChain[3],cd=driver,dv=-fullLength,at=('translate%s'%self.axisVal),v=btmJntLength) mc.setDrivenKeyframe(self.jointChain[3],cd=driver,dv=-(fullLength*5),at=('translate%s'%self.axisVal),v=(btmJntLength*5) ) mc.setDrivenKeyframe(self.jointChain[1],cd=driver,dv=0,at=('translate%s'%self.axisVal),v=topJntLength ) mc.setDrivenKeyframe(self.jointChain[3],cd=driver,dv=0,at=('translate%s'%self.axisVal),v=btmJntLength ) print "Don't forget to make the SDK curves linear and infinite."
def measureBoundingBox(geo): """ Create visual distance dimensions for the specified geometry or geometry group. @param geo: Geometry or geometry group to create distance dimensions for. @type geo: str """ # Check Geo if not cmds.objExists(geo): raise Exception('Geometry "' + geo + '" does not exist!!') # ============================== # - Create Distance Dimensions - # ============================== del_locs = [] # Height hDimensionShape = cmds.distanceDimension(sp=(0, 0, 0), ep=(1, 1, 1)) locs = cmds.listConnections(hDimensionShape, s=True, d=False) or [] del_locs += locs hDimension = cmds.listRelatives(hDimensionShape, p=True)[0] hDimension = cmds.rename(hDimension, geo + '_height_measure') # Width wDimensionShape = cmds.distanceDimension(sp=(0, 0, 0), ep=(1, 1, 1)) locs = cmds.listConnections(wDimensionShape, s=True, d=False) or [] del_locs += locs wDimension = cmds.listRelatives(wDimensionShape, p=True)[0] wDimension = cmds.rename(wDimension, geo + '_width_measure') # Depth dDimensionShape = cmds.distanceDimension(sp=(0, 0, 0), ep=(1, 1, 1)) locs = cmds.listConnections(dDimensionShape, s=True, d=False) or [] del_locs += locs dDimension = cmds.listRelatives(dDimensionShape, p=True)[0] dDimension = cmds.rename(dDimension, geo + '_depth_measure') # Group measure_grp = cmds.group([hDimension, wDimension, dDimension], n=geo + '_measure_grp') # =============================== # - Connect Distance Dimensions - # =============================== # Height cmds.connectAttr(geo + '.boundingBoxMin', hDimension + '.startPoint', f=True) addHeightNode = cmds.createNode('plusMinusAverage', n=geo + '_height_plusMinusAverage') cmds.connectAttr(geo + '.boundingBoxMin', addHeightNode + '.input3D[0]', f=True) cmds.connectAttr(geo + '.boundingBoxSizeY', addHeightNode + '.input3D[1].input3Dy', f=True) cmds.connectAttr(addHeightNode + '.output3D', hDimension + '.endPoint', f=True) # Width cmds.connectAttr(geo + '.boundingBoxMin', wDimension + '.startPoint', f=True) addWidthNode = cmds.createNode('plusMinusAverage', n=geo + '_width_plusMinusAverage') cmds.connectAttr(geo + '.boundingBoxMin', addWidthNode + '.input3D[0]', f=True) cmds.connectAttr(geo + '.boundingBoxSizeX', addWidthNode + '.input3D[1].input3Dx', f=True) cmds.connectAttr(addWidthNode + '.output3D', wDimension + '.endPoint', f=True) # Depth cmds.connectAttr(geo + '.boundingBoxMin', dDimension + '.startPoint', f=True) addDepthNode = cmds.createNode('plusMinusAverage', n=geo + '_depth_plusMinusAverage') cmds.connectAttr(geo + '.boundingBoxMin', addDepthNode + '.input3D[0]', f=True) cmds.connectAttr(geo + '.boundingBoxSizeZ', addDepthNode + '.input3D[1].input3Dz', f=True) cmds.connectAttr(addDepthNode + '.output3D', dDimension + '.endPoint', f=True) # Delete Unused Locators if del_locs: cmds.delete(del_locs) # Return Result return measure_grp
def makePlait(*pArgs): _depth = cm.intSliderGrp('subdivisionCurve', q=True, v=True) _width = cm.floatSliderGrp('braidWidth', q=True, v=True) #_depth*=2 _width *= 2 cm.rename('braid_CRV') cm.rebuildCurve(cm.ls(sl=True), ch=True, rpo=True, rt=False, end=True, kr=False, kcp=False, kep=True, kt=False, s=_depth, tol=0.01) piv1 = cm.xform('braid_CRV.cv[0]', q=True, t=True, ws=True) piv3 = cm.xform('braid_CRV.cv[' + str(_depth) + ']', q=True, t=True, ws=True) cm.distanceDimension(ep=(piv3[0], piv3[1], piv3[2]), sp=(piv1[0], piv1[1], piv1[2])) dist = cm.getAttr('distanceDimension1.distance') moveY = float(dist) / float(_depth / 2.0) #1.2 if _depth % 2 != 0: _depth += 1 switch = 1 for i in range(0, _depth): switch *= -1 if i % 3 == 0 and switch > 0: cm.select('braid_CRV.ep[' + str(i + 1) + ']', add=True) cm.select('braid_CRV.ep[' + str(i + 2) + ']', add=True) cm.move(_width, 0, 0, r=True, os=True) cm.select(deselect=True) for i in range(0, _depth): switch *= -1 if i % 3 == 0 and switch < 0: cm.select('braid_CRV.ep[' + str(i + 1) + ']', add=True) cm.select('braid_CRV.ep[' + str(i + 2) + ']', add=True) cm.move(-_width, 0, 0, r=True, os=True) cm.select(deselect=True) for i in range(0, _depth): if i % 3 == 0: cm.select('braid_CRV.ep[' + str(i + 1) + ']', add=True) cm.move(0, 0, _width * 2, r=True, os=True) cm.select(deselect=True) for i in range(0, _depth): if i % 3 == 0: cm.select('braid_CRV.ep[' + str(i + 2) + ']', add=True) cm.move(0, 0, -_width * 2, r=True, os=True) cm.polyCylinder(n='polyCircle', sx=5, sy=0, sz=1) cm.select('polyCircle.f[0:9]') cm.delete() piv = cm.xform('braid_CRV.cv[0]', q=True, t=True, ws=True) cm.move(piv[0], piv[1], piv[2], 'polyCircle', ws=True, a=True) float(moveY) cm.scale(float(moveY * 0.1), float(moveY * 0.1), float(moveY * 0.05), 'polyCircle', os=True) cm.select('polyCircle.f[0:4]', add=True) maya.mel.eval( 'polyExtrudeFacet -constructionHistory 1 -keepFacesTogether 1 -pvx 0.09549146891 -pvy 21.69501618 -pvz -25.49619563 -divisions 1 -twist 0 -taper 1 -off 0 -thickness 0 -smoothingAngle 30 -inputCurve braid_CRV polyCircle.f[0:4];' ) cm.setAttr('polyExtrudeFace1.divisions', 50) #make unique maya.mel.eval( 'polyNormal -normalMode 0 -userNormalMode 0 -ch 1 polyCircle;') cm.duplicate('polyCircle', n='polyCircle2') cm.move(0, float(moveY), 0, 'polyCircle2', r=True) # cm.move(0, float(_depth/moveY), 0, 'polyCircle2', r=True) cm.duplicate('polyCircle2', n='polyCircle3') cm.move(0, float(moveY), 0, 'polyCircle3', r=True) #cm.move(0, float(_depth/moveY), 0, 'polyCircle3', r=True) print _depth cm.polyUnite('polyCircle*', n='DONE_braid') maya.mel.eval('DeleteHistory;') cm.rename('braid_CRV', 'DONE_braid') cm.delete('distanceDimension1', 'locator1', 'locator2')
def streatchy_ik(self, ik='', ik_ctrl='', top_ctrl='', pv_ctrl='', attrs_location='', name='', axis='Y'): ''' create a ik stretchy system for the simple ik chain (only 3 joints allowed) ''' if ik == '': ik = cmds.ls(sl=True) if name == '': name = ik #get components in the ik base_joint = cmds.listConnections(ik) effector = base_joint[1] end_joint = cmds.listConnections(effector) #joints in chain ik_joints = cmds.listRelatives(base_joint, ad=True, typ='joint') ik_joints.append(base_joint[0]) #find position of the base and end joints to create the distance tool first_pos = cmds.xform(ik_joints[0], q=True, t=True, ws=True) end_pos = cmds.xform(ik_joints[-1], q=True, t=True, ws=True) pv_pos = cmds.xform(pv_ctrl, q=True, t=True, ws=True) start_loc = cmds.spaceLocator(n=str(ik_joints[0]) + '_Stretchy' + nc['locator']) cmds.xform(start_loc, t=first_pos) cmds.setAttr(str(start_loc[0]) + '.visibility', 0) end_loc = cmds.spaceLocator(n=str(ik_joints[-1]) + '_Stretchy' + nc['locator']) cmds.xform(end_loc, t=end_pos) cmds.setAttr(str(end_loc[0]) + '.visibility', 0) pv_loc = cmds.spaceLocator(n=str(ik_joints[1]) + '_Stretchy' + nc['locator']) cmds.xform(pv_loc, t=pv_pos) cmds.setAttr(str(pv_loc[0]) + '.visibility', 0) cmds.parentConstraint(top_ctrl, start_loc) cmds.parentConstraint(ik_ctrl, end_loc) cmds.parentConstraint(pv_ctrl, pv_loc) #distances nodes #main distance distance = cmds.distanceDimension(sp=first_pos, ep=end_pos) distance = cmds.rename( distance, ik_joints[-1] + '_' + ik_joints[0] + nc['distance'] + '_Shape') cmds.rename(cmds.listRelatives(distance, p=True), ik_joints[-1] + '_' + ik_joints[0] + nc['distance']) cmds.setAttr('{}.visibility'.format(distance), 0) #top PV distance top_distance = cmds.distanceDimension(sp=first_pos, ep=pv_pos) top_distance = cmds.rename( top_distance, ik_joints[1] + '_' + ik_joints[0] + nc['distance'] + '_Shape') cmds.rename(cmds.listRelatives(top_distance, p=True), ik_joints[1] + '_' + ik_joints[0] + nc['distance']) cmds.setAttr('{}.visibility'.format(top_distance), 0) #IK PV distance ik_distance = cmds.distanceDimension(sp=end_pos, ep=pv_pos) ik_distance = cmds.rename( ik_distance, ik_joints[-1] + '_' + ik_joints[1] + nc['distance'] + '_Shape') cmds.rename(cmds.listRelatives(ik_distance, p=True), ik_joints[-1] + '_' + ik_joints[1] + nc['distance']) cmds.setAttr('{}.visibility'.format(ik_distance), 0) # stretchy math joints_for_distance = cmds.listRelatives(base_joint, ad=True, typ='joint') total_distance = 0 for joint in joints_for_distance: current_distance = cmds.getAttr(joint + str('.translate' + axis)) total_distance = total_distance + current_distance if total_distance < 0: total_distance = total_distance * -1 # New Attributes #Attr mult Stretchy print(attrs_location) for line in reversed(range(11)): try: self.line_attr(input=attrs_location, name='IK', lines=line) break except: pass stretch_Attr = self.new_attr(input=attrs_location, name='Stretch_On', min=0, max=1, default=int(setup['stretch_default'])) #IK Stretchy Nodes and Connections from RdM2 contidion_node = cmds.shadingNode('condition', asUtility=True, n=end_joint[0] + nc['condition']) cmds.setAttr(str(contidion_node) + ".operation", 2) cmds.setAttr(str(contidion_node) + '.secondTerm', total_distance) #Connect To Distance md0 = self.connect_md_node(in_x1=str(distance) + '.distance', in_x2=total_distance, out_x=str(contidion_node) + '.colorIfTrueR', mode='divide', name='') #connect to joints md1 = self.connect_md_node( in_x1=str(contidion_node) + '.outColorR', in_x2=cmds.getAttr(str(ik_joints[1]) + '.scale{}'.format(axis)), out_x=str(ik_joints[1]) + '.scale{}'.format(axis), mode='mult', name='{}_NewScale'.format(ik_joints[1])) md2 = self.connect_md_node( in_x1=str(contidion_node) + '.outColorR', in_x2=cmds.getAttr(str(ik_joints[2]) + '.scale{}'.format(axis)), out_x=str(ik_joints[2]) + '.scale{}'.format(axis), mode='mult', name='{}_NewScale'.format(ik_joints[2])) md3 = self.connect_md_node(in_x1=str(distance) + '.distance', in_x2=stretch_Attr, out_x=str(contidion_node) + '.firstTerm', mode='mult', name='{}_TotalDistance'.format(name)) print(md0, md1, md2, md3) #normalize stretch normalize_loc = cmds.spaceLocator(n=name + '_NormalScale' + nc['locator'])[0] normal_md = self.connect_md_node(in_x1=str(distance) + '.distance', in_x2=str(normalize_loc) + '.scaleX', out_x=md0 + '.input1X', mode='divide', name='{}_Normalize'.format(distance), force=True) cmds.connectAttr(normal_md + '.outputX', md3 + '.input1X', f=True) #manual change the sacles mult lower_attr = self.new_attr(input=attrs_location, name='Lower_Length', min=0.25, max=2, default=1) upper_attr = self.new_attr(input=attrs_location, name='Upper_Length', min=0.25, max=2, default=1) cmds.connectAttr(lower_attr, md2 + '.input2X', f=True) cmds.connectAttr(upper_attr, md1 + '.input2X', f=True) #elbow/knee lock #a bit hard coded bit it is what it is lock_attr = self.new_attr(input=attrs_location, name='Pole_Vector_Lock', min=0, max=1, default=0) upper_lock_blend = cmds.shadingNode('blendColors', asUtility=True, n='{}_Lock{}'.format( ik_joints[1], nc['blend'])) cmds.connectAttr(lock_attr, '{}.blender'.format(upper_lock_blend)) cmds.connectAttr('{}.output.outputR'.format(upper_lock_blend), str(ik_joints[2]) + '.scale{}'.format(axis), f=True) cmds.connectAttr('{}.outputX'.format(md1), '{}.color2.color2R'.format(upper_lock_blend), f=True) lower_lock_blend = cmds.shadingNode('blendColors', asUtility=True, n='{}_Lock{}'.format( ik_joints[2], nc['blend'])) cmds.connectAttr(lock_attr, '{}.blender'.format(lower_lock_blend)) cmds.connectAttr('{}.output.outputR'.format(lower_lock_blend), str(ik_joints[1]) + '.scale{}'.format(axis), f=True) cmds.connectAttr('{}.outputX'.format(md2), '{}.color2.color2R'.format(lower_lock_blend), f=True) #connect lock pole vectors distance to normalize too cmds.connectAttr( str(top_distance) + '.distance', normal_md + '.input1Y') cmds.connectAttr( str(ik_distance) + '.distance', normal_md + '.input1Z') self.connect_md_node( in_x1=normal_md + '.outputY', in_x2=cmds.getAttr(str(ik_joints[0]) + '.translate' + axis), out_x=lower_lock_blend + '.color1.color1R', mode='divide', name='{}_DownLock_PV'.format(name)) self.connect_md_node( in_x1=normal_md + '.outputZ', in_x2=cmds.getAttr(str(ik_joints[1]) + '.translate' + axis), out_x=upper_lock_blend + '.color1.color1R', mode='divide', name='{}_UpLock_PV'.format(name)) #volume preservation volume_attr = self.new_attr(input=attrs_location, name='Volume', min=0, max=1, default=float( setup['volume_preservation'])) upper_volume_blend = cmds.shadingNode('blendColors', asUtility=True, n='{}_Volume{}'.format( ik_joints[2], nc['blend'])) lower_volume_blend = cmds.shadingNode('blendColors', asUtility=True, n='{}_Volume{}'.format( ik_joints[1], nc['blend'])) cmds.setAttr('{}.color2.color2R'.format(upper_volume_blend), 1) cmds.setAttr('{}.color2.color2R'.format(lower_volume_blend), 1) cmds.connectAttr(volume_attr, '{}.blender'.format(upper_volume_blend)) cmds.connectAttr(volume_attr, '{}.blender'.format(lower_volume_blend)) self.connect_md_node(in_x1=1, in_x2=upper_lock_blend + '.output.outputR', out_x=upper_volume_blend + '.color1.color1R', mode='divide', name='{}_DownLock_PV'.format(name)) self.connect_md_node(in_x1=1, in_x2=lower_lock_blend + '.output.outputR', out_x=lower_volume_blend + '.color1.color1R', mode='divide', name='{}_DownLock_PV'.format(name)) volume_axis = ['X', 'Y', 'Z'] volume_axis.remove(axis) #str(ik_joints[2])+'.scale{}'.format(axis) for scale_axis in volume_axis: cmds.connectAttr('{}.output.outputR'.format(upper_volume_blend), str(ik_joints[2]) + '.scale{}'.format(scale_axis)) cmds.connectAttr('{}.output.outputR'.format(upper_volume_blend), str(ik_joints[1]) + '.scale{}'.format(scale_axis)) #organize ik_grp = cmds.group(top_distance, ik_distance, distance, start_loc, end_loc, pv_loc, normalize_loc, n='{}_Stretchy{}'.format(ik, nc['group'])) cmds.setAttr('{}.visibility'.format(ik_grp), 0) return (ik_grp, normalize_loc, start_loc, end_loc, pv_loc, distance, top_distance, ik_distance)
def measureBoundingBox(geo): """ Create visual distance dimensions for the specified geometry or geometry group. @param geo: Geometry or geometry group to create distance dimensions for. @type geo: str """ # Check Geo if not cmds.objExists(geo): raise Exception('Geometry "' + geo + '" does not exist!!') # ============================== # - Create Distance Dimensions - # ============================== del_locs = [] # Height hDimensionShape = cmds.distanceDimension(sp=(0, 0, 0), ep=(1, 1, 1)) locs = cmds.listConnections(hDimensionShape, s=True, d=False) or [] del_locs += locs hDimension = cmds.listRelatives(hDimensionShape, p=True)[0] hDimension = cmds.rename(hDimension, geo + "_height_measure") # Width wDimensionShape = cmds.distanceDimension(sp=(0, 0, 0), ep=(1, 1, 1)) locs = cmds.listConnections(wDimensionShape, s=True, d=False) or [] del_locs += locs wDimension = cmds.listRelatives(wDimensionShape, p=True)[0] wDimension = cmds.rename(wDimension, geo + "_width_measure") # Depth dDimensionShape = cmds.distanceDimension(sp=(0, 0, 0), ep=(1, 1, 1)) locs = cmds.listConnections(dDimensionShape, s=True, d=False) or [] del_locs += locs dDimension = cmds.listRelatives(dDimensionShape, p=True)[0] dDimension = cmds.rename(dDimension, geo + "_depth_measure") # Group measure_grp = cmds.group([hDimension, wDimension, dDimension], n=geo + "_measure_grp") # =============================== # - Connect Distance Dimensions - # =============================== # Height cmds.connectAttr(geo + ".boundingBoxMin", hDimension + ".startPoint", f=True) addHeightNode = cmds.createNode("plusMinusAverage", n=geo + "_height_plusMinusAverage") cmds.connectAttr(geo + ".boundingBoxMin", addHeightNode + ".input3D[0]", f=True) cmds.connectAttr(geo + ".boundingBoxSizeY", addHeightNode + ".input3D[1].input3Dy", f=True) cmds.connectAttr(addHeightNode + ".output3D", hDimension + ".endPoint", f=True) # Width cmds.connectAttr(geo + ".boundingBoxMin", wDimension + ".startPoint", f=True) addWidthNode = cmds.createNode("plusMinusAverage", n=geo + "_width_plusMinusAverage") cmds.connectAttr(geo + ".boundingBoxMin", addWidthNode + ".input3D[0]", f=True) cmds.connectAttr(geo + ".boundingBoxSizeX", addWidthNode + ".input3D[1].input3Dx", f=True) cmds.connectAttr(addWidthNode + ".output3D", wDimension + ".endPoint", f=True) # Depth cmds.connectAttr(geo + ".boundingBoxMin", dDimension + ".startPoint", f=True) addDepthNode = cmds.createNode("plusMinusAverage", n=geo + "_depth_plusMinusAverage") cmds.connectAttr(geo + ".boundingBoxMin", addDepthNode + ".input3D[0]", f=True) cmds.connectAttr(geo + ".boundingBoxSizeZ", addDepthNode + ".input3D[1].input3Dz", f=True) cmds.connectAttr(addDepthNode + ".output3D", dDimension + ".endPoint", f=True) # Delete Unused Locators if del_locs: cmds.delete(del_locs) # Return Result return measure_grp