def bdConnectChains(side, rigString, ikString, fkString): rigBones = [] for bone in legBonesNames[:-1]: legBone = pm.ls(side + bone + '_' + rigString)[0] rigBones.append(legBone) print legBone.name() for jnt in rigBones: if rigString in jnt.name(): fkJnt = None ikJnt = None searchFkJnt = pm.ls(jnt.name().replace(rigString, fkString)) if searchFkJnt: fkJnt = searchFkJnt[0] searchIkJnt = pm.ls(jnt.name().replace(rigString, ikString)) if searchIkJnt: ikJnt = searchIkJnt[0] print fkJnt, ikJnt if fkJnt and ikJnt: # baseName = ''.join([i for i in jnt.name().split("_")[0] if not i.isdigit()]) cfgCtrl = pm.ls(side + '*cfg_ctrl')[0] if cfgCtrl.hasAttr('fkIk'): print 'has attr already' else: pm.addAttr(cfgCtrl, ln='fkIk', nn='fkIk', at='float') cfgCtrl.attr('fkIk').setMin(0) cfgCtrl.attr('fkIk').setMax(1) cfgCtrl.attr('fkIk').setKeyable(True) bdCreateBlend(jnt, fkJnt, ikJnt, cfgCtrl)
def add_attr(node, attr_name, debug=False, **kwargs): """ Assign attributes to the given object. >>> import pymel.core as pm >>> FOO = pm.sphere() # Result: [nt.Transform(u'nurbsSphere1'), t.MakeNurbSphere(u'makeNurbSphere2')] # >>> shapeNode = FOO[-1] # Get the shape of the FOO >>> add_attr(shapeNode, "newAttributeName", attributeType='float') # Create a new attribute called "newAttributeName", type float :param node: (PyMel nodes) Object to assign new attributes to. :param attr_name: (String) attributes name :param debug: (Boolean) Set True if you want to print out the result. :param kwargs: attribute keywords. ex: """ # Add the attribute if it already doesn't exist if not node.hasAttr(attr_name): pm.addAttr(node, longName=attr_name, **kwargs) if debug: logging.info("Attribute '{}' is added to {}".format( attr_name, node)) else: logging.warning("Attribute '{}' already exists on {}".format( attr_name, node))
def doGuide(self, **kwargs): self.__dict__.update(kwargs) # apaga se existir displaySetup = self.moveallGuideSetup.copy() cntrlName = displaySetup['nameTempl'] + self.guideSulfix if pm.objExists(cntrlName): pm.delete(cntrlName) self.guideMoveall = controlTools.cntrlCrv(name=cntrlName, hasZeroGrp=False, cntrlSulfix='', hasHandle=True, **displaySetup) if not pm.objExists('GUIDES'): pm.group(self.guideMoveall, n='GUIDES') else: pm.parent(self.guideMoveall, 'GUIDES') displaySetup = self.startGuideSetup.copy() cntrlName = displaySetup['nameTempl'] + self.guideSulfix self.startGuide = controlTools.cntrlCrv(name=cntrlName, hasZeroGrp=False, cntrlSulfix='', hasHandle=True, **displaySetup) displaySetup = self.endGuideSetup.copy() cntrlName = displaySetup['nameTempl'] + self.guideSulfix self.endGuide = controlTools.cntrlCrv(name=cntrlName, hasZeroGrp=False, cntrlSulfix='', hasHandle=True, **displaySetup) pm.parent(self.startGuide, self.endGuide, self.guideMoveall) self.setCntrl(self.endGuide, 'end', space='object') self.setCntrl(self.startGuide, 'start', space='object') self.setCntrl(self.guideMoveall, 'moveall', space='world') pm.addAttr(self.guideMoveall, ln='neckDict', dt='string') self.guideMoveall.neckDict.set(json.dumps(self.exportDict()))
def createGuides(self): prevGuide = None for i in range(self.nJnt): guide = Guide(shader = self.shader,name=self.name + '_guide_' + (str(i)).zfill(2),moduleParent = self.name) guide.drawGuide() pos = [0,0,i*10] if i == 0: self.moduleCtrl ,self.moduleCtrlGrp = utils.buildBoxController(guide.name,self.name + '_ctrl',2) pm.parent(self.moduleCtrlGrp,self.moduleGrp) pm.parent(self.moduleGuidesGrp,self.moduleCtrl) guide.setPos(pos) self.guidesList.append(guide.name) pm.parent(guide.guideGrp,self.moduleGuidesGrp) attrName = 'guide_' + (str(i)).zfill(2) pm.addAttr(self.moduleCtrl,ln=attrName,at='message') guide.transform.message.connect( self.moduleCtrl.attr(attrName)) if i > 0: connectionGrp = prevGuide.drawConnectionTo(guide) pm.parent(connectionGrp,self.moduleConnectionsGrp) prevGuide = guide self.moduleRebuildInfo['guidesList'] = self.guidesList self.moduleCtrlGrp.setTranslation(self.position,space='world')
def stretchyBack( ikHandleTorso, jntList ): pymelLogger.debug('Starting: stretchyBack()...') #Stretchy process # ArcLen to create curveInfo curveInfoNodeBack = pm.arclen( ikHandleTorso[2], ch=True ) # add attr to curveinfo Node (normalizedScale) # this will have a value coming from a multiply divide node that will be # dividing the current length by the initial length of the curve # this will be used later to scale the joints pm.addAttr(curveInfoNodeBack, longName='normalizedScale', attributeType='double') # get initial length of the curve iniLen = pm.getAttr( curveInfoNodeBack + '.arcLength' ) # create a node multiplydivide, operation set to division MDCurveBack = pm.shadingNode( 'multiplyDivide', asUtility=True ) pm.setAttr( MDCurveBack+'.operation', 2 ) # divide # Connect curve arcLength to input1X pm.connectAttr( curveInfoNodeBack + '.arcLength', MDCurveBack + '.input1X', force=True ) # Set input2X to initial length of the curve pm.setAttr(MDCurveBack+'.input2X', iniLen) # connect outpux x from multiplydivide to normalized scale of the curve info pm.connectAttr(MDCurveBack + '.outputX', curveInfoNodeBack + '.normalizedScale', force=True) returnList = [curveInfoNodeBack,MDCurveBack] pymelLogger.debug('End: stretchyBack()...') return returnList
def add_enum_parameters(self, enum, scene_object, **kwargs): name = kwargs.pop('name', 'spaceSwitch') if name in pm.listAttr(scene_object): if pm.getAttr(scene_object + "." + name, type=True) == 'enum': enums_in_object = self.get_control_enums(scene_object) for eachEnum in enum: if not eachEnum in enums_in_object: enums_in_object.append(eachEnum) pm.addAttr(scene_object + '.' + name, e=True, ln=name, en=":".join(enums_in_object)) index = 0 return_index_dictionary = {} for eachEnum in enums_in_object: return_index_dictionary[eachEnum] = index index += 1 return return_index_dictionary else: pm.addAttr(scene_object, at="enum", ln=name, k=1, en=":".join(enum)) return None
def makePolygonsWithAttr(listOfGeomAttDictTuples): """This function takes a list of tuples, each tuple containing first a point list, and second a dictionary of attributes where the keys are the names of the attributes and the values are the corresponding values for each attribute, then the function creates a polygon from each point list and for that polygon, creates an attribute for each attribute in the attribute dictionary. The return value is a list of the names of all the created polygons.""" # create an empty list to hold results curves = [] for item in listOfGeomAttDictTuples: # each item consists of a point list, and # an attribute dictionary pointList, attDict = item[0], item[1] # this should return the name of the item curve = ptListToPolyline(pointList) for key in attDict: # ln and sn, are long name and short name respectively pm.addAttr(curve, ln=key, sn=key, dt="string") # attKey creates a handle that whould point direclty to # the attribute on that specific object attKey = '%s.%s' % (curve, key) # and here we set the attribute to the corresponding # value. pm.setAttr(attKey, attDict[key], typ="string") # finally add the name of the object to the list # of results. curves.append(curve) return curves
def __addInfo__(master, slave, channel, mo): # create master name attribut if slave.hasAttr('cstTgtName') == False: pmc.addAttr(slave, longName = 'cstTgtName', dataType = 'string', hidden = False) attribut = slave.cstTgtName attribut.setLocked(False) attribut.set(master.name()) attribut.setLocked(True) # create channel array attribut if channel != [1,1,1,1] or slave.hasAttr('cstOptStr'): if slave.hasAttr('cstOptStr') == False: pmc.addAttr(slave, longName = 'cstOptStr', dataType = 'string', hidden = False) attribut = slave.cstOptStr attribut.setLocked(False) # create a better information looking word = ['tr', 'ro', 'sc', 'sh'] s = '' for i in range(0, len(channel)): s=s + word[i] + '=' + str(channel[i]) + ' ' attribut.set(s) attribut.setLocked(True) # delete previous mo info if no need anymore if mo==False and slave.hasAttr('cstOffMat'): slave.cstOffMat.delete()
def bdConnectChains(): selection = pm.ls(sl=True) bindChainChildren = [] if len(selection) == 2: bindChain = selection[0] ikfkCon = selection[1] if ikfkCon.hasAttr('IKFK'): print 'has attr already' else: pm.addAttr(ikfkCon ,ln='IKFK',nn='IKFK',at='float' ) ikfkCon.attr('IKFK').setMin(0) ikfkCon.attr('IKFK').setMax(1) ikfkCon.attr('IKFK').setKeyable(True) fkJnt = pm.ls(bindChain.name().replace('JNT','FK'))[0] ikJnt = pm.ls(bindChain.name().replace('JNT','IK'))[0] bdCreateBlend(bindChain,fkJnt,ikJnt,ikfkCon) bindChainChildren = bindChain.listRelatives(c=True, type= 'joint',ad=True) bindChainChildren.reverse() bindChainChildren = bindChainChildren[:3] for child in bindChainChildren : fkJnt = pm.ls(child.name().replace('JNT','FK'))[0] ikJnt = pm.ls(child.name().replace('JNT','IK'))[0] print child bdCreateBlend(child,fkJnt,ikJnt,ikfkCon)
def facialShapeDriver(): shapeDriver = 'facialShapeDriver_LOC' if not cmds.objExists(shapeDriver): shapeDriver = rig_transform(0, name='facialShapeDriver', type='locator', parent='rig_GRP').object shapeDriver = pm.PyNode(shapeDriver) shapes = defaultShapeDriverList() pm.addAttr(shapeDriver, ln='SHAPE', at='enum', enumName='___________', k=True) shapeDriver.SHAPE.setLocked(True) for shape in shapes: print shape pm.addAttr(shapeDriver, longName=shape, at='float', k=True, min=0, max=1, dv=0)
def __finalizeFkChainShape(self): reversedList = list(self.controlsArray) reversedList.reverse() #parent shape for num,ctrl in enumerate(self.controlsArray): # for shape in ctrl.control.getShapes(): # pm.parent(shape,self.chain[num],r=1,s=1) pm.parent(ctrl.control.getShape(),self.chain[num],r=1,s=1) #stretch #Add attr pm.addAttr(self.chain[num],ln = 'stretch',at = 'double',dv = 0) pm.setAttr(self.chain[num] + '.stretch',e = 1,k = 1) #create node fkStrectchPMANodeName = nameUtils.getUniqueName(self.side,'fkStrectch','MDN') fkStrectchPMANode = pm.createNode('plusMinusAverage',n = fkStrectchPMANodeName) #connect oriTx = self.chain[num].tx.get() fkStrectchPMANode.input3D[0].input3Dx.set(oriTx) self.chain[num].stretch.connect(fkStrectchPMANode.input3D[1].input3Dx) fkStrectchPMANode.operation.set(1) fkStrectchPMANode.output3Dx.connect(self.chain[num].tx) #lock and hide control.lockAndHideAttr(self.chain[num],["tx","ty","tz","sy","sz","sx"]) #delete grp for i in range(len(reversedList)): pm.delete(reversedList[i].controlGrp)
def drive(control, attr, driven, minVal=None, maxVal=None, asInt=False, dv=None, flipped=False): ''' Add the attr to the control and feed it into driven. ''' attrType = 'short' if asInt else 'double' if not control.hasAttr(attr): control.addAttr(attr, at=attrType, k=True) if minVal is not None: control.attr(attr).setMin(minVal) if maxVal is not None: control.attr(attr).setMax(maxVal) if dv is not None: defaultVal = dv if maxVal is not None: defaultVal = min(defaultVal, maxVal) if minVal is not None: defaultVal = max(defaultVal, minVal) addAttr(control.attr(attr), e=True, dv=dv) if flipped: pdil.math.multiply(control.attr(attr), -1) >> driven else: control.attr(attr) >> driven return control.attr(attr)
def spineFKIK(): ''' Spine FK/IK feature ''' import pymel.core as pm pCns = {1:'HIP_CTRL', 2:'HIP_CTRL', 3:'SPINE_LOWER_CTRL', 4:'SPINE_MIDDLE_CTRL', 5:'SPINE_MIDDLE_CTRL', 6:'SPINE_UPPER_CTRL'} pm.addAttr('WORLD', sn='SpineIKFKSwitch', at='enum', en='IK:FK') newAttr = pm.PyNode('WORLD.SpineIKFKSwitch') newAttr.set(0, keyable=True, lock=False) for i in range(1,7): pm.parent('jSpine%02d'%i, 'bindSkelSpine') cnsNode = pm.parentConstraint(pCns[i], 'jSpine%02d'%i, mo=True) wtAttr = cnsNode.listAttr()[-2:] condNode = pm.createNode('condition', name='cond_spine%02s_parent'%i) condNode.colorIfTrueR.set(1) condNode.colorIfFalseR.set(0) condNode.colorIfTrueG.set(0) condNode.colorIfFalseG.set(1) newAttr >> condNode.firstTerm condNode.outColorR >> wtAttr[0] condNode.outColorG >> wtAttr[1]
def bdConnectChains(side): selection = pm.ls(sl=True) bindChainChildren = [] bindChain = pm.ls(side + '_' + armBones[0] + '_bnd', type='joint')[0] ikfkCon = pm.ls(side + '_arm_ikfk_ctrl', type='transform')[0] if ikfkCon.hasAttr('IKFK'): print 'has attr already' else: pm.addAttr(ikfkCon, ln='IKFK', nn='IKFK', at='float') ikfkCon.attr('IKFK').setMin(0) ikfkCon.attr('IKFK').setMax(1) ikfkCon.attr('IKFK').setKeyable(True) fkJnt = pm.ls(bindChain.name().replace('bnd', 'fk'))[0] ikJnt = pm.ls(bindChain.name().replace('bnd', 'ik'))[0] bdCreateBlend(bindChain, fkJnt, ikJnt, ikfkCon) bindChainChildren = bindChain.listRelatives(c=True, type='joint', ad=True) bindChainChildren.reverse() bindChainChildren = bindChainChildren[:3] for child in bindChainChildren: fkJnt = pm.ls(child.name().replace('bnd', 'fk'))[0] ikJnt = pm.ls(child.name().replace('bnd', 'ik'))[0] print child bdCreateBlend(child, fkJnt, ikJnt, ikfkCon)
def rad_load_associations(): someFailures = False targetFile = "" files = cmds.fileDialog2(dialogStyle=2, fileFilter="*.radpw", fileMode=1, caption="Load Pickwalk Configuration", okCaption="Load") if files: if len(files) > 0: targetFile = files[0] if not targetFile: return allNodes = cmds.ls(recursive=True) with open(targetFile) as f: for line in f: if not line.startswith("This"): infoArray = line.split() # node-name dir dir dir dir nodeName = infoArray[0] if pm.objExists(nodeName): infoIndex = 1 for direction in DIRECTIONS: dirNode = infoArray[infoIndex] infoIndex += 1 if dirNode != "null": try: if not pm.attributeQuery(dir_to_attr(direction), node=nodeName, exists=True): pm.addAttr(nodeName, longName=dir_to_attr(direction), attributeType="message") make_pick_walk(nodeName, dirNode, direction) except: print "Error during load of " + nodeName + " -> " + direction + " -> " + dirNode someFailures = True if someFailures: pm.warning("Some relationships failed to load (possibly due to different set of nodes)")
def sumAttr(sumCtrl=None, ctrlAttrA=None, ctrlAttrB=None, ctrlAttrResult=None, scaleA=None, scaleB=None): pmaNode = pm.shadingNode('plusMinusAverage',n='%s_Sum'%sumCtrl, asUtility=1) if scaleA: scaleA_node = pm.shadingNode('multiplyDivide',n='%s_ScaleA'%sumCtrl, asUtility=1) pm.setAttr('%s.input1X'%scaleA_node,scaleA) pm.connectAttr(ctrlAttrA,'%s.input2X'%scaleA_node,f=1) pm.connectAttr('%s.outputX'%scaleA_node,'%s.input1D[0]'%pmaNode,f=1) else: pm.connectAttr(ctrlAttrA,'%s.input1D[0]'%pmaNode,f=1) if scaleB: scaleB_node = pm.shadingNode('multiplyDivide',n='%s_ScaleB'%sumCtrl, asUtility=1) pm.setAttr('%s.input1X'%scaleB_node,scaleB) pm.connectAttr(ctrlAttrB,'%s.input2X'%scaleB_node,f=1) pm.connectAttr('%s.outputX'%scaleB_node,'%s.input1D[1]'%pmaNode,f=1) else: pm.connectAttr(ctrlAttrB,'%s.input1D[1]'%pmaNode,f=1) try: pm.addAttr(sumCtrl, ln=ctrlAttrResult.split('.')[1], k=1) except Exception, e: raise( e )
def buildSpan(self, points, index): num = str(index + 1).zfill(2) main_grp = pmc.group(empty=1, name='%s_span_%s_GRP' % (self.name, num)) # Create curve and connect curve points crv = curveBetweenNodes(points[0], points[2], name='%s_span_%s' % (self.name, num)) crv.setParent(main_grp) locs = connectCurve(crv) pmc.pointConstraint(points[0], points[1], locs[1], mo=0) pmc.pointConstraint(points[1], points[2], locs[2], mo=0) locs[0].setParent(points[0]) locs[1].setParent(main_grp) locs[2].setParent(main_grp) locs[3].setParent(points[2]) # Motionpath node mp = nodesAlongCurve(crv, numNodes=1, name='%s_span_%s' % (self.name, str(index)), upNode=points[1]) npc = pmc.createNode('nearestPointOnCurve', name='%s_span_%s' % (self.name, num)) points[1].worldPosition[0].connect(npc.inPosition) crv.worldSpace[0].connect(npc.inputCurve) npc.parameter.connect(mp['mpNodes'][0].uValue) mp['mpNodes'][0].fractionMode.set(0) mp['grps'][0].setParent(main_grp) # Tangents tanGrp = coreUtils.addChild(points[1], 'group', '%s_span_%s_tangent_GRP' % (self.name, num)) pmc.orientConstraint(mp['grps'][0], tanGrp) tanDrv = coreUtils.addChild(tanGrp, 'group', '%s_span_%s_tangent_DRV' % (self.name, num)) points[1].r.connect(tanDrv.r) points[1].s.connect(tanDrv.s) inTan_grp = coreUtils.addChild(tanDrv, 'group', '%s_span_%s_inTangent_GRP' % (self.name, num)) inTan_loc = coreUtils.addChild(inTan_grp, 'locator', '%s_span_%s_inTangent_LOC' % (self.name, num)) inDist = coreUtils.distanceBetweenNodes(points[0], points[1], '%s_span_%s_in_dist' % (self.name, num)) outTan_grp = coreUtils.addChild(tanDrv, 'group', '%s_span_%s_outTangent_GRP' % (self.name, num)) outTan_loc = coreUtils.addChild(outTan_grp, 'locator', '%s_span_%s_outTangent_LOC' % (self.name, num)) outDist = coreUtils.distanceBetweenNodes(points[1], points[2], '%s_span_%s_out_dist' % (self.name, num)) pmc.addAttr(points[1], ln='tangentWeight', at="float", minValue=0.0, maxValue=1.0, keyable=1, hidden=0, defaultValue=0.25) inWeight_md = coreUtils.multiply(inDist.distance, points[1].tangentWeight, 'md_%s_span_%s_inWeight_UTL' % (self.name, num)) outWeight_md = coreUtils.multiply(outDist.distance, points[1].tangentWeight, 'md_%s_span_%s_outWeight_UTL' % (self.name, num)) weight_uc = coreUtils.convert(inWeight_md.outputX, -1, 'uc_%s_span_%s_weightInvert_UTL' % (self.name, num)) outWeight_md.outputX.connect(outTan_grp.tx) weight_uc.output.connect(inTan_grp.tx) return { 'inTan': inTan_loc, 'outTan': outTan_loc, 'inDist': inDist, 'outDist': outDist, # 'weight_md':weight_md, 'main_grp': main_grp, }
def fetchAttr(data): node = data['node'] kwargs = kwargsMap[data['type']] pymel.addAttr(node, longName = data['longName'], multi=data['isMulti'], niceName = data['niceName'], keyable = data['keyable'], hidden = data['hidden'], **kwargs ) attr = node.attr(data['longName']) # Re-connect inputs if not data['isMulti']: inn = next(iter(data['inputs']), None) if inn: pymel.connectAttr(inn, attr) else: for i, inn in enumerate(data['inputs']): pymel.connectAttr(inn, attr[i]) # Re-connect outputs for i, output in enumerate(data['outputs']): if output: pymel.connectAttr(attr[i], output)
def rigBook(containers): center = createJointChain(name='center') left = createJointChain(name='left') right = createJointChain(name='right') ctrl = containers["ctrl"] pm.addAttr(containers["ctrl"], ln="_", at="enum", en="______" ) pm.setAttr(containers["ctrl"]+"._", e=1, keyable=1) for page in range(pages): pageName = 'page'+str(page) skin = createJointChain(pageName+"_") rigPage(skin, center, left, right, ctrl, pageName) paper = createPaper(pageName) pm.select(skin, r=1, hi=1) pm.select(paper, add=1, ) pm.bindSkin(toAll = 1, colorJoints = 1) pm.select(cl=1) pm.parent(paper, containers["paper_grp"]) pm.parent(skin[0], containers["pages_grp"]) pm.select(cl=1) print "rigged: %s" % pageName pm.parent(center[0], containers["pageTargets_grp"]) pm.parent(left[0], containers["pageTargets_grp"]) pm.parent(right[0], containers["pageTargets_grp"])
def createWorld(name='human', scale=1): ''' Create World node for character with standardized Rigg Groups and export Sets Creates Placer, Mover, Direction Ctrls Args: name: Name of world Returns: ''' if pm.objExists('%s_world' % name): lg.info('createWorld: Deleting existing %s_world' % name) pm.delete('%s_world' % name) world = pm.createNode('transform', n='%s_world' % name) pm.createNode('transform', n='CONTROLS'), pm.createNode( 'transform', n='RIG'), pm.createNode('transform', n='GEO') pm.parent(['CONTROLS', 'RIG', 'GEO'], world) pm.createNode('transform', n='CONTSTRAINER') pm.parent('CONTSTRAINER', 'CONTROLS') pm.createNode('transform', n='render_Geo'), pm.createNode('transform', n='nonRender_Geo') pm.parent(['render_Geo', 'nonRender_Geo'], 'GEO') pm.createNode('transform', n='RIG_NONSCALE') pm.parent('RIG_NONSCALE', 'RIG') rigscale = pm.createNode('transform', n='RIG_SCALE') pm.parent('RIG_SCALE', 'RIG') print 'placer' placer = curveLib.createShapeCtrl(type='PLACER', name='PLACER', scale=scale) print 'mover' mover = curveLib.createShapeCtrl(type='MOVER', name='MOVER', scale=scale, color='blue') print 'direction' direction = curveLib.createShapeCtrl(type='DIRECTION', name='DIRECTION', scale=scale, color='red') # size attribute pm.addAttr(direction, ln='size', at='double', dv=1, k=1) direction.size >> direction.scaleX direction.size >> direction.scaleY direction.size >> direction.scaleZ direction.size >> rigscale.scaleX direction.size >> rigscale.scaleY direction.size >> rigscale.scaleZ pm.parent(direction, mover) pm.parent(mover, placer) pm.parent(placer, 'CONTSTRAINER') # DISPLAY curveLib.createTextCtrl('D', 'DISPLAY', font="Arial", size=scale) riggUtils.grpCtrl(ctrl='DISPLAY') pm.parent('DISPLAY_ZERO', placer) riggUtils.makeExportable([placer, mover, direction, 'DISPLAY'])
def addSeparator(transform, character=pcfg.separator_character): """ Adds the given character attribute to help visually separate attributes in channel box to specified transform. Args: transform (string or pm.nodetypes.DependNode): transform node to add given character attribute to. character (string): Character to use to visually separate attributes in channel box. """ transform = pm.PyNode(transform) separator_count = [] separator = character # get all the attributes with '_' in the transform's attributes for full_attribute in transform.listAttr(): attribute = full_attribute.split(str(transform)) if character in attribute[1]: separator_count.append(attribute[1].count(character)) # make an underscore that is one '_' longer than the longest underscore if separator_count: separator = (separator * max(separator_count)) + separator # make the attribute pm.addAttr(transform, longName=separator, k=True, at='enum', en=character) transform.attr(separator).lock()
def buildArm(arm, fingers): # Fingers should be in order, starting with Thumb ctrl = arm['units'][1]['controls'][0] for finger in fingers: # Add curl controls to hand IK root = finger['root'] name = finger['name'].split('_')[0].replace('Finger', '') pm.addAttr(ctrl, ln=name + 'Curl', at='float', minValue=0.0, maxValue=10.0, defaultValue=0.0, k=True) rv = remapAttr(ctrl.attr(name + 'Curl'), in_range=(0.0, 10.0)) pm.connectAttr(rv, root.attr('curl')) # Set spread multipliers (exclude Thumb) if fingers.index(finger): finger['root'].spreadAmt.set( finger['root'].spreadAmt.get() * (-(fingers.index(finger) - 2.5) / 1.5)) # Add spread control pm.addAttr(ctrl, ln='spread', at='float', minValue=-5.0, maxValue=10.0, defaultValue=0.0, k=True) rv = remapAttr(ctrl.attr('spread'), in_range=(-5.0, 10.0), out_range=(-0.5, 1.0)) connectAttrMulti(rv, [finger['root'].spread for finger in fingers[1:]])
def setup_look_at(camera): """sets up the look at locator for the given camera """ # just create a locator under the camera # and move it to -10 loc = pm.spaceLocator(n=camera.name() + "vertigo_loc#") # create a new attribute under the camera global vertigo_attr_name camera_shape = camera.getShape() if not camera.hasAttr(vertigo_attr_name): pm.addAttr(camera, ln=vertigo_attr_name, at="message") # connect the message attribute of the locator to the camera loc.message >> camera.attr(vertigo_attr_name) pm.parent(loc, camera) loc.t.set(0, 0, -10) loc.r.set(0, 0, 0) # lock locators tx, ty and rotate channels loc.tx.lock() loc.ty.lock() loc.r.lock()
def doGuide(self, edgeLoop=None, autoExtremes=True, **kwargs): self.edgeLoop = edgeLoop self.mesh = pm.ls(self.edgeLoop[0], o=True)[0] self.guideMoveall = self.createCntrl('moveallGuide') self.inCorner = self.createCntrl(setupName='cornersGuide', nameTempl=self.name + 'InCorner' + self.guideSulfix) self.outCorner = self.createCntrl(setupName='cornersGuide', nameTempl=self.name + 'OutCorner' + self.guideSulfix) self.upCorner = self.createCntrl(setupName='cornersGuide', nameTempl=self.name + 'UpCorner' + self.guideSulfix) self.lowCorner = self.createCntrl(setupName='cornersGuide', nameTempl=self.name + 'LowCorner' + self.guideSulfix) if autoExtremes: try: pts = vtxWalk.getEdgeLoopExtremesPoints(self.edgeLoop) inPos = pm.xform(pts[0], q=True, ws=True, t=True) outPos = pm.xform(pts[1], q=True, ws=True, t=True) upPos = pm.xform(pts[2], q=True, ws=True, t=True) lowPos = pm.xform(pts[3], q=True, ws=True, t=True) self.guideDict['inCorner'] = [inPos, (0, 0, 0)] self.guideDict['outCorner'] = [outPos, (0, 0, 0)] self.guideDict['upCorner'] = [upPos, (0, 0, 0)] self.guideDict['lowCorner'] = [lowPos, (0, 0, 0)] except: logger.debug('not possible autoextremes') self.setCntrl(self.inCorner, 'inCorner', space='world') self.setCntrl(self.outCorner, 'outCorner', space='world') self.setCntrl(self.upCorner, 'upCorner', space='world') self.setCntrl(self.lowCorner, 'lowCorner', space='world') pm.parent(self.inCorner, self.outCorner, self.upCorner, self.lowCorner, self.guideMoveall) pm.addAttr(self.guideMoveall, ln='stickLipsDict', dt='string') self.guideMoveall.stickLipsDict.set(json.dumps(self.exportDict()))
def updateAOVStrAttr( *args ): strAttr = 'object_list' sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True) # filter AOV id_aov_sets = [ node for name, node in sceneAOVs if node.find('_id_') == 5 ] for aov in id_aov_sets: if( not( pm.PyNode(aov).hasAttr(strAttr) ) ): pm.addAttr( aov, longName=strAttr, dataType='string' ) pm.PyNode(aov+'.'+strAttr).set('') listMesh = pm.ls(type='mesh') amount = 0.0 maxValue = len(listMesh) pm.progressWindow( title='AOV Update Calculation', progress=amount, maxValue=maxValue , isInterruptable=True, status='calculating: 0%' ) for mesh in listMesh: amount = amount + 1 pm.progressWindow( edit=True, progress=amount, status=('calculating: ' + str( 100 * amount/ maxValue) + '%') ) if( mesh.hasAttr('mtoa_constant_Id') ): idName = mesh.mtoa_constant_Id.get() currAOVStrAttr = 'aiAOV_' + idName + '.' + strAttr pm.PyNode(currAOVStrAttr).set( pm.PyNode(currAOVStrAttr).get() + mesh + ';' ) pm.progressWindow(endProgress=1) return 1
def loadTranslationControl(root_joint, module_name, container, module_control_grp, control_type = "translation", color = [1, 0, 0]): """ loads translation control onto the root_joint """ path = os.path.join(environ.ControlObjectsPath, "translation_control.ma") pm.importFile(path, renameAll = True, loadReferenceDepth = "all", namespace =":") # renamePrefix == namespace # rename default module translation_control = pm.rename("translation_control", module_name + ":" + root_joint.stripNamespace() + "_translation_control", ignoreShape = False) translation_control_grp = pm.group(translation_control, name = module_name + ":" + root_joint.stripNamespace() + "_translation_controlGrp") # move control to root root_joint pm.delete(pm.pointConstraint(root_joint, translation_control_grp, maintainOffset=False)) translation_control_grp.setParent(module_control_grp) pm.addAttr(translation_control, longName="ControlType", dataType="string", keyable=False) pm.addAttr(translation_control, longName="ParentObject", at="message", multi = True) translation_control.ControlType.set(control_type, type = "string", lock = True) utils.addNodeToContainer(container, [translation_control, translation_control_grp], ihb = True, includeNetwork = True) pm.container(container, edit=True, publishAndBind=[translation_control + ".rotate", translation_control.stripNamespace() + "_rotate"]) pm.container(container, edit=True, publishAndBind=[translation_control + ".translate", translation_control.stripNamespace() + "_translate"]) return translation_control, translation_control_grp
def add_attr(node, attr_name, debug=False, **kwargs): """ Assign attributes to the given object. >>> import pymel.core as pm >>> FOO = pm.sphere() # Result: [nt.Transform(u'nurbsSphere1'), t.MakeNurbSphere(u'makeNurbSphere2')] # >>> shapeNode = FOO[-1] # Get the shape of the FOO >>> add_attr(shapeNode, "newAttributeName", attributeType='float') # Create a new attribute called "newAttributeName", type float :param node: (PyMel nodes) Object to assign new attributes to. :param attr_name: (String) attributes name :param debug: (Boolean) Set True if you want to print out the result. :param kwargs: attribute keywords. ex: """ # Add the attribute if it already doesn't exist if not node.hasAttr(attr_name): pm.addAttr(node, longName=attr_name, **kwargs) if debug: logging.info("Attribute '{}' is added to {}".format(attr_name, node)) else: logging.warning("Attribute '{}' already exists on {}".format(attr_name, node))
def bdConnectChains(side): selection = pm.ls(sl=True) bindChainChildren = [] bindChain = pm.ls(side + '_' + armBones[0] + '_bnd', type='joint')[0] ikfkCon = pm.ls(side + '_arm_ikfk_ctrl',type='transform')[0] if ikfkCon.hasAttr('IKFK'): print 'has attr already' else: pm.addAttr(ikfkCon ,ln='IKFK',nn='IKFK',at='float' ) ikfkCon.attr('IKFK').setMin(0) ikfkCon.attr('IKFK').setMax(1) ikfkCon.attr('IKFK').setKeyable(True) fkJnt = pm.ls(bindChain.name().replace('bnd','fk'))[0] ikJnt = pm.ls(bindChain.name().replace('bnd','ik'))[0] bdCreateBlend(bindChain,fkJnt,ikJnt,ikfkCon) bindChainChildren = bindChain.listRelatives(c=True, type= 'joint',ad=True) bindChainChildren.reverse() bindChainChildren = bindChainChildren[:3] for child in bindChainChildren : fkJnt = pm.ls(child.name().replace('bnd','fk'))[0] ikJnt = pm.ls(child.name().replace('bnd','ik'))[0] print child bdCreateBlend(child,fkJnt,ikJnt,ikfkCon)
def bdAddFkCtrls(self, ctrl): ctrlGrpAll = [] tempCtrl = ctrl.duplicate()[0] ctrlGrp = self.bdSetUpCtrl(ctrl,self.fkRootObj) ctrlGrpAll.append(ctrlGrp) pm.addAttr(ctrl, ln = "dynamic", at = 'double', min = 0, max = 1 , dv = 0) ctrl.attr('dynamic').setKeyable(True) ctrl.overrideEnabled.set(1) ctrl.overrideColor.set(6) self.fkCtrlTop = ctrl fkChainDesc = self.fkRootObj.listRelatives(type='joint', ad=True, f=True) fkChainDesc.reverse() for jnt in fkChainDesc[:-1]: newCtrl = tempCtrl.duplicate()[0] newCtrl.overrideEnabled.set(1) newCtrl.overrideColor.set(6) ctrlGrp = self.bdSetUpCtrl(newCtrl, jnt) ctrlGrpAll.append(ctrlGrp) print range(len(ctrlGrpAll)) for i in range(len(ctrlGrpAll)-1,0,-1): pm.parent(ctrlGrpAll[i],ctrlGrpAll[i-1].getChildren()[0]) pm.delete([tempCtrl]) self.bdCreateFkDynSwitch()
def handControlSetup(self, *args): """ Create attributes on hand_cnt and connect them as needed. """ pm.addAttr(self.hand_cnt,ln='FK_IK',at='float',dv=0,min=0,max=1,k=True) # IK/FK blend color nodes pm.connectAttr( '%s.FK_IK'%self.hand_cnt, '%s.blender'%self.shldr_node1 ) pm.connectAttr( '%s.FK_IK'%self.hand_cnt, '%s.blender'%self.elbow1_node1 ) pm.connectAttr( '%s.FK_IK'%self.hand_cnt, '%s.blender'%self.elbow1_node2 ) pm.connectAttr( '%s.FK_IK'%self.hand_cnt, '%s.blender'%self.wrist_node1 ) pm.connectAttr( '%s.FK_IK'%self.hand_cnt, '%s.blender'%self.wrist_node2 ) #IK/FK controls vis switch pm.connectAttr( '%s.FK_IK'%self.hand_cnt, '%s.visibility'%self.ikChain[0] ) pm.connectAttr( '%s.FK_IK'%self.hand_cnt, '%s.visibility'%self.ikControl[0] ) pm.setDrivenKeyframe(self.fkChain[0], cd='%s.FK_IK' % self.hand_cnt, at='visibility', dv=1, v=0) pm.setDrivenKeyframe(self.fkChain[0], cd='%s.FK_IK' % self.hand_cnt, at='visibility', dv=0, v=1) # Zero hand control and parent to the following joint chian. self.zero(self.hand_cnt) bufferNode = pm.listRelatives(self.hand_cnt,parent=True) pm.parentConstraint(self.jointChain[2],bufferNode,mo=True)
def messageConnect(fromNode=None, toNode=None, fromName=None, toName=None, category=None): ''' Creates a message attribute on fromNode and toNode with the names fromName and toName respectively Connects the two new attributes ''' # validation if not fromNode or not toNode and (len(pmc.selected()) == 2): fromNode = pmc.selected()[0] toNode = pmc.selected()[1] if not fromNode or not toNode: return 'Argument Error, messageConnect requires fromNode and toNode as either arguments or 2 selected nodes' if not fromName or not toName: return 'Argument Error, messageConnect requires fromName and toName arguments for newly created attrs' # Add attributes if pmc.attributeQuery(fromName, node=fromNode, exists=1): print '%s.%s: Attribute exists' % (fromNode, fromName) else: pmc.addAttr(fromNode, ln=fromName, at='message', category=category) print '%s.%s: Attribute created' % (fromNode, fromName) if pmc.attributeQuery(toName, node=toNode, exists=1): print '%s.%s: Attribute exists' % (toNode, toName) else: pmc.addAttr(toNode, ln=toName, at='message', category=category) print '%s.%s: Attribute created' % (toNode, toName) # Connect attributes pmc.connectAttr('%s.%s' % (fromNode, fromName), '%s.%s' % (toNode, toName), f=1) print '%s.%s connected to %s.%s' % (fromNode, fromName, toNode, toName)
def RigFK( jnts=None, side='L', ctrlSize=1.0, stretch=True, color='r' ): if not jnts: jnts = pm.ls( sl=True ) else: jnts = pm.ls( jnts ) # find color of the ctrls color = 'y' if side == 'L': color = 'r' elif side == 'R': color = 'b' shapes = [] for jnt in jnts: if not jnt or not jnt.type()=='joint': pm.warning('ehm_tools...RigFK: %s was not a joint, skipped!'%jnt) shapes.append( (JntToCrv ( jnts = jnt , size = ctrlSize )).newShapes ) LockHideAttr( objs=jnt, attrs='t' ) LockHideAttr( objs=jnt, attrs='radius' ) if stretch == True: # add length attribute and connect it to scale pm.addAttr ( jnt , ln = "length" , at = "double" , min = 0 , dv = 1 , k = True ) jnt.length >> jnt.scaleX LockHideAttr( objs=jnt, attrs='s' ) Colorize( shapes=shapes, color=color ) return shapes
def rig_attachToCurve(obj, crv, createGroup=True, constrainParent=False): ''' attaches an object to a curve Args: obj (pm.PyNode): Object to constrain to crv (pm.nt.NurbsCurve): Curve to get info from constrainParent (bool): if we constrain to the object's parent instead of the object Returns (pm.shadingNode.pointOnCurveInfo): pointOnCurveInfo node that results Usage: rig_attachToCurve(pm.ls(sl=True), pm.PyNode('curve1'), createGroup=False, constrainParent=False) for obj in pm.ls(sl=True): rig_attachToCurve(obj, pm.PyNode('curve1'), createGroup=False, constrainParent=False) ''' passArgs=[None,None] if constrainParent and obj.getParent(): passArgs = [obj.getParent(),obj.getParent()] elif not obj.getParent() and constrainParent: pm.error('Could not find a parent for object %s'%obj) return None elif createGroup: grp=pm.group(em=True, n='_'.join([obj.name(),crv.name(),'Offset_GRP'])) grp.inheritsTransform.set(0) grp.t.set(obj.getRotatePivot(space='world')) grp.r.set(pm.xform(obj, q=True, ro=True, a=True, ws=True)) pm.addAttr(grp, ln='connectPCObj', dt='string', k=True) passArgs=[obj,grp] else: passArgs=[obj, obj] poci = rig_getClosestPointNode(passArgs[0], crv, cpoc=True) mdpma = rig_connectPociWithOffset(poci, passArgs[1]) pm.tangentConstraint(crv, passArgs[1]) return [passArgs[1], poci] + mdpma
def doGuide(self, **kwargs): self.__dict__.update(kwargs) if pm.objExists('facial_guides_grp'): facialGrp = 'facial_guides_grp' else: facialGrp = pm.group(n='facial_guides_grp', em=True) self.guideMoveall = self.createCntrl('moveallGuide') self.L_cornerGuide = self.createCntrl('L_cornerGuide') self.R_cornerGuide = self.createCntrl('R_cornerGuide') self.jawGuide = self.createCntrl('jawGuide') self.pivotGuide = self.createCntrl('pivotGuide') self.upperLipGuide = self.createCntrl('upperLipGuide') self.upperTeethGuide = self.createCntrl('upperTeethGuide') self.lowerTeethGuide = self.createCntrl('lowerTeethGuide') self.tongue1Guide = self.createCntrl('tongue1Guide') self.tongue2Guide = self.createCntrl('tongue2Guide') self.tongue3Guide = self.createCntrl('tongue3Guide') self.tongue4Guide = self.createCntrl('tongue4Guide') self.tongue5Guide = self.createCntrl('tongue5Guide') pm.parent(self.L_cornerGuide, self.R_cornerGuide, self.jawGuide, self.upperLipGuide, self.pivotGuide, self.upperTeethGuide, self.lowerTeethGuide, self.tongue1Guide, self.tongue2Guide, self.tongue3Guide, self.tongue4Guide, self.tongue5Guide, self.guideMoveall) self.setCntrl(self.L_cornerGuide, 'L_corner') self.setCntrl(self.R_cornerGuide, 'R_corner') self.setCntrl(self.jawGuide, 'jaw') self.setCntrl(self.pivotGuide, 'pivot') self.setCntrl(self.upperLipGuide, 'upperLip') self.setCntrl(self.upperTeethGuide, 'upperTeeth') self.setCntrl(self.lowerTeethGuide, 'lowerTeeth') self.setCntrl(self.tongue1Guide, 'tongue1') self.setCntrl(self.tongue2Guide, 'tongue2') self.setCntrl(self.tongue3Guide, 'tongue3') self.setCntrl(self.tongue4Guide, 'tongue4') self.setCntrl(self.tongue5Guide, 'tongue5') self.setCntrl(self.guideMoveall, 'moveall') self.R_cornerGuide.template.set(1) guide_mdn = pm.createNode('multiplyDivide') guide_mdn.input2.input2X.set(-1) self.L_cornerGuide.translate >> guide_mdn.input1 guide_mdn.output >> self.R_cornerGuide.translate self.L_cornerGuide.rotate >> self.R_cornerGuide.rotate self.L_cornerGuide.scale >> self.R_cornerGuide.scale pm.parent(self.guideMoveall, facialGrp) pm.addAttr(self.guideMoveall, ln='jawDict', dt='string') self.guideMoveall.jawDict.set(json.dumps(self.exportDict()))
def rp_grip(): """..............................................................................................//""" s = pm.ls(sl=1) if pm.mel.gmatch(s[0], "*_grip*"): ps = pm.listRelatives(s[0], p=1) pm.delete(ps[0]) else: rp_check(s) cj = pm.ls((s[0] + "_tw_*"), typ="joint") for y in range(0, (len(cj))): if pm.objExists("ctgrp_" + s[0] + "_grip" + str((y + 1))) == 0: ct = pm.circle(ch=0, nr=(1, 0, 0), r=0.8, d=3, n=("CT_" + s[0] + "_grip" + str((y + 1)))) ctg = str(pm.group(ct[0], n=("ctgrp_" + s[0] + "_grip" + str((y + 1))))) pm.parent(ctg, (s[0] + "_rig")) pm.setAttr((ct[0] + ".tx"), k=0, l=1) pm.setAttr((ct[0] + ".ty"), k=0, l=1) pm.setAttr((ct[0] + ".tz"), k=0, l=1) pm.setAttr((ct[0] + ".rx"), k=0, l=1) pm.setAttr((ct[0] + ".ry"), k=0, l=1) pm.setAttr((ct[0] + ".rz"), k=0, l=1) pm.setAttr((ct[0] + ".sx"), k=0, l=1) pm.setAttr((ct[0] + ".sy"), k=0, l=1) pm.setAttr((ct[0] + ".sz"), k=0, l=1) pm.setAttr((ct[0] + ".v"), k=0) pm.setAttr((ct[0] + "Shape.ove"), 1) pm.setAttr((ct[0] + "Shape.ovc"), 13) pm.addAttr(ct[0], min=0, ln="move", max=(len(cj)), k=1, at="long", dv=0) pm.parentConstraint(cj, ctg, w=1) for i in range(0, (len(cj))): pm.setAttr((ct[0] + ".move"), i) for x in range(0, (len(cj))): pm.setAttr((ctg + "_parentConstraint1." + cj[x] + "W" + str(x)), 0) pm.setAttr((ctg + "_parentConstraint1." + cj[i] + "W" + str(i)), 1) pm.setDrivenKeyframe((ctg + "_parentConstraint1." + cj[x] + "W" + str(x)), cd=(ct[0] + ".move")) pm.setAttr((ct[0] + ".move"), (y + 1)) pm.select(s[0]) break
def blender(s1, s2, t, cont, style): # created a blend node between two sources and a target # adding attributes for control # type - 0 for rotation or 1 for translation try: cont.attr("blend") except Exception, err: pmc.addAttr(cont, shortName='bl', longName='blend', defaultValue=0.5, minValue=0.0, maxValue=1.0)
def _patch_module(module): net = module.sysIK._network ctrl = module.sysIK.ctrl_ik attr_anm = ctrl.rollAutoThreshold if not net.hasAttr('attrAutoRollThreshold'): print("Fixing {}".format(net)) pymel.addAttr(net, longName='attrAutoRollThreshold') pymel.connectAttr(attr_anm, net.attrAutoRollThreshold)
def addRotationOrderAttr(self): pm.addAttr(self.control, ln="rotationOrder", en="xyz:yzx:zxy:xzy:yxz:zyx:", at="enum") pm.setAttr((str(self.control) + ".rotationOrder"), e=1, keyable=True) pm.connectAttr((str(self.control) + ".rotationOrder"), (str(self.control) + ".rotateOrder"))
def _create_data_attribute(self): """creates attribute in self._object to hold the data """ if not self._object.hasAttr("pivotData"): pm.addAttr(self._object, ln="pivotData", at="compound", nc=1) if not self._object.hasAttr("futurePivot"): pm.addAttr(self._object, ln="futurePivot", at="message", p="pivotData")
def tagEditAdd_PB_hit(self): tag_name = self.tagEditName_LE.text() SG_list = self.getUsedShaderSg() for sg in SG_list: exists = pm.attributeQuery('gpuCacheShaderTag', node=sg, ex=True, longName=True) if exists is False: pm.addAttr(sg, longName='gpuCacheShaderTag', dataType='string') sg.setAttr('gpuCacheShaderTag', tag_name)
def addOutputAttrs(node): try: pmc.deleteAttr(node.outMatrix) except: print 'attributes to delete not found' pmc.select(node) pmc.addAttr(ln='outMatrix', at='matrix', multi=1)
def doGuide(self, **kwargs): self.__dict__.update(kwargs) self.guideMoveall = self.createCntrl('moveallGuide') self.setCntrl(self.guideMoveall, 'moveall', space='world') pm.addAttr(self.guideMoveall, ln='eyeLookAtDict', dt='string') self.guideMoveall.eyeLookAtDict.set(json.dumps(self.exportDict()))
def write_tags(self): """write tags in extr attributes object """ self.tags = set(self.tags) str_tags = ','.join(self.tags) if not pmc.attributeQuery("GuerillaTags", node=self.obj, exists=True): pmc.addAttr(self.obj, longName="GuerillaTags", dt="string") self.obj.attr("GuerillaTags").set(str_tags)
def add_dict_attr(node, ln, attrs): pm.addAttr(node, ln=ln, numberOfChildren=len(attrs), at="compound") for key, value in attrs.iteritems(): pm.addAttr(node, ln=key, at="message", parent=ln) for key, value in attrs.iteritems(): pm.connectAttr("%s.message" % (value.name()), "%s.%s" % (node.name(), key))
def copyMTOAAttr(srcGeo,standIn): # copy mtoa attributes from render geo to standIn for n in attrList: # add mtoa custom attributes to ASS pm.addAttr(standIn.getShape(), ln = "mtoa_constant_" + n, nn = n, dt = 'string') for m in attrList: # copy custom attribute values to ASS attrLong = srcGeo.getShape() + '.mtoa_constant_' + m attrValue = pm.getAttr(attrLong) if not attrValue == None: pm.setAttr(standIn.getShape() + ".mtoa_constant_" + m, attrValue ,type = 'string')
def addAttrIK(): # ik attributes sel = pm.ls(sl= True) newAttrs = ("autoStretch" , "lockElbow", "squashNStretch",) for i in range(0,3): pm.addAttr( sel[0], longName = newAttrs[i], attributeType = 'double', min = 0 , max = 1, dv = 0 ) pm.setAttr( (sel[0] + "." + newAttrs[i]) , keyable = True )
def appendButton(self, *args): sel = pm.ls(sl=1) for obj in sel: self.ui.sources_listWidget.addItem(obj.name()) pm.addAttr(obj, ln='sources__', dt='string') self.ui.sources_listWidget.sortItems(QtCore.Qt.AscendingOrder)
def checkAndCreate(self, obj, attr): if not self.attrExists(obj, attr): # create the attribute pm.addAttr( obj.name(), ln=attr, dt="string" )
def setUp(self): self.temp = tempfile.mkdtemp(prefix='referencesTest') print "created temp dir: %s" % self.temp # Refs: # sphere.ma # (no refs) # cube.ma # :sphere => sphere.ma # cone.ma # :cubeInCone => cube.ma # :cubeInCone:sphere => sphere.ma # master.ma # :sphere1 => sphere.ma # :sphere2 => sphere.ma # :cube1 => cube.ma # :cube1:sphere => sphere.ma # :cone1 => cone.ma # :cone1:cubeInCone => cube.ma # :cone1:cubeInCone:sphere => sphere.ma # create sphere file print "sphere file" # cmds.file(new=1, f=1) pm.newFile(f=1) sphere = pm.polySphere() # We will use this to test failed ref edits... pm.addAttr(sphere, ln='zombieAttr') self.sphereFile = pm.saveAs( os.path.join( self.temp, 'sphere.ma' ), f=1 ) # create cube file print "cube file" pm.newFile(f=1) pm.polyCube() pm.createReference( self.sphereFile, namespace='sphere' ) pm.PyNode('sphere:pSphere1').attr('translateX').set(2) self.cubeFile = pm.saveAs( os.path.join( self.temp, 'cube.ma' ), f=1 ) # create cone file print "cone file" pm.newFile(f=1) pm.polyCone() pm.createReference( self.cubeFile, namespace='cubeInCone' ) pm.PyNode('cubeInCone:pCube1').attr('translateZ').set(2) pm.PyNode('cubeInCone:sphere:pSphere1').attr('translateZ').set(2) self.coneFile = pm.saveAs( os.path.join( self.temp, 'cone.ma' ), f=1 ) print "master file" pm.newFile(f=1) self.sphereRef1 = pm.createReference( self.sphereFile, namespace='sphere1' ) pm.PyNode('sphere1:pSphere1').attr('translateY').set(2) self.sphereRef2 = pm.createReference( self.sphereFile, namespace='sphere2' ) pm.PyNode('sphere2:pSphere1').attr('translateY').set(4) self.cubeRef1 = pm.createReference( self.cubeFile, namespace='cube1' ) pm.PyNode('cube1:sphere:pSphere1').attr('translateY').set(6) pm.PyNode('cube1:pCube1').attr('translateY').set(6) self.coneRef1 = pm.createReference( self.coneFile, namespace='cone1' ) self.masterFile = pm.saveAs(os.path.join(self.temp, 'master.ma'), f=1)
def build(name=None, crv=None, reg_node=None, log=False): """Create ine node deformer and attributes on given plane, and IK control connected to the reg_node. name -- Prefix name. Str crv -- Curve to add deformer to. nt.Transform reg_node -- registration node. nt.Transform """ general.check_type(name, "name", [str]) general.check_type(crv, "crv", [pm.nt.Transform]) general.check_type(reg_node, "reg_node", [pm.nt.Transform]) cnt_attr = "%s1_ik_cnt" % name if not hasattr(reg_node, cnt_attr): raise errors.InputError("reg_node", reg_node, "Missing attr: %s" % cnt_attr) attr = getattr(reg_node, cnt_attr) cnt = attr.listConnections()[0] if log: str_1 = "Cnt: ", cnt general.logging.debug(str_1) crv2 = crv.duplicate() sineDef, sineHndl = pm.nonLinear(crv2, typ="sine", name="%s_sineDeformer" % name) bs = pm.blendShape(crv2, crv, foc=True, name="%s_sineBlendShape" % name)[0] attr = getattr(bs, crv2[0].name()) attr.set(1) sineDef.rename("%s_sineDeformer" % name) sineHndl.rename("%s_sineDeformerHandle" % name) attrs = {"sineOffOn": [1, 0, 1], "amplitude": 0.3, "wavelength": 2, "offset": 0, "direction": 0} for attr in attrs.keys(): if isinstance(attrs[attr], list): pm.addAttr(cnt, ln=attr, dv=attrs[attr][0], min=attrs[attr][1], max=attrs[attr][2], k=1) else: pm.addAttr(cnt, ln=attr, dv=attrs[attr], k=1) cnt.sineOffOn >> sineDef.envelope cnt.amplitude >> sineDef.amplitude cnt.wavelength >> sineDef.wavelength cnt.offset >> sineDef.offset cnt.direction >> sineHndl.rotateY # Setup the handle hndl_grp = pm.group(name="%s_hndlGrp" % name, em=1) pm.parent(sineHndl, hndl_grp) sineHndl.rz.set(180) sineDef.dropoff.set(1) sineDef.lowBound.set(0) sineDef.highBound.set(2) control.register_object(reg_node, "sine_handle", sineHndl) return reg_node
def doGuide(self): if pm.objExists('facial_guides_grp'): facialGrp = 'facial_guides_grp' else: facialGrp = pm.group(n='facial_guides_grp', em=True) if pm.objExists(self.name + 'Moveall_guide'): pm.delete(self.name + 'Moveall_guide') self.ctrlGuide= self.createCntrl('ctrlGuide') self.baseGuide = self.createCntrl('baseGuide') self.endGuide = self.createCntrl('endGuide') self.midGuide = self.createCntrl('midGuide', hasZeroGrp=True) self.guideMoveall = self.createCntrl('moveallGuide') pm.parent(self.ctrlGuide, self.endGuide) pm.parent(self.baseGuide, self.endGuide, self.midGuide.getParent(), self.guideMoveall) self.setCntrl(self.ctrlGuide, 'ctrl') self.setCntrl(self.baseGuide, 'base') self.setCntrl(self.endGuide, 'end') self.setCntrl(self.midGuide, 'mid') self.setCntrl(self.guideMoveall, 'moveall', space='world') pm.parentConstraint(self.baseGuide, self.endGuide, self.midGuide.getParent(), w=1, mo=False) pm.setAttr(self.baseGuide.translateX, lock=True, keyable=False, channelBox=False) pm.setAttr(self.baseGuide.translateZ, lock=True, keyable=False, channelBox=False) pm.setAttr(self.baseGuide.scaleX, lock=True, keyable=False, channelBox=False) pm.setAttr(self.baseGuide.scaleY, lock=True, keyable=False, channelBox=False) pm.setAttr(self.baseGuide.scaleZ, lock=True, keyable=False, channelBox=False) pm.setAttr(self.baseGuide.rotateX, lock=True, keyable=False, channelBox=False) pm.setAttr(self.baseGuide.rotateY, lock=True, keyable=False, channelBox=False) pm.setAttr(self.baseGuide.rotateZ, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.translateX, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.translateZ, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.scaleX, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.scaleY, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.scaleZ, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.rotateX, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.rotateY, lock=True, keyable=False, channelBox=False) pm.setAttr(self.endGuide.rotateZ, lock=True, keyable=False, channelBox=False) self.length = pm.createNode('distanceBetween') self.baseGuide.worldMatrix[0] >> self.length.inMatrix1 self.endGuide.worldMatrix[0] >> self.length.inMatrix2 self.midPos = pm.createNode('distanceBetween') self.baseGuide.worldMatrix[0] >> self.midPos.inMatrix1 self.midGuide.worldMatrix[0] >> self.midPos.inMatrix2 pm.parent (self.guideMoveall, facialGrp) pm.addAttr(self.guideMoveall, ln='squashDict', dt='string') self.guideMoveall.squashDict.set(json.dumps(self.exportDict()))
def createCurveControl(controlObj, controlAttribute, destinationAttribute): ''' Script: js_createCurveControl.mel Author: Jason Schleifer Descr: This script will create a single curve which can be used to control the given attribute on the selected objects. For example, if you want to drive the ty attribute on 10 objects with a "height" curve on another object, you would select the 10 objects, and then enter: js_createControlCurve controlObj height ty Note: make sure the given object and attribute exists ''' if not pm.objExists(controlObj): pm.pm.mel.error(controlObj + " does not exist. Exiting..\n") if not pm.attributeQuery(controlAttribute, node=controlObj, exists=1): pm.addAttr(controlObj, ln=controlAttribute, at='double') pm.setAttr((controlObj + "." + controlAttribute), k=1) # find the selected objects objs = pm.ls(sl=1) if len(objs) == 0: pm.pm.mel.error("Nothing Selected.\n") numControls = len(objs) # now that we have the objects, we can create the animation curve which will control the attribute objAttr = (controlObj + "." + controlAttribute) pm.setKeyframe(controlObj, v=0, at=controlAttribute, t=1) pm.setKeyframe(controlObj, v=0, at=controlAttribute, t=numControls) pm.keyTangent(controlObj, wt=1, at=controlAttribute) pm.keyTangent(controlObj, at=controlAttribute, weightLock=False) pm.keyTangent(objAttr, a=1, e=1, t=1, outAngle=50) pm.keyTangent(objAttr, a=1, e=1, t=numControls, inAngle=-50) # next, we'll create frameCache nodes for each object, and attach them to the object's attribute for x in range(0, numControls): fc = pm.createNode('frameCache') # create the frameCache node fc = pm.rename(fc, (str(objs[x]) + "_frameCache")) # connect the attribute pm.connectAttr(objAttr, (str(fc) + ".stream")) # set the frame pm.setAttr((str(fc) + ".vt"), (x + 1)) # connect the output # check and see if the destination attribute exists. if not, create it if not pm.attributeQuery(destinationAttribute, node=objs[x], exists=1): pm.addAttr(objs[x], ln=destinationAttribute, at='double') pm.setAttr((str(objs[x]) + "." + destinationAttribute), k=1) pm.connectAttr((str(fc) + ".v"), (str(objs[x]) + "." + destinationAttribute), f=1) pm.select(objAttr)
def createHierarchy(): """hierarchy construction""" gp = {} # create groups grps = [['TEMPLATES'], ['BDD'], ['PERSO'], ['SKINSKEL'], ['ADDITIVERIG'], ['ANIMATION'], ['TODELETE'], ['SETUP','PERSO|'], ['SCALEOFFSET','PERSO|SETUP|'], ['NOXFORM','PERSO|SETUP|']] for grp in grps: # create the absolute path tmpName = '|' for i in reversed(range(len(grp))): tmpName += grp[i] # check if the object exist if pmc.objExists(tmpName): gp[grp[0]] = pmc.PyNode(tmpName) else: gp[grp[0]] = pmc.createNode('transform', name=grp[0], skipSelect=True) if len(grp)==2: gp[grp[0]].setParent(grp[1]) clean.__lockHideTransform__(gp[grp[0]], channel=['v']) # uncheck inherits transform gp['BDD'].inheritsTransform.set(False) gp['NOXFORM'].inheritsTransform.set(False) # create scale offset attribut if gp['SCALEOFFSET'].hasAttr('scaleOffset')==False: pmc.addAttr(gp['SCALEOFFSET'], longName='scaleOffset', attributeType='float', defaultValue=1.0, keyable=True ) # connect the scale offset attribut into the scale clean.__lockHideTransform__(gp['SCALEOFFSET'], channel=['s'], lock=False) if len(gp['SCALEOFFSET'].sx.inputs(plugs=True))==0: gp['SCALEOFFSET'].scaleOffset >> gp['SCALEOFFSET'].sx if len(gp['SCALEOFFSET'].sy.inputs(plugs=True))==0: gp['SCALEOFFSET'].scaleOffset >> gp['SCALEOFFSET'].sy if len(gp['SCALEOFFSET'].sz.inputs(plugs=True))==0: gp['SCALEOFFSET'].scaleOffset >> gp['SCALEOFFSET'].sz # hide and lock attribut for key in gp.keys(): clean.__lockHideTransform__(gp[key], channel=['t', 'r', 's']) # create set pmc.select(clear=True) sets = ['CONTROLS'] for set in sets: if pmc.objExists(set)==False: gp[set] = pmc.sets(name=set) else: gp[set] = pmc.nodetypes.ObjectSet('CONTROLS') return gp
def bdImportCon(con): xmlPath = 'c:\\Users\\bogdan_d\\Documents\\bdPyScripts\\controllers\\' dom = parse(xmlPath + con) controllerNode = dom.getElementsByTagName('controller') for node in controllerNode: conName = node.getAttribute('name') shapeNodes = node.getElementsByTagName('shape') curvesToParent = [] for s in shapeNodes: shapeName = s.getAttribute('name') print shapeName shapeCvs = s.getAttribute('cvs') pos = [ float(pos.strip('[](),')) for pos in shapeCvs.split(" ") ] reconstructedPos = [(pos[i], pos[i + 1], pos[i + 2]) for i in range(0, len(pos), 3)] shapeKnots = s.getAttribute('knots') knots = [ float(k.strip('[](),')) for k in shapeKnots.split(" ") ] reconstructedKnots = [k for k in knots] shapeDegree = int(s.getAttribute('degree')) shapePeriodic = int(s.getAttribute('periodic')) curve = pm.curve(p=reconstructedPos, k=reconstructedKnots, d=shapeDegree, per=shapePeriodic) curve.rename(shapeName.replace('Shape', '')) curvesToParent.append(curve) parentCurve = curvesToParent[0] for curve in curvesToParent[1:]: pm.parent(curve.getShape(), parentCurve, r=1, shape=1) pm.delete(curve) pm.select(cl=1) parentCurve.centerPivots() atributesList = node.getElementsByTagName('attribute') for attr in atributesList: attrType = attr.getAttribute('type') attrName = attr.getAttribute('name') attrLocked = attr.getAttribute('locked') attrCB = attr.getAttribute('channelBox') attrVal = attr.getAttribute('value') attrMinMax = attr.getAttribute('minMax') if attrType == 'string': pm.addAttr(parentCurve, ln=attrName, dt=attrType) parentCurve.attr(attrName).setLocked(attrLocked) else: pm.addAttr(parentCurve, ln=attrName, at=attrType) parentCurve.attr(attrName).setLocked(attrLocked)
def CreateSpaceSwitch(self, _aSpaces, _aLabels, _bUseDefault=True): oConstraint = pymel.parentConstraint(_aSpaces, self.offset, maintainOffset=True) pymel.addAttr(self.offset, longName='space', at='enum', enumName=_aLabels) attSpace = self.offset.getAttr('space') aWeightAtts = oConstraint.getWeightAliasList() for i, attWeight in enumerate(aWeightAtts): iIndexToMatch = i if not _bUseDefault else i + 1 attSpaceIsActive = libRigging.CreateUtilityNode('condition', firstTerm=attSpace, secondTerm=iIndexToMatch, colorIfTrueR=1, colorIfFalseR=0).outColorR #Equal pymel.connectAttr(attSpaceIsActive, attWeight)
def addAOV( name ): aovName = 'id_' + name aovs.AOVInterface().addAOV( aovName ) aovNode = aovs.AOVInterface().getAOVNode( aovName ) pm.addAttr( aovNode, longName='isID', niceName='ai_ID', attributeType='bool', defaultValue=1 ) aovNode.setAttr( 'isID', lock=True ) return 1