def rig_humanProject_skeletonStrip(): '''Strips the human Skeleton Layout Puppet of its joints etc Args (None) Returns (None) ''' skel_grp = pm.PyNode('skeleton_GRP') pm.select(skel_grp,hi=True,r=True) hierarchy = pm.ls(sl=True, tr=True) for obj in hierarchy: for attr in ['jointOrient','r','s','t','tx','ty','tz','rx','ry','rz','sx','sy','sz']: if pm.objExists(obj+'.'+attr): obj.attr(attr).disconnect() obj.attr(attr).unlock() if obj.type() in ['parentConstraint','aimConstraint','orientConstraint','pointConstraint','scaleConstraint']: if obj: pm.delete(obj) pm.select('spineJA_JNT',r=True) mel.eval('rig_humanProjectUI_rotationsToOrients_cb()') skel_grp.setParent(w=True) skel_grp.v.disconnect() skel_grp.overrideEnabled.disconnect() skel_grp.overrideEnabled.set(0) skel_grp.v.set(1) pm.delete('wwzRigPuppetSkeletonLayoutATop_GRP') mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes");')
def check_uv_existence(): """check if there are uvs in all objects """ # skip if this is a representation v = staging.get('version') if v and Representation.repr_separator in v.take_name: return all_meshes = pm.ls(type='mesh') nodes_with_no_uvs = [] for node in all_meshes: if not node.getAttr('intermediateObject'): if not len(node.getUVs(uvSet='map1')[0]): nodes_with_no_uvs.append(node) if len(nodes_with_no_uvs) > 0: # get transform nodes tra_nodes = map( lambda x: x.getParent(), nodes_with_no_uvs ) pm.select(tra_nodes) raise RuntimeError( """There are nodes with <b>no UVs</b>: <br><br>%s""" % '<br>'.join( map(lambda x: x.name(), tra_nodes[:MAX_NODE_DISPLAY]) ) )
def check_if_leaf_mesh_nodes_have_no_transformation(): """checks if all the Mesh transforms have 0 transformation, but it is allowed to move the mesh nodes in space with a parent group node. """ mesh_nodes_with_transform_children = [] for node in pm.ls(dag=1, type='mesh'): parent = node.getParent() tra_under_shape = pm.ls( parent.listRelatives(), type='transform' ) if len(tra_under_shape): mesh_nodes_with_transform_children.append(parent) if len(mesh_nodes_with_transform_children): pm.select(mesh_nodes_with_transform_children) raise PublishError( 'The following meshes have other objects parented to them:' '\n\n%s' '\n\nPlease remove any object under them!' % '\n'.join( map(lambda x: x.name(), mesh_nodes_with_transform_children[:MAX_NODE_DISPLAY]) ) )
def bdAddTwist(self,surfaceRbn_BS): pm.select(surfaceRbn_BS) twistDef, twistDefTransform = pm.nonLinear(type='twist') twistDefTransform.rename(surfaceRbn_BS.name().replace('SRF_BS','twistHandle')) twistDef.rename(surfaceRbn_BS.name().replace('SRF_BS','twist')) twistDefTransform.rotateX.set(180) return twistDef, twistDefTransform
def check_model_quality(): """checks the quality of the model """ # skip if this is a representation v = staging.get('version') if v and Representation.repr_separator in v.take_name: return pm.select(None) pm.mel.eval( 'polyCleanupArgList 3 { "1","2","0","0","1","0","0","0","0","1e-005",' '"0","0","0","0","0","2","1" };' ) if len(pm.ls(sl=1)) > 0: raise RuntimeError( """There are issues in your model please run:<br><br> <b>PolygonMesh -> Mesh -> Cleanup...</b><br><br> <ul>Check: <li>Faces with more than 4 sides</li> <li>Faces with holes</li> <li>Lamina Faces</li> <li>Non-manifold Geometry</li> </ul>""" )
def createFkAnimatedSystemConstraints(self): pm.select(cl = True) #FkManips #iterate fkManipsList for index in range(0, len(self.fkAnimatedManipsList) - 1): #constrain pm.scaleConstraint( self.fkAnimatedManipsList[index], self.fkAnimatedManipsList[index + 1].getParent(), mo = True ) pm.parentConstraint( self.fkAnimatedManipsList[index], self.fkAnimatedManipsList[index + 1].getParent(), mo = True ) pm.select(cl = True) #FkManipBase pm.scaleConstraint( self.manip_master, self.fkAnimatedManipsList[0].getParent(), mo = True ) pm.parentConstraint( self.manip_master, self.fkAnimatedManipsList[0].getParent(), mo = True ) pm.select(cl = True) #FkAnimatedJointsGrp pm.scaleConstraint( self.manip_master, self.fkAnimatedJointsGrp, mo = True ) pm.parentConstraint( self.manip_master, self.fkAnimatedJointsGrp, mo = True ) pm.select(cl = True) #Orientconstrain all fkAnimatedJoints for index in range(0, len(self.fkAnimatedManipsList)): pm.orientConstraint( self.fkAnimatedManipsList[index], self.fkAnimatedJointsList[index], mo = True ) pm.select(cl = True)
def check_history(): """there should be no history on the objects """ excluded_types = ['mesh', 'shadingEngine', 'groupId'] nodes_with_history = [] # get all shapes all_shapes = pm.ls(type='mesh') for node in all_shapes: history_nodes = [] for h_node in node.listHistory(pdo=1, lv=1): if h_node.type() not in excluded_types: history_nodes.append(h_node) if len(history_nodes) > 0: nodes_with_history.append(node) if len(nodes_with_history): pm.select(nodes_with_history) # there is history raise PublishError( 'There is history on:\n\n' '%s' '\n\n' 'there should be no ' 'history in Model versions' % '\n'.join( map(lambda x: x.name(), nodes_with_history[:MAX_NODE_DISPLAY]) ) )
def __init__(self, selVerts, loopNum): ''' Populates the data from an initial loop of verts, and the number of loops around it selVerts - flattened list of MeshVertex loopNum - int ''' # initialize lists for the loop previousLoop = selVerts nextLoop = [] self.vertLoops = [list(previousLoop)] pm.select(selVerts, r=True) #pm.progressWindow(title='Analyzing edge loops', progress=0, max=loopNum) # traverse loops outward from selection for loopId in range(loopNum): previousLoop += nextLoop pm.runtime.GrowPolygonSelectionRegion() selVertsLoop = pm.ls(sl=True, fl=True) nextLoop = [vert for vert in selVertsLoop if vert not in previousLoop] self.vertLoops.append(nextLoop)
def createEmitter(self, mesh, name="particleEmitter_msh"): # Create boundingBox of the mesh bbx = pm.polyEvaluate(mesh, b=True) cube = pm.polyCube( w=abs(bbx[0][1] - bbx[0][0]), h=abs(bbx[1][1] - bbx[1][0]), d=abs(bbx[2][1] - bbx[2][0]), sx=1, sy=1, sz=1, ax=(0, 1, 0), cuv=4, ch=0, name=name, ) cube = cube[0] cube.setAttr("t", ((bbx[0][1] + bbx[0][0]) / 2, (bbx[1][1] + bbx[1][0]) / 2, (bbx[2][1] + bbx[2][0]) / 2)) # Keep only face 1 for emit pm.delete([cube + ".f[2:6]", cube + ".f[0]"]) # Connection of mesh and the emitter self.connectOriginaleMesh(mesh, cube) # Move emitter in y in a percentage of area of face. face = pm.PyNode(cube + ".f[1]") area = face.getArea(space="world") pm.select(cube) y = pow(area, 0.1) * 100 pm.move(0, y, 0, r=1, os=1, wd=1) return cube
def rigParentControl( joint_name ): jnt = pm.nt.Transform(joint_name) grp = pm.group(name="%s_parent"%jnt, em=True) pm.parent(grp, joint_name) grp.t.set([0,0,0]) grp.r.set([0,0,0]) pm.parent(grp, world=1) try: rig, rig_type = pm.ls('rig',showType=1) except: rig, rig_type = (None, None) if rig_type == 'transform': pm.parent(grp,rig) pm.parentConstraint( jnt.getParent(), grp, mo=1, w=1) grp.t.lock() grp.r.lock() grp.s.lock() control = createNurbsShape("%s_control"%jnt,"cube",width=0.5, height=0.5, depth=0.5) addToSet( [control], 'controlsSet' ) pm.parent(control,grp) control.t.set([0,0,0]) control.r.set([0,0,0]) control.displayHandle.set(1) pm.parentConstraint( control, jnt, mo=1, w=1) pm.select( control, r=1 ) return [ control ]
def rebuildDagPose(): """ Walks through bind pose data in selected skeleton and consolidates it down to one new bindPose node Directly inspired by Nathan Horne's NT_rebuildDagPose.mel script """ dagPoses = set() connectedSkinClusters = set() selection = pmc.selected() joints = pmc.listRelatives(selection[0], path=True, allDescendents=True, type="joint") joints.insert(0, selection[0]) for jnt in joints: dagPoses.update(jnt.listConnections(type="dagPose")) for dag in dagPoses: connectedSkinClusters.update(dag.listConnections(type="skinCluster")) pmc.delete(dagPoses) pmc.select(joints, replace=True) newDagPose = pmc.dagPose(save=True, selection=True, bindPose=True) print "New dagPose, {0}, created".format(newDagPose.shortName()) for sc in connectedSkinClusters: print "Connecting {0}.message to {1}.bindPose".format(newDagPose.shortName(), sc.shortName()) newDagPose.message.connect(sc.bindPose)
def edgeFlow(self): oldSel = pm.ls(sl = 1) pm.select(pm.ls(o=1, sl=1)) selected = pm.ls(sl = 1) pm.delete(selected, constructionHistory = 1) pm.select(cl = 1) for s in selected: rootEdges = pm.ls( self.root(s) , fl = 1) tipEdges = pm.ls( self.tip(s) , fl = 1) ############length edgeloops of the card myEdges = pm.ls(pm.polySelect(s, ebp = [ rootEdges[0].index(), tipEdges[0].index() ],ass = True ), fl = 1) side1Edges = [x for x in myEdges if x not in rootEdges and x not in tipEdges] borderEdges = [x for x in pm.ls(s.e, fl = 1) if x.isOnBoundary()] pm.select(tipEdges) for x in range(len(side1Edges)*2): if x != borderEdges and x!= rootEdges and x!= tipEdges: pm.polyEditEdgeFlow(adjustEdgeFlow=1, constructionHistory=0) pm.pickWalk(type = 'edgeloop', direction = 'left') if self.lenCheckBox.getValue() == 1: pm.select(side1Edges) for x in range( len(rootEdges)*2 ): pm.polyEditEdgeFlow(adjustEdgeFlow=1, constructionHistory=0) pm.pickWalk(type = 'edgeloop', direction = 'left') pm.select(oldSel)
def randomTransformSel(self, myList): amount = int((1.0-self.randSliderT.getValue()/10) * len(myList)) result = [] for x in range(amount): myList.pop(random.randint(0, len(myList)-1)) pm.select(cl = 1) pm.select(myList)
def _delConstraints(self, jnt, *args): pm.select(jnt, hi=1, r=1) sel = pm.ls(sl=1) consList = ['parentConstraint','scaleConstraint','orientConstraint', 'pointConstraint'] for each in sel: for cons in consList: if each.type() == cons: pm.delete(each)
def middle2(self, s): middleL = [] #use input field data to determine flat uv set flatUvSet = self.findFlatUvSet(s) #get tips of geo and split to top and bottom pairs pair1, pair2 = self.findTips(s, flatUvSet) #select edges going the length on the cards and list as vertices pm.polyUVSet(s, currentUVSet =1, uvSet=flatUvSet) side1Edge = pm.polySelect(s, ass = 1, shortestEdgePathUV = (pair1[0].getUVIndices(str(flatUvSet))[0], pair1[1].getUVIndices(str(flatUvSet))[0])) side1 = pm.ls(pm.polyListComponentConversion(side1Edge, fe =1, tv =1), fl = 1) if len(side1) > 2: side2Edge = pm.polySelect(s, ass = 1, shortestEdgePathUV = (pair2[0].getUVIndices(str(flatUvSet))[0], pair2[1].getUVIndices(str(flatUvSet))[0])) side2 = pm.ls(pm.polyListComponentConversion(side2Edge, fe =1, tv =1), fl = 1) #select bottom verts and walk(traverse) to the middle of the geo on both sides mid1 = pm.ls(self.traverse(start = pair1[0], listToWalk = side1, multiplyBy = 0.5 )) mid2 = pm.ls(self.traverse(start = pair2[0], listToWalk = side2, multiplyBy = 0.5 )) #select shortest path between the 2 middle points and add to the middleL list MidLine = pm.polySelect(s, ass = 1, shortestEdgePathUV = (mid1[0].getUVIndices(str(flatUvSet))[0], mid2[0].getUVIndices(str(flatUvSet))[0])) middleL.append(MidLine) pm.select(cl = 1) if len(side1) % 2 == 0: mid3 = pm.ls(self.traverse(start = pair1[-1], listToWalk = side1, multiplyBy = 0.5 )) mid4 = pm.ls(self.traverse(start = pair2[-1], listToWalk = side2, multiplyBy = 0.5 )) MidLine2 = pm.polySelect(s, ass = 1, shortestEdgePathUV = (mid3[0].getUVIndices(str(flatUvSet))[0], mid4[0].getUVIndices(str(flatUvSet))[0])) middleL.append(MidLine2) pm.select(cl = 1) return pm.ls( middleL, fl = True)
def export_hierarchy_obj(self): """Export the individual meshes in the hierarchy""" file_info = {} # Reverse the geo list so that the deepest geo is deleted first in case there is a geo inside geo geo_list = self.geo_list geo_list.reverse() for self.current_target in geo_list: pm.delete(self.current_target, ch=1) parent = pm.listRelatives(self.current_target, parent=True) pm.parent(self.current_target, w=True) pm.select(self.current_target) path = libFile.linux_path(libFile.join(self.export_dir, self.current_target + ".obj")) # Load the obj plugin cmds.file(path, pr=1, typ="OBJexport", force=1, options="groups=0;ptgroups=0;materials=0;smoothing=0;normals=0", es=1) file_info[self.current_target] = path logger.info("Exporting\n%s" % file_info[self.current_target]) if not self.new_scene and self.cleansing_mode: pm.delete(self.current_target) pm.refresh() else: pm.parent(self.current_target, parent) self.update_progress() # Write the geo file_info self.geo_file_info = file_info
def import_hierarchy_geo(self): """Import all the obj objects""" file_info = self.geo_file_info for self.current_target in file_info.keys(): cmds.file(file_info[self.current_target], rpr="PKD_Temp", i=1, type="OBJ", loadReferenceDepth="all", ra=True, mergeNamespacesOnClash=False, options="mo=1") # Delete Existing geo if it exists if not self.cleansing_mode: if pm.objExists(self.current_target): pm.delete(self.current_target) logger.info("Importing\n%s" % file_info[self.current_target]) if self.cleansing_mode: os.remove(file_info[self.current_target]) for top in pm.ls(assemblies=True, ud=True): if top.getShape(): if top.getShape().type() == "mesh" and top.name() == "PKD_Temp_Mesh": top.rename(self.current_target) pm.select(self.current_target) mel.eval("polySetToFaceNormal") mel.eval("polySoftEdge -a 180 -ch 1 %s" % self.current_target) pm.delete(self.current_target, ch=1) pm.refresh() self.update_progress()
def buildIK(self, *args): """ Build the IK """ #Setup variables if self.normal == 1: self.normal = (1, 0, 0) if self.normal == 2: self.normal = (0, 1, 0) if self.normal == 3: self.normal = (0, 0, 1) #Create IK control self.ikControl = pm.circle(nr=self.normal, r=self.radius, n='%s_ikCnt'%self.prefix) pm.select(self.ikControl[0], r=True) pm.mel.eval("DeleteHistory;") pm.delete( pm.parentConstraint(self.ikChain[2], self.ikControl[0], mo=0) ) self.zero(self.ikControl[0]) #Create RP IK self.arm_ikHandle = pm.ikHandle(sj=self.ikChain[0], ee=self.ikChain[2], solver='ikRPsolver', name=(self.prefix + '_armIkHandle')) pm.setAttr(self.arm_ikHandle[0] + '.visibility', 0) #Parent IK Handle to the ikWrist_cnt pm.parent(self.arm_ikHandle[0], self.ikControl[0]) # Creates: self.pv_cnt self.createPoleVector()
def fromList(self,posList = [],orientList = [],autoOrient = 1): for i in range(len(posList)): tempName = nameUtils.getUniqueName(self.side,self.baseName,self.type) if i == len(posList) - 1: tempName = nameUtils.getUniqueName(self.side,self.baseName,self.type) pm.select(cl = 1) if autoOrient == 1: tempJnt = pm.joint(n = tempName,position = posList[i]) else : tempJnt = pm.joint(n = tempName,position = posList[i],orientation = orientList[i]) self.chain.append(tempJnt) self.__parentJoints() if autoOrient == 1: #pm.joint(self.chain[0].name(),e = 1,oj = 'yzx',secondaryAxisOrient = 'zup',ch = 1) pm.joint(self.chain[0].name(),e = 1,oj = 'xyz',secondaryAxisOrient = 'zdown',ch = 1) #xzy -secondaryAxisOrient ydown -ch -zso; self.__zeroOrientJoint(self.chain[-1])
def createBoundJointChain(self): pm.select(cl = True) #Iterate highResCurveCoordList and append to boundJointsList joint at each position self.boundJointsList = [] for index in range(0, len(self.highResCurveCoordList)): #create Joint #decide jointNames jointName = self.prefix + '_bound_j_' + str(index + 1) if( index == 0 ): jointName = self.prefix + '_bound_j_' + 'base' if( index + 1 == len(self.highResCurveCoordList) ): jointName = self.prefix + '_bound_j_' + 'tip' joint = pm.joint(a = True, p= self.highResCurveCoordList[index] , co = True, n = jointName) self.boundJointsList.append(joint) pm.select(cl = True) #Orient boundJoints pm.joint(self.boundJointsList[0], e = True, sao = 'yup', oj='xyz', zso = True, ch = True) pm.select(cl = True) #Create boundJointsGrp and parent first bound joint self.boundJointsGrp = pm.group(n = self.prefix + '_bound_joints_grp') pm.select(cl = True) pm.parent(self.boundJointsList[0] , self.boundJointsGrp) pm.select(cl = True)
def createSkinclusterAndSplineIk(self): #Skincluster #---------------------------------------------------- pm.select(cl = True) self.bound_curve_skincluster = pm.skinCluster( self.splineIkBoundJointsList , self.lowResCurveTrans ,tsb=True, n = self.prefix + '_bound_curve_skincluster', rui = False, ih = True) pm.select(cl = True) #Spline Ik #---------------------------------------------------- pm.select( cl = True ) #Create spline IK self.bound_curve_spline_ik = pm.ikHandle( sj= self.ikSplineJointsList[0] , ee= self.ikSplineJointsList[-1] , roc = True, n = self.prefix + '_ikSplineHandle_bound_curve', c = self.lowResCurveTrans, ccv = False, pcv = False, sol = 'ikSplineSolver' )[0] pm.select( cl = True ) #Group Spline_ik self.bound_curve_spline_ik_grp = pm.group(self.bound_curve_spline_ik , n= self.prefix + '_ikSplineHandle_bound_curve_grp' ) pm.select(cl = True)
def rtb_shrink_wrap_verts(highresListDropdown, *args, **kwargs): ''' ''' global defaultString high = highresListDropdown.getValue() if not high == defaultString: pm.undoInfo(openChunk=True) live = pm.PyNode(high.replace('_high', '_live')) liveShape = live.getShape() sel = pm.ls(sl=True) if sel: verts = geometry.getVertsFromSelection(sel) if verts and verts[0].nodeType() == 'mesh': try: geometry.shrinkWrap(verts, liveShape, prefix+'_progress_control') except: pm.warning('You Should Not See This Error!') pm.progressBar(prefix+'_progress_control', edit=True, endProgress=True) else: pm.warning('No verts to shrink wrap!') pm.select(sel, r=True) pm.hilite(pm.PyNode(sel[0].split('.')[0]).getParent(), r=True) type = geometry.getMeshSelectionType(sel) geometry.switchSelectType(type) pm.undoInfo(closeChunk=True) else: pm.warning('Select a mesh from the dropdown list')
def createLocToCenter(): old_selection = pymel.selected() p3Pos = get_center(pymel.selected(flatten=True)) pPoint = pymel.general.spaceLocator() pPoint.setTranslation(p3Pos, space='world') if old_selection: pymel.select(old_selection)
def getAlpha(): target = py.ls(sl=1) py.select(target[0]) s = getShader() aa = py.getAttr(s + ".transparency") a = 255 * abs(1-aa[0]) return a
def keyAlpha(c): target = py.ls(sl=1) for i in range(0,len(target)): py.select(target[i]) s = getShader() setA(s,c) py.mel.eval("setKeyframe { \"" + s + ".it\" };")
def bdAddExtraGrp(nameMaskCon,grpType,empty): controllers = pm.ls(nameMaskCon,type = 'transform') conPyNodes = [] for con in controllers: conPyNodes.append(con) for node in conPyNodes: if empty: pm.select(cl=True) conGrp = pm.group(name = node.name() + '_' + grpType) pos = node.getTranslation(space='world') rot = node.getRotation(space='world') conGrp.setTranslation(pos) conGrp.setRotation(rot) parent = node.getParent() pm.parent(conGrp,parent) else: conGrp = pm.duplicate(node,name = node.name().replace('CON',grpType)) ''' for axis in ['X','Y','Z']: conGrp[0].attr('translate' + axis).setKeyable(True) conGrp[0].attr('translate' + axis).setLocked(False) ''' conGrpRelatives = pm.listRelatives(conGrp,ad = True) #print sdkConRelatives pm.delete(conGrpRelatives) pm.parent(node,conGrp)
def setAlpha(c): target = py.ls(sl=1) for i in range(0,len(target)): py.select(target[i]) s = getShader() a = abs(1-(float(c) / 255.0)) py.setAttr(s + ".transparency", (a,a,a))
def getSkinBones(): aInfluences = [] for oCurObj in pymel.selected(): oSkinCluster = getSkinCluster(oCurObj) if oSkinCluster is not None: aInfluences += libSkinning.get_skin_cluster_influence_objects(oSkinCluster) pymel.select(aInfluences)
def vis_orbits(self): global vis_orbGrp vis_orbGrp = pm.group(n='olp_visOrbits', em=True) intervValue = self.interv_int.value() distValue = self.distance_float.value() orbitValue = self.orbit_int.value() global all_orbitObjs all_orbitObjs = [] for orbit in range(orbitValue): orbitRot = orbit * 360/float(orbitValue*2) orbit_visObject = pm.circle(n='olp_orbCircle{0}'.format(orbit+1), r=distValue, s=intervValue*2, nr=[1, 0, 0], ch=True)[0] pm.parent(orbit_visObject, vis_orbGrp) orbit_visObject.overrideEnabled.set(1) orbit_visObject.overrideColorRGB.set(0, 1, 1) orbit_visObject.overrideRGBColors.set(1) pm.xform(orbit_visObject, ro=[0, 0, orbitRot]) all_orbitObjs.append(orbit_visObject) pm.xform(vis_orbGrp, a=True, t=sel_center) pm.parent(vis_orbGrp, vis_mainGrp) pm.select(sel_objects, r=True) return vis_orbGrp
def create(ctl, tipGeo, weights, name, keys, addGeos=[], useScale=False): ''' tipGeo - vtx of the tip of the eye weights - list of weights for each loop radiating outwards (including geoTip) e.g. [1, 1, 1, 1, 1, .95, 0.75, 0.5, .25, .1] addGeo - list of additional geometry for cluster to deform name - 'pupil' or 'iris' e.g.: geo = nt.Mesh(u'LT_eyeball_geoShape') tipGeo = geo.vtx[381] ctl = nt.Transform(u'LT_eye_ctl') name = '_iris' keys = {'sx': {0.01:0.01, 1:1, 2:2}, 'sy': {0.01:0.01, 1:1, 2:2}, 'sz': {0.01:0.01, 1:1, 2:3.75}} weights = [1, 1, 1, 1, 1, .95, 0.75, 0.5, .25, .1] ''' geo = tipGeo.node() dfm, hdl = pm.cluster(tipGeo, n=ctl+name+'_dfm', foc=True) dfg = pm.group(hdl, n=ctl+name+'_dfg') rp = hdl.getRotatePivot(space='world') sp = hdl.getScalePivot(space='world') dfg.setRotatePivot(rp, space='world') dfg.setScalePivot(sp, space='world') dfh = pm.group(dfg, n=ctl+name+'_dfh') ctl.addAttr(name, min=0.01, max=2, dv=1, k=True) for attr, key in keys.items(): rt.connectSDK(ctl.attr(name), hdl.attr(attr), key) loopNums = len(weights) - 1 vertLoops = mesh.VertexLoops([tipGeo], loopNums) # add membership pm.select(vertLoops[:]) for vertLoop in vertLoops[:]: for eachVert in vertLoop: dfm.setGeometry(eachVert) for loopId, weight in enumerate(weights): for eachVert in vertLoops[loopId]: print eachVert dfm.setWeight(geo, 0, eachVert, weight) # add additional geometries for eachGeo in addGeos: dfm.setGeometry(eachGeo, foc=True) if useScale: # modulate cluster scale by control scale for eachAttr in ('sx', 'sy', 'sz'): scaleInput = hdl.attr(eachAttr).inputs(p=True)[0] mdl = pm.createNode('multDoubleLinear', n=hdl+'_'+eachAttr+'_scale_mdl') scaleInput >> mdl.input1 ctl.attr(eachAttr) >> mdl.input2 mdl.output >> hdl.attr(eachAttr) return dfh
def makeCard(self): ''' Make a new card and child it if a BPJoint is selected. .. todo:: I think, when adding a chain, if the parent doesn't have an orient target already, give it its existing child. Of course this won't quite work for the pelvis but whatever. ''' try: radius = 1 targetParent = util.selectedJoints()[0] if util.selectedJoints( ) else None if not targetParent and selected(): # Quick hack for if the annotation is selected instead of the # handle. This is really just a pain and I should link the # Annotation to the real joint. try: intendedTarget = selected()[0].t.listConnections( )[0].output3D.listConnections()[0] if intendedTarget.__class__.__name__ == 'BPJoint': targetParent = intendedTarget except Exception: pass count = self.ui.jointCount.value() name = str(self.ui.cardJointNames.text()) # Auto repeat the name if only one was given if len(name.split()) == 1 and count > 1 and name[-1] != '*': name += '*' try: head, repeat, tail = util.parse(name) except Exception: raise Exception('Invalid characters given') if count <= 0: raise Exception('You must specify at least one joint!') namedCount = len(head) + len(tail) + (1 if repeat else 0) print(namedCount) if count < namedCount: raise Exception( 'Not enough joints exist to take all of the given names') if count > namedCount and not repeat: raise Exception( 'No name was specified as repeating and too many joints were given.' ) #card = skeletonTool.core.Card( jointCount=count, name=name, rigInfo=None, size=(4, 6) ) newCard = fossil_card.makeCard(jointCount=count, jointNames=name, rigInfo=None, size=(4, 6)) if targetParent: moveCard.to(newCard, targetParent) #skeletonTool.proxy.pointer( targetParent, newCard.start() ) newCard.start().setBPParent(targetParent) radius = targetParent.radius.get() else: proxy.makeProxy(newCard.start()) newCard.start().proxy.setParent(proxy.getProxyGroup()) for j in newCard.joints: j.radius.set(radius) j.proxy.radius.set(radius) select(newCard) except Exception as ex: print(traceback.format_exc()) m = str(ex) + '''\n All names must be valid as Maya names. Optionally one may end with a '*' signifying it repeats. Ex: Chest Neck* Head HeadTip Would only be valid if the card had at least 4 joints, any above that would increase the Neck: Chest Neck01 Neck02 .. Neck<N> Head HeadTip Repeating can be at the start or end or no repeats at all, as long as the numbers make sense. ''' confirmDialog(t='Error', m=m) raise
def finalize(self): """Finalize the rig.""" groupIdx = 0 # Properties -------------------------------------- mgear.log("Finalize") # clean jnt_org -------------------------------------- if self.options["joint_rig"]: mgear.log("Cleaning jnt org") for jOrg in dag.findChildrenPartial(self.jnt_org, "org"): if not jOrg.listRelatives(c=True): pm.delete(jOrg) # Groups ------------------------------------------ mgear.log("Creating groups") # Retrieve group content from components for name in self.componentsIndex: component_ = self.components[name] for name, objects in component_.groups.items(): self.addToGroup(objects, name) for name, objects in component_.subGroups.items(): self.addToSubGroup(objects, name) # Create master set to group all the groups masterSet = pm.sets(n=self.model.name() + "_sets_grp", em=True) pm.connectAttr(masterSet.message, self.model.rigGroups[groupIdx]) groupIdx += 1 # Creating all groups pm.select(cl=True) for name, objects in self.groups.items(): s = pm.sets(n=self.model.name() + "_" + name + "_grp") s.union(objects) pm.connectAttr(s.message, self.model.rigGroups[groupIdx]) groupIdx += 1 masterSet.add(s) for parentGroup, subgroups in self.subGroups.items(): pg = pm.PyNode(self.model.name() + "_" + parentGroup + "_grp") for sg in subgroups: sub = pm.PyNode(self.model.name() + "_" + sg + "_grp") if sub in masterSet.members(): masterSet.remove(sub) pg.add(sub) # Bind pose --------------------------------------- # controls_grp = self.groups["controllers"] # pprint(controls_grp, stream=None, indent=1, width=100) ctl_master_grp = pm.PyNode(self.model.name() + "_controllers_grp") pm.select(ctl_master_grp, replace=True) dag_node = pm.dagPose(save=True, selection=True) pm.connectAttr(dag_node.message, self.model.rigPoses[0]) print(dag_node) # Bind skin re-apply if self.options["importSkin"]: try: pm.displayInfo("Importing Skin") skin.importSkin(self.options["skin"]) except RuntimeError: pm.displayWarning( "Skin doesn't exist or is not correct. " + self.options["skin"] + " Skipped!" )
def displayoverrideAll_Off(): pm.select(hi=True) selection = pm.selected() if len(selection) == 0: pm.error("select maya DAG nodes that you want to affect") display_override(selection, False, "normal")
def _UI(self): if cmds.window(self.win, exists=True): cmds.deleteUI(self.win, window=True) cmds.window(self.win, title=self.win, menuBar=True, sizeable=False, widthHeight=(300, 380)) cmds.menu(label='Help') cmds.menuItem(label='Watch MasterClass Video', c=lambda x: self._contactDetails(opentype='vimeo')) cmds.menuItem(label='Contact', c=r9Setup.red9ContactInfo) # cmds.menuItem(label='Contact', c=lambda x:self._contactDetails(opentype='email')) cmds.menuItem(label='Blog', c=r9Setup.red9_blog) cmds.menuItem(label='Red9HomePage', c=r9Setup.red9_website_home) cmds.columnLayout(adjustableColumn=True) cmds.text(fn="boldLabelFont", label="Advanced Bind Options") cmds.separator(h=15, style="none") cmds.rowColumnLayout(numberOfColumns=2, cw=((1, 150), (2, 150)), cs=((1, 10))) cmds.checkBox( value=self.settings.bind_rots, label="bind_rots", ann="Bind only the Rotates of the given Controller", al="left", onc=lambda x: self.settings.__setattr__('bind_rots', True), ofc=lambda x: self.settings.__setattr__('bind_rots', False)) cmds.checkBox( value=self.settings.bind_trans, label="bind_trans", ann="Bind only the Translates of the given Controller", al="left", onc=lambda x: self.settings.__setattr__('bind_trans', True), ofc=lambda x: self.settings.__setattr__('bind_trans', False)) cmds.checkBox( value=1, label="AlignRots CtrSpace", ann="Force the BindLocator to the position of the Controller", al="left", onc=lambda x: self.settings.__setattr__('align_to_control_rots', True), ofc=lambda x: self.settings.__setattr__('align_to_source_rots', True)) cmds.checkBox( value=1, label="AlignTrans CtrSpace", ann="Force the BindLocator to the position of the Controller", al="left", onc=lambda x: self.settings.__setattr__('align_to_control_trans', True), ofc=lambda x: self.settings.__setattr__('align_to_source_trans', True)) cmds.checkBox( value=self.settings.reset_rots, label="Reset Rots Offsets", ann="Reset any Offset during bind, snapping the systems together", al="left", onc=lambda x: self.settings.__setattr__('reset_rots', True), ofc=lambda x: self.settings.__setattr__('reset_rots', False)) cmds.checkBox( value=self.settings.reset_trans, label="Reset Trans Offsets", ann="Reset any Offset during bind, snapping the systems together", al="left", onc=lambda x: self.settings.__setattr__('reset_trans', True), ofc=lambda x: self.settings.__setattr__('reset_trans', False)) cmds.setParent('..') cmds.separator(h=10, style="none") cmds.button( label="BasicBind", al="center", ann= "Select the Joint on the driving Skeleton then the Controller to be driven", c=lambda x: BindNodeBase(cmds.ls(sl=True, l=True)[0], cmds.ls(sl=True, l=True)[1], settings=self.settings).add_binder_node()) cmds.button( label="ComplexBind", al="center", ann= "Select the Joint on the driving Skeleton then the Controller to be driven", c=lambda x: BindNodeTwin(cmds.ls(sl=True, l=True)[0], cmds.ls(sl=True, l=True)[1], settings=self.settings).add_binder_node()) cmds.button( label="AimerBind", al="center", ann= "Select the Joint on the driving Skeleton to AIM at, then the Controller to be driven, finally a node on the driven skeleton to use as UpVector", c=lambda x: BindNodeAim(cmds.ls(sl=True, l=True)[0], cmds.ls(sl=True, l=True)[1], cmds.ls(sl=True, l=True)[2], settings=self.settings).add_binder_node()) cmds.separator(h=15, style="none") cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1, 147), (2, 147)]) cmds.button( label="Add BakeMarker", al="center", ann="Add the BoundCtrl / Bake Marker to the selected nodes", c=lambda x: add_bind_markers(cmds.ls(sl=True, l=True))) cmds.button( label="remove BakeMarker", al="center", ann="Remove the BoundCtrl / Bake Marker from the selected nodes", c=lambda x: removeBindMarker(cmds.ls(sl=True, l=True))) cmds.button( label="Select BindNodes", al="center", ann="Select Top Group Node of the Source Binder", c=lambda x: pm.select(get_bind_nodes(cmds.ls(sl=True, l=True)))) cmds.button(label="Select BoundControls", al="center", ann="Select Top Group Node of the Bound Rig", c=lambda x: pm.select( get_bound_controls(cmds.ls(sl=True, l=True)))) cmds.setParent('..') cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1, 200), (2, 74)], columnSpacing=[(2, 5)]) cmds.button(label="Bake Binder", al="center", ann="Select Top Group Node of the Bound Rig", c=lambda x: bake_binder_data(cmds.ls(sl=True, l=True), self .settings.bake_debug)) cmds.checkBox( value=self.settings.bake_debug, label="Debug View", ann="Keep viewport active to observe the baking process", al="left", onc=lambda x: self.settings.__setattr__('bake_debug', True), ofc=lambda x: self.settings.__setattr__('bake_debug', False)) cmds.setParent('..') cmds.separator(h=10, style="none") cmds.button( label="Link Skeleton Hierarchies - Direct Connect", al="center", ann= "Select Root joints of the source and destination skeletons to be connected - connect via attrs", c=lambda x: bind_skeletons( cmds.ls(sl=True)[0], cmds.ls(sl=True)[1], method='connect')) cmds.button( label="Link Skeleton Hierarchies - Constraints", al="center", ann= "Select Root joints of the source and destination skeletons to be connected - connect via parentConstraints", c=lambda x: bind_skeletons( cmds.ls(sl=True)[0], cmds.ls(sl=True)[1], method='constrain')) cmds.separator(h=10, style="none") cmds.button( label="MakeStabilizer", al="center", ann="Select the nodes you want to extract the motion data from", c=lambda x: make_stabilized_node()) cmds.separator(h=20, style="none") cmds.iconTextButton(style='iconOnly', bgc=(0.7, 0, 0), image1='Rocket9_buttonStrap2.bmp', c=lambda *args: (r9Setup.red9ContactInfo()), h=22, w=200) cmds.showWindow(self.win) cmds.window(self.win, e=True, h=400)
def makeCorrective(items=None, name=None): import cvShapeInverter xformAttrs = [ 't', 'r', 's', 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', ] xformAttrDefaults = [0, 0, 0, 0, 0, 0, 1, 1, 1] duplicates = [] if name == None: result = cmds.promptDialog(title='Create Corrective Shape', message='Enter Corrective Name:', text='positionA', button=['Create', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result != 'Create': return None name = cmds.promptDialog(query=True, text=True) if not items: items = [] for item in pymel.ls(selection=True): inheritedTypes = item.nodeType(inherited=True) if 'transform' in inheritedTypes: if item.getShapes(): items.append(item) elif 'shape' in inheritedTypes: items.append(item.getParent()) for item in items: itemShape = item.getShape() itemPosition = pymel.xform(item, query=True, translation=True, worldSpace=True) itemMatrix = pymel.xform(item, query=True, matrix=True, worldSpace=True) # get the origShape itemOrigShape = getOrigShape(itemShape) # create a duplicate duplicate = pymel.duplicate(item, smartTransform=False)[0] duplicate.rename('%s_%sCorrective' % ( item.nodeName(), name, )) duplicateShape = duplicate.getShape() duplicates.append(duplicate) ## set the duplicate's shape to match the item's orig shape #itemOrigShape.intermediateObject.set(0) #tempBlendShape = pymel.blendShape(itemOrigShape, duplicate)[0] #itemOrigShape.intermediateObject.set(1) #tempBlendShape.w[0].set(1) #tempBlendShape.inputTarget[0].inputTargetGroup[0].inputTargetItem[6000].inputGeomTarget.disconnect() #pymel.delete(duplicate, constructionHistory=True) # unlock translate attrs so the user can move the target for attr in xformAttrs: try: duplicate.attr(attr).set(lock=False) except: pass # create secondary blendshape node if one does not already exist secondaryBlendShape = None for deformer in getDeformers(item): if hasattr(deformer, 'isSecondaryBlendShape'): secondaryBlendShape = deformer break if not secondaryBlendShape: secondaryBlendShape = pymel.blendShape(item)[0] secondaryBlendShape.addAttr('isSecondaryBlendShape', at='bool', defaultValue=True) secondaryBlendShape.isSecondaryBlendShape.set(lock=True) secondaryBlendShape.rename(item.nodeName() + '_secondaryBlendshape') #duplicateOrigShape = getOrigShape(duplicateShape) #duplicateOrigShape.intermediateObject.set(0) #staticBlendShape = pymel.blendShape(item, duplicateOrigShape)[0] #duplicateOrigShape.intermediateObject.set(1) #staticBlendShape.rename(duplicate.nodeName()+'_staticBlendShape') #staticBlendShape.w[0].set(1) #pymel.delete(duplicate, constructionHistory=True) liveBlendShape = pymel.blendShape(item, duplicate)[0] liveBlendShape.rename(duplicate.nodeName() + '_liveBlendShape') liveBlendShape.w[0].set(1) tweakNode = None for deformer in reversed(getDeformers(duplicateShape)): if deformer.nodeType() == 'tweak': tweakNode = deformer break tweakNode.rename(duplicate.nodeName() + '_secondaryTweak') pymel.reorderDeformers(tweakNode, liveBlendShape) #pymel.reorderDeformers(tweakNode, staticBlendShape) # connect the input of the blendshape as a target of the live shape groupParts = secondaryBlendShape.input[0].inputGeometry.inputs()[0] groupParts.outputGeometry >> liveBlendShape.inputTarget[ 0].inputTargetGroup[0].inputTargetItem[6000].inputGeomTarget # backgroundTweak backgroundTweak = pymel.createNode('tweak') backgroundTweak.rename('backgroundTweak') groupParts.outputGeometry >> backgroundTweak.input[0].inputGeometry #groupParts.outputGeometry >> staticBlendShape.inputTarget[0].inputTargetGroup[0].inputTargetItem[6000].inputGeomTarget pymel.blendShape(item, duplicate)[0] index = pymel.blendShape(secondaryBlendShape, query=True, weightCount=True) pymel.blendShape(secondaryBlendShape, edit=True, target=(item, index, duplicate, 1.0)) secondaryBlendShape.w[index].set(1) #backgroundTweak.outputGeometry[0] >> secondaryBlendShape.inputTarget[0].inputTargetGroup[index].inputTargetItem[6000].inputGeomTarget #blendShape = None #for deformer in getDeformers(item): #if deformer.nodeType() == 'blendShape': #blendShape = deformer #break #if blendShape: #index = pymel.blendShape(blendShape, query=True, weightCount=True) #OOOOOOO = "index"; print '%s: ' % OOOOOOO, eval(OOOOOOO), ' ', type(eval(OOOOOOO)) #pymel.blendShape(blendShape, edit=True, target=(item, index, invertedItem, 1.0)) #blendShape.w[index].set(1) #OOOOOOO = "blendShape"; print '%s: ' % OOOOOOO, eval(OOOOOOO), ' ', type(eval(OOOOOOO)) #else: #blendShape = pymel.blendShape(invertedItem, item, frontOfChain=True,)[0] #blendShape.rename(item.nodeName()+'_blendShape') #blendShape.w[0].set(1) #print 'NEW' #blendShapeA.w[0].set(1) #ka_shapes.shapeParent(invertedItem, duplicate) #itemBlendShape = None #for deformer in getDeformers(item): #if defomer.nodeType() == '': #pass #pymel.blendShape(bs, query=True, weightCount=True) #bs[0].w[0].set(2) #OOOOOOO = "invertedItem"; print '%s: ' % OOOOOOO, eval(OOOOOOO), ' ', type(eval(OOOOOOO)) #staticBlendShape.inputTarget[0].inputTargetGroup[0].inputTargetItem[6000].inputGeomTarget.disconnect() pymel.xform( duplicate, translation=[ itemPosition[0] + 5, itemPosition[1], itemPosition[2] ], worldSpace=True, ) pymel.select(duplicates)
def makeCorrective2(items=None, name=None): import cvShapeInverter xformAttrs = [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', ] xformAttrDefaults = [0, 0, 0, 0, 0, 0, 1, 1, 1] duplicates = [] if name == None: result = cmds.promptDialog(title='Create Corrective Shape', message='Enter Corrective Name:', text='positionA', button=['Create', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result != 'Create': return None name = cmds.promptDialog(query=True, text=True) if not items: items = [] for item in pymel.ls(selection=True): inheritedTypes = item.nodeType(inherited=True) if 'transform' in inheritedTypes: if item.getShapes(): items.append(item) elif 'shape' in inheritedTypes: items.append(item.getParent()) for item in items: itemPosition = pymel.xform(item, query=True, translation=True, worldSpace=True) duplicate = pymel.duplicate(item)[0] duplicate.rename(name + 'Corrective') duplicateShape = duplicate.getShape() duplicates.append(duplicate) for attr in xformAttrs: try: duplicate.attr(attr).set(lock=False) except: pass pymel.xform( duplicate, translation=[ itemPosition[0] + 5, itemPosition[1], itemPosition[2] ], worldSpace=True, ) pymel.select(item, duplicate) invertedItem = cvShapeInverter.invert() invertedItem = pymel.ls(invertedItem)[0] invertedItem.setParent(duplicate) invertedItemShape = invertedItem.getShape() invertedItem.v.set(0) for i, attr in enumerate(xformAttrs): invertedItem.attr(attr).set(xformAttrDefaults[i]) blendShape = None for deformer in getDeformers(item): if deformer.nodeType() == 'blendShape': blendShape = deformer break if blendShape: index = pymel.blendShape(blendShape, query=True, weightCount=True) OOOOOOO = "index" print '%s: ' % OOOOOOO, eval(OOOOOOO), ' ', type(eval(OOOOOOO)) pymel.blendShape(blendShape, edit=True, target=(item, index, invertedItem, 1.0)) blendShape.w[index].set(1) OOOOOOO = "blendShape" print '%s: ' % OOOOOOO, eval(OOOOOOO), ' ', type(eval(OOOOOOO)) else: blendShape = pymel.blendShape( invertedItem, item, frontOfChain=True, )[0] blendShape.rename(item.nodeName() + '_blendShape') blendShape.w[0].set(1) print 'NEW' #blendShapeA.w[0].set(1) #ka_shapes.shapeParent(invertedItem, duplicate) #itemBlendShape = None #for deformer in getDeformers(item): #if defomer.nodeType() == '': #pass #pymel.blendShape(bs, query=True, weightCount=True) #bs[0].w[0].set(2) OOOOOOO = "invertedItem" print '%s: ' % OOOOOOO, eval(OOOOOOO), ' ', type(eval(OOOOOOO))
def check_external_files(self): """checks for external files in the current scene and raises RuntimeError if there are local files in the current scene, used as: - File Textures - Mentalray Textures - ImagePlanes - IBL nodes - References """ def is_in_repo(path): """checks if the given path is in repository :param path: the path which wanted to be checked :return: True or False """ assert isinstance(path, (str, unicode)) path = os.path.expandvars(path) return path.startswith(os.environ[conf.repository_env_key].replace( '\\', '/')) external_nodes = [] # check for file textures for file_texture in pm.ls(type=pm.nt.File): path = file_texture.attr('fileTextureName').get() logger.debug('checking path: %s' % path) if path is not None \ and os.path.isabs(path) \ and not is_in_repo(path): logger.debug('is not in repo: %s' % path) external_nodes.append(file_texture) # check for mentalray textures try: for mr_texture in pm.ls(type=pm.nt.MentalrayTexture): path = mr_texture.attr('fileTextureName').get() logger.debug("path of %s: %s" % (mr_texture, path)) if path is not None \ and os.path.isabs(path) \ and not is_in_repo(path): external_nodes.append(mr_texture) except AttributeError: # mental ray not loaded pass # check for ImagePlanes for image_plane in pm.ls(type=pm.nt.ImagePlane): path = image_plane.attr('imageName').get() if path is not None \ and os.path.isabs(path) \ and not is_in_repo(path): external_nodes.append(image_plane) # check for IBL nodes try: for ibl in pm.ls(type=pm.nt.MentalrayIblShape): path = ibl.attr('texture').get() if path is not None \ and os.path.isabs(path) \ and not is_in_repo(path): external_nodes.append(ibl) except AttributeError: # mental ray not loaded pass if external_nodes: pm.select(external_nodes) raise RuntimeError( 'There are external references in your scene!!!\n\n' 'The problematic nodes are:\n\n' + "\n\t".join(map(lambda x: x.name(), external_nodes)) + '\n\nThese nodes are added in to your selection list,\n' 'Please correct them!\n\n' 'YOUR FILE IS NOT GOING TO BE SAVED!!!')
def selectAll(self): select(core.findNode.allCards())
def cardIk(card): #ctrl = mel.eval( 'curve -d 1 -p -0.5 1 -0.866026 -p -0.5 1 0.866025 -p 1 1 0 -p -0.5 1 -0.866026 -p 0 0 0 -p -0.5 -1 -0.866026 -p -0.5 -1 0.866025 -p 0 0 0 -p -0.5 1 0.866025 -p 1 1 0 -p 0 0 0 -p 1 -1 0 -p -0.5 -1 -0.866026 -p -0.5 -1 0.866025 -p 1 -1 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 ;' ) ctrl = tempWidget() ctrl.rename(card.name() + "_target") upCtrl = duplicate(ctrl)[0] upCtrl.rename(card.name() + "_up") aim = spaceLocator() aim.setParent(ctrl) aim.t.set(0, 0, 0) hide(aim) up = spaceLocator() up.setParent(upCtrl) hide(up) base = spaceLocator() base.rename('cardIkBase') hide(base) pointConstraint(card, base) pdil.dagObj.moveTo(ctrl, card.joints[-1]) #pdil.dagObj.moveTo( upCtrl, card.vtx[1] ) pdil.dagObj.moveTo(upCtrl, card.cv[1][0]) aimConstraint(aim, card, wut='object', wuo=up, aim=[0, -1, 0], u=[0, 0, -1]) dist = distanceDimension(base, aim) dist.getParent().setParent(ctrl) hide(dist) pdil.math.divide(dist.distance, dist.distance.get() / card.sy.get()) >> card.sy follower = spaceLocator() follower.rename('cardIkFollower') follower.setParent(card) follower.t.set(0, 0, 0) hide(follower) pointConstraint(up, follower, skip=['x', 'z']) sideDist = distanceDimension(follower, up) sideDist.getParent().setParent(ctrl) hide(sideDist) pdil.math.divide(sideDist.distance, sideDist.distance.get() / card.sz.get()) >> card.sz # Orient controls with the card so moving in local space initially preserves orientation. upCtrl.setRotation(card.getRotation(space='world'), space='world') ctrl.setRotation(card.getRotation(space='world'), space='world') distBetweenCtrls = (ctrl.getTranslation(space='world') - upCtrl.getTranslation(space='world')).length() if distBetweenCtrls < 8.0: upCtrl.s.set([distBetweenCtrls / 8.0] * 3) ctrl.s.set([distBetweenCtrls / 8.0] * 3) select(ctrl)
def cardListerSelection(self): if self.ui.cardLister.uiActive: cards = [item.card for item in self.ui.cardLister.selectedItems()] select(cards)
def flip_pose( self, mirrorMode=True, *args ): try: selectedItem = pm.radioCollection( self.mirrorModeRC, q=True, select=True ) mirrorModeInUI = (pm.radioButton( selectedItem, q=True, label=True )).lower() except: pass objs = pm.ls( sl=True ) flippedObjs = [] # list of objects already flipped for obj in objs: mirrorMode = mirrorModeInUI mirrorModeAttrExists = pm.attributeQuery( 'mirrorMode', node=obj, exists=True ) if mirrorModeAttrExists: mirrorMode = obj.mirrorMode.get() name = self.findMirror( obj ) # find mirrored object's name if name in flippedObjs: # prevent object to get flipped twice continue flippedObjs.append( obj ) # get object's attributes allAttrs = pm.listAttr( obj, keyable=True, unlocked=True ) userAttrs = pm.listAttr(obj, ud=True, unlocked=True) if not name: # if mirror not found go to next object # 1. create 3 locators representing Position, aimVector and upVector pos = self.createChildLoc( obj ) aim = self.createChildLoc( obj ) upv = self.createChildLoc( obj ) # 2. get the flip plane from our control object, default is YZ. place aim and up vectors accordingly try: flipPlane = obj.mirrorPlane.get() except: flipPlane = 'YZ' if flipPlane == 'YZ': aim.translateZ.set(1) upv.translateY.set(1) elif flipPlane == 'XZ': aim.translateX.set(1) upv.translateZ.set(1) elif flipPlane == 'XY': aim.translateX.set(1) upv.translateY.set(1) # 3. parent locators under control's parent. They should be in the same group as our control object we want to flip try: controlParent = obj.getParent() except: controlParent = None if controlParent: pm.parent( pos, controlParent ) pm.parent( aim, controlParent ) pm.parent( upv, controlParent ) # 4. group all locators and scale the group according to our flip plane grp = pm.group( pos, aim, upv ) pm.xform( grp, os=True, piv=(0,0,0) ) if flipPlane == 'YZ': grp.scaleX.set(-1) elif flipPlane == 'XZ': grp.scaleY.set(-1) elif flipPlane == 'XY': grp.scaleZ.set(-1) # 5. create point and aim constraints to achieve the pose on a null object and apply the values to our control result = pm.group( empty=True ) result.rotateOrder.set( obj.rotateOrder.get() ) if controlParent: pm.parent( result, controlParent ) pm.pointConstraint( pos, result ) if flipPlane == 'YZ': pm.aimConstraint( aim, result, aimVector=[0,0,1], upVector=[0,1,0], worldUpType="object", worldUpObject=upv ) elif flipPlane == 'XZ': pm.aimConstraint( aim, result, aimVector=[1,0,0], upVector=[0,0,1], worldUpType="object", worldUpObject=upv ) elif flipPlane == 'XY': pm.aimConstraint( aim, result, aimVector=[1,0,0], upVector=[0,1,0], worldUpType="object", worldUpObject=upv ) result.scale.set( obj.scale.get() ) # get object's attributes allAttrs = pm.listAttr( obj, keyable=True, unlocked=True ) userAttrs = pm.listAttr(obj, ud=True, unlocked=True) for attr in allAttrs: try: obj.attr(attr).set( result.attr(attr).get() ) except: continue # 6. delete extra nodes pm.delete( grp, result ) continue for attr in allAttrs: if pm.connectionInfo( pm.PyNode(name).attr(attr), isDestination=True ): pass if attr not in userAttrs:# match main attributes try: otherValue = pm.PyNode(name).attr(attr).get() value = obj.attr(attr).get() if attr == 'visibility': # no need to mirror visibility pass elif attr=='translateX': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='translateY': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='translateZ': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='rotateX': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='rotateY': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif attr=='rotateZ': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) else: pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) except: pm.error('ehm_tools...mirrorPose: Flip failed on main attributes!') else:# match user defined attributes try: otherValue = pm.PyNode(name).attr(attr).get() value = obj.attr(attr).get() pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) except: pm.error('ehm_tools...mirrorPose: Flip failed on user defined attributes!') pm.select( objs )
def createOffsetForSelected(): """ Create an offset group for the selected nodes """ pm.select([createOffsetGroup(s) for s in pm.selected(type='transform')])
def createObjID(*agrs): checkArnold() sel = pm.ls(sl = 1) #select jbject for object IDs index = checkObjID() for i in iterBy(sel,3): #Create AOV and mask color to RED setupObjID(index) pm.select(i[0]) pm.runtime.SelectHierarchy() selShapes = pm.ls(sl = 1, shapes = True) pm.select(selShapes) msk = addColor('%02d' %index) for e in selShapes: #set mask color to R attr = str(e) + '.mtoa_constant_maskOBJ_' + str('%02d' % index) pm.setAttr(attr, R) pm.select(i[1]) pm.runtime.SelectHierarchy() selShapes = pm.ls(sl = 1, shapes = True) pm.select(selShapes) msk = addColor('%02d' %index) for e in selShapes: #set mask color to G attr = str(e) + '.mtoa_constant_maskOBJ_' + str('%02d' % index) pm.setAttr(attr, G) pm.select(i[2]) pm.runtime.SelectHierarchy() selShapes = pm.ls(sl = 1, shapes = True) pm.select(selShapes) msk = addColor('%02d' %index) for e in selShapes: #set mask color to B attr = str(e) + '.mtoa_constant_maskOBJ_' + str('%02d' % index) pm.setAttr(attr, B) index += 1
def editJointPivotExit(self, objects): pm.select(objects, r=True) # self.freezeRotation() pm.selectMode(o=True)
def splitSidesAPI(targetObj=None, sourceObj=None, baseName=None, falloff=0.2): ''' Based on script by Jeff Rosenthal Modified by Leonardo Cadaval 03/12/2018 Creates left and ride side variations of a blendshape along the X axis Select your source face, then select the blendshape you created run the script! :param targetObj: :param sourceObj: :param falloff: :return: ''' # look at number of verticies pm.select(sourceObj) tgtVertex = getObjVertex(targetObj.name()) srcVertex = getObjVertex(sourceObj.name()) bBox = getBBox(targetObj.name()) rgtX = bBox.max.x # duplicate face twice (one left, one right) if baseName: tgtName = baseName else: tgtName = targetObj targetObj_Lft = pm.duplicate(targetObj, n='R_' + tgtName)[0] pm.move(targetObj_Lft, rgtX * -2.1, 0, 0, r=1) targetObj_Rgt = pm.duplicate(targetObj, n='L_' + tgtName)[0] pm.move(targetObj_Rgt, rgtX * 2.1, 0, 0, r=1) side = 1 # on each object for target in ([targetObj_Lft, targetObj_Rgt]): side *= -1 newPoint = om2.MPoint() newPntArray = om2.MPointArray() for id in range(len(srcVertex)): # get vert positions # find difference differencePos = (srcVertex[id][0] - tgtVertex[id][0], srcVertex[id][1] - tgtVertex[id][1], srcVertex[id][2] - tgtVertex[id][2]) # get falloff amount from side of object falloffDist = getValue(srcVertex[id][0], falloff * side) # move vert difference * falloff amount newPntArray.append( om2.MPoint(tgtVertex[id][0] + (differencePos[0] * falloffDist), tgtVertex[id][1] + (differencePos[1] * falloffDist), tgtVertex[id][2] + (differencePos[2] * falloffDist))) setObjVertex(target.name(), newPntArray) return [targetObj_Lft, targetObj_Rgt]
def cardIk(card): #ctrl = mel.eval( 'curve -d 1 -p -0.5 1 -0.866026 -p -0.5 1 0.866025 -p 1 1 0 -p -0.5 1 -0.866026 -p 0 0 0 -p -0.5 -1 -0.866026 -p -0.5 -1 0.866025 -p 0 0 0 -p -0.5 1 0.866025 -p 1 1 0 -p 0 0 0 -p 1 -1 0 -p -0.5 -1 -0.866026 -p -0.5 -1 0.866025 -p 1 -1 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 ;' ) ctrl = PyNode( mel.eval( 'curve -d 1 -p 0 4 0 -p -2.828427 2.828427 -2.47269e-007 -p -4 0 -3.49691e-007 -p -2.828427 -2.828427 -2.47269e-007 -p 0 -4 0 -p 2.828427 -2.828427 0 -p 4 0 0 -p 2.828427 2.828427 0 -p 0 4 0 -p -1.23634e-007 2.828427 2.828427 -p -1.74846e-007 0 4 -p -1.23634e-007 -2.828427 2.828427 -p 0 -4 0 -p 3.70903e-007 -2.828427 -2.828427 -p 5.24537e-007 0 -4 -p 3.70903e-007 2.828427 -2.828427 -p 0 4 0 -p 0 0 0 -p 0 -4 0 -p 0 0 0 -p -4 0 0 -p 4 0 0 -p 0 0 -4 -p 0 0 4 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 18 -k 19 -k 20 -k 21 -k 22 -k 23 ;' )) ctrl.rename(card.name() + "_target") upCtrl = duplicate(ctrl)[0] upCtrl.rename(card.name() + "_up") aim = spaceLocator() aim.setParent(ctrl) aim.t.set(0, 0, 0) hide(aim) up = spaceLocator() up.setParent(upCtrl) hide(up) base = spaceLocator() base.rename('cardIkBase') hide(base) pointConstraint(card, base) util.moveTo(ctrl, card.joints[-1]) util.moveTo(upCtrl, card.vtx[1]) aimConstraint(aim, card, wut='object', wuo=up, aim=[0, -1, 0], u=[0, 0, -1]) dist = distanceDimension(base, aim) dist.getParent().setParent(ctrl) hide(dist) core.math.divide(dist.distance, dist.distance.get() / card.sy.get()) >> card.sy follower = spaceLocator() follower.rename('cardIkFollower') follower.setParent(card) follower.t.set(0, 0, 0) hide(follower) pointConstraint(up, follower, skip=['x', 'z']) sideDist = distanceDimension(follower, up) sideDist.getParent().setParent(ctrl) hide(sideDist) core.math.divide(sideDist.distance, sideDist.distance.get() / card.sz.get()) >> card.sz # Orient controls with the card so moving in local space initially preserves orientation. upCtrl.setRotation(card.getRotation(space='world'), space='world') ctrl.setRotation(card.getRotation(space='world'), space='world') distBetweenCtrls = (ctrl.getTranslation(space='world') - upCtrl.getTranslation(space='world')).length() if distBetweenCtrls < 8.0: upCtrl.s.set([distBetweenCtrls / 8.0] * 3) ctrl.s.set([distBetweenCtrls / 8.0] * 3) select(ctrl)
def extendPipe(jointLength=1): defaultLength = 3.0 currJnt = '' name = '' root = '' newJnts = [] for sel in pm.selected(): sel.select() # for now, there's no branching, so we find the deepest joint try: currJnt = sel name = currJnt.split('_')[0] root = pm.nt.Joint('%s_Jnt0' % name) except: raise "select an object on the pipe that you want to extend" # naming #---------- num = int(currJnt.extractNum()) try: twoPrev = int(currJnt.getParent().getParent().extractNum()) except: twoPrev = num - 2 try: prev = int(currJnt.getParent().extractNum()) except: prev = num - 1 curr = num new = int(currJnt.nextUniqueName().extractNum()) print "extending from", currJnt, new branchNum = len(currJnt.getChildren()) #print '%s has %s children' % (currJnt, branchNum) if branchNum: print "new segment is a branching joint" currJnt.addAttr('pipeLengthInBtwn%s' % branchNum, min=0) #currJnt.attr( 'pipeLengthInBtwn%s' % branchNum ).showInChannelBox(1) #print twoPrev, prev, curr, new rigGrp = '%s_RigGrp' % name geoGrp = '%s_GeoGrp' % name # new skeletal joint #--------------------- if new > 1: prevJnt = pm.nt.Joint('%s_Jnt%s' % (name, prev)) pos = 2 * currJnt.getTranslation(ws=1) - prevJnt.getTranslation( ws=1) else: prevJnt = None pos = currJnt.getTranslation(ws=1) + [0, defaultLength, 0] newJnt = pm.joint(p=pos, n='%s_Jnt%s' % (name, new)) # re-orient the last created joint, which is considered our current joint pm.joint(currJnt, e=1, zeroScaleOrient=1, secondaryAxisOrient='yup', orientJoint='xyz') # pymel method: NEEDS FIXING #currJnt.setZeroScaleOrient(1) #currJnt.setSecondaryAxisOrient('yup') # Flag secondaryAxisOrient can only be used in conjunction with orientJoint flag. #currJnt.setOrientJoint('xyz') newJnt.scale.lock() newJnt.addAttr('pipeLength', defaultValue=jointLength, min=.0001) newJnt.pipeLength.showInChannelBox(1) newJnt.addAttr('pipeLengthInBtwn0', min=0) #newJnt.attr( 'pipeLengthInBtwn0' ).showInChannelBox(1) newJnt.addAttr('pipeLeadIn', dv=0, min=0) newJnt.pipeLeadIn.showInChannelBox(1) newJnt.addAttr('radiusMultiplier', dv=1, min=0) newJnt.radiusMultiplier.showInChannelBox(1) newJnt.displayHandle = 1 newJnt.radius.showInChannelBox(0) # bend hierarchy #----------------- trans = pm.group(empty=1, n='%s_Elbow%s' % (name, new)) trans.rotateOrder = 1 pm.aimConstraint(currJnt, trans, aimVector=[0, -1, 0], upVector=[-1, 0, 0]) pm.pointConstraint(newJnt, trans) trans.setParent(rigGrp) # keep the end joint oriented along the joint chain so that it can be slid back # and forth to change the length of the current pipe segment pm.delete(pm.orientConstraint(trans, newJnt)) # Main Pipe #------------ pipe, pipeHist = pm.polyCylinder(height=1, radius=1, name='%s_Geo%s' % (name, new)) pipeHist = pipeHist.rename('%s_GeoHist%s' % (name, new)) pipe.setPivots([0, -.5, 0], r=1) root.globalPipeRadius >> pipe.sx root.globalPipeRadius >> pipe.sz pipeHist.createUVs = 3 # normalize and preserve aspect ratio root.subdivisionsAxis >> pipeHist.subdivisionsAxis # Pipe Connectors #------------- pipeConn1, pipeConnHist1 = pm.polyCylinder(height=.1, radius=1, name='%s_Connector1AGeo%s' % (name, new)) pipeConnHist1 = pipeConnHist1.rename('%s_Connector1AHist%s' % (name, new)) pipeConn1.setPivots([0, -.05, 0], r=1) pipeConn1.setParent(pipe, relative=True) pipeConn1.rotate.lock() root.subdivisionsAxis >> pipeConnHist1.subdivisionsAxis pipeConn2, pipeConnHist2 = pm.polyCylinder(height=.1, radius=1, name='%s_Connector2AGeo%s' % (name, new)) pipeConnHist2 = pipeConnHist2.rename('%s_Connector2AHist%s' % (name, new)) pipeConn2.setPivots([0, .05, 0], r=1) pipeConn2.setParent(pipe, relative=True) pipeConn2.rotate.lock() root.subdivisionsAxis >> pipeConnHist2.subdivisionsAxis pipeConn1, pipeConnHist1 = pm.polyCylinder(height=.1, radius=1, name='%s_Connector1BGeo%s' % (name, new)) pipeConnHist1 = pipeConnHist1.rename('%s_Connector1BHist%s' % (name, new)) pipeConn1.setPivots([0, -.05, 0], r=1) pipeConn1.setParent(pipe, relative=True) pipeConn1.rotate.lock() pipeConn1.visibility = 0 root.subdivisionsAxis >> pipeConnHist1.subdivisionsAxis pipeConn2, pipeConnHist2 = pm.polyCylinder(height=.1, radius=1, name='%s_Connector2BGeo%s' % (name, new)) pipeConnHist2 = pipeConnHist2.rename('%s_Connector2BHist%s' % (name, new)) pipeConn2.setPivots([0, .05, 0], r=1) pipeConn2.setParent(pipe, relative=True) pipeConn2.rotate.lock() pipeConn2.visibility = 0 root.subdivisionsAxis >> pipeConnHist2.subdivisionsAxis pipe.setParent(geoGrp) #constraints pm.pointConstraint(currJnt, pipe) aim = pm.aimConstraint(newJnt, pipe) aim.offsetZ = -90 # convert the previous pipe joint into a bendy joint if new > 1: currElbow = pm.PyNode('%s_Elbow%s' % (name, curr)) pipeLoc = pm.spaceLocator(n='%s_PipeDummy%s' % (name, new)) pipeLoc.hide() tweak = pm.group(n='%s_ElbowTweak%s' % (name, new)) tweak.rotateOrder = 2 #tweak.translate = currElbow.translate.get() tweak.setParent(currElbow, r=1) pm.aimConstraint(prevJnt, tweak, aimVector=[1, 0, 0], upVector=[0, -1, 0], skip=['z', 'x']) # Pipe Joint #------------ pipeJnt, pipeJntHist = pm.polyCylinder(height=1, radius=1, name='%s_JntGeo%s' % (name, new), subdivisionsAxis=20, subdivisionsHeight=30) pipeJnt.setParent(geoGrp) pipeJnt.sy = jointLength pipeJnt.visibility = 0 pipeJntHist = pipeJntHist.rename('%s_JntGeoHist%s' % (name, new)) pipeJntHist.createUVs = 3 # normalize and preserve aspect ratio root.subdivisionsAxis >> pipeJntHist.subdivisionsAxis root.subdivisionsJoint >> pipeJntHist.subdivisionsHeight # constraints pm.parentConstraint(pipeLoc, pipeJnt) pipeJnt.translate.lock() pipeJnt.rotate.lock() #pipeJnt.scale.lock() aim = pm.PyNode('%s_Elbow%s_aimConstraint1' % (name, curr)) aim.setWorldUpType(2) aim.setWorldUpObject(newJnt) bend, bendHandle = pm.nonLinear('%s_JntGeo%s' % (name, new), type='bend') bendHandle = pm.nt.Transform(bendHandle).rename('%s_BendHandle%s' % (name, new)) bendHandle.sx = .5 bendHandle.hide() bend.rename('%s_Bend%s' % (name, new)) pm.parentConstraint('%s_ElbowTweak%s' % (name, new), bendHandle) aim = '%s_ElbowTweak%s_aimConstraint1' % (name, new) #aim.worldUpType.set( 1 ) pm.aimConstraint(aim, e=1, worldUpType='object', worldUpObject=newJnt) bendHandle.setParent(rigGrp) expr = """ float $v1[]; $v1[0] = %(name)s_Elbow%(twoPrev)s.translateX - %(name)s_Elbow%(prev)s.translateX; $v1[1] = %(name)s_Elbow%(twoPrev)s.translateY - %(name)s_Elbow%(prev)s.translateY; $v1[2] = %(name)s_Elbow%(twoPrev)s.translateZ - %(name)s_Elbow%(prev)s.translateZ; float $v2[]; $v2[0] = %(name)s_Elbow%(curr)s.translateX - %(name)s_Elbow%(prev)s.translateX; $v2[1] = %(name)s_Elbow%(curr)s.translateY - %(name)s_Elbow%(prev)s.translateY; $v2[2] = %(name)s_Elbow%(curr)s.translateZ - %(name)s_Elbow%(prev)s.translateZ; float $mag = sqrt ( $v2[0]*$v2[0] + $v2[1]*$v2[1] + $v2[2]*$v2[2] ); float $angleData[] = `angleBetween -v1 $v1[0] $v1[1] $v1[2] -v2 $v2[0] $v2[1] $v2[2] `; float $angle = $angleData[3]; if ( !equivalentTol($angle,180.0, 0.1) ) { float $jointDeg = 180 - $angle; float $jointRad = -1 * deg_to_rad( $jointDeg ); %(name)s_Bend%(curr)s.curvature = $jointRad/2; %(name)s_ElbowTweak%(curr)s.rotateZ = $jointDeg/2; %(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s = %(name)s_Jnt%(prev)s.pipeLength; float $pipeLength = %(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s; float $centerAngleRad = deg_to_rad(90 -$angle/2); float $delta = 0; float $pipeLengthRatio = 1; if ($centerAngleRad > 0.0) { float $radius = .5*%(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s/ $centerAngleRad; $delta = $radius - ($radius * cos( $centerAngleRad )); $pipeLengthRatio = .5 * $pipeLength / ( $radius * sin( $centerAngleRad ) ); $pipeLength *= $pipeLengthRatio; } %(name)s_PipeDummy%(curr)s.translateX = -1*$delta; %(name)s_BendHandle%(curr)s.scaleX = .5*%(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s; %(name)s_BendHandle%(curr)s.scaleY = %(name)s_BendHandle%(curr)s.scaleX; %(name)s_BendHandle%(curr)s.scaleZ = %(name)s_BendHandle%(curr)s.scaleX; %(name)s_JntGeo%(curr)s.scaleY = $pipeLength * (1.0+%(name)s_Jnt%(curr)s.pipeLeadIn); %(name)s_JntGeo%(curr)s.scaleX = %(name)s_Jnt0.globalPipeRadius + %(name)s_Jnt0.globalJointRadius; %(name)s_JntGeo%(curr)s.scaleZ = %(name)s_JntGeo%(curr)s.scaleX; %(name)s_JntGeo%(curr)s.visibility = 1; %(name)s_Connector1BGeo%(curr)s.visibility=1; %(name)s_Connector2BGeo%(curr)s.visibility=1; } else { %(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s = 0; %(name)s_JntGeo%(curr)s.scaleY = 0; %(name)s_JntGeo%(curr)s.visibility = 0; %(name)s_Connector1BGeo%(curr)s.visibility=0; %(name)s_Connector2BGeo%(curr)s.visibility=0; } %(name)s_Connector1AGeo%(curr)s.scaleY = %(name)s_Jnt0.globalConnectorThickness * (1/%(name)s_Geo%(curr)s.scaleY); %(name)s_Connector2AGeo%(curr)s.scaleY = %(name)s_Connector1AGeo%(curr)s.scaleY; %(name)s_Connector1AGeo%(curr)s.translateY = -.5 + %(name)s_Connector1AHist%(curr)s.height/2 + .1*%(name)s_Jnt0.globalConnectorOffset; %(name)s_Connector2AGeo%(curr)s.translateY = 0.5 - %(name)s_Connector1AHist%(curr)s.height/2 - .1*%(name)s_Jnt0.globalConnectorOffset; %(name)s_Connector1AGeo%(curr)s.scaleX = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector1AGeo%(curr)s.scaleZ = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector2AGeo%(curr)s.scaleX = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector2AGeo%(curr)s.scaleZ = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector1BGeo%(curr)s.scaleY = %(name)s_Jnt0.globalConnectorThickness * (1/%(name)s_Geo%(curr)s.scaleY); %(name)s_Connector2BGeo%(curr)s.scaleY = %(name)s_Connector1BGeo%(curr)s.scaleY; %(name)s_Connector1BGeo%(curr)s.translateY = -.5 + %(name)s_Connector1BHist%(curr)s.height/2 - .1*%(name)s_Jnt0.globalConnectorOffset - .1*%(name)s_Connector1BGeo%(curr)s.scaleY; %(name)s_Connector2BGeo%(curr)s.translateY = 0.5 - %(name)s_Connector1BHist%(curr)s.height/2 + .1*%(name)s_Jnt0.globalConnectorOffset + .1*%(name)s_Connector1BGeo%(curr)s.scaleY; %(name)s_Connector1BGeo%(curr)s.scaleX = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector1BGeo%(curr)s.scaleZ = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector2BGeo%(curr)s.scaleX = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector2BGeo%(curr)s.scaleZ = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Geo%(curr)s.scaleY = $mag - .5*%(name)s_Jnt%(curr)s.pipeLengthInBtwn0 - .5*%(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s; normalize($v2); %(name)s_Geo%(curr)s_pointConstraint1.offsetX = .5*%(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s * $v2[0]; %(name)s_Geo%(curr)s_pointConstraint1.offsetY = .5*%(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s * $v2[1]; %(name)s_Geo%(curr)s_pointConstraint1.offsetZ = .5*%(name)s_Jnt%(prev)s.pipeLengthInBtwn%(branch)s * $v2[2]; """ % { 'twoPrev': prev, 'prev': curr, 'curr': new, 'new': new + 1, 'name': name, 'branch': branchNum } #print expr print 'editing %s_PipeExpr%s' % (name, new) #expression( '%s_PipeExpr%s' % (name, curr), e=1, s=expr, ae=1 ) pm.expression(s=expr, ae=1, n='%s_PipeExpr%s' % (name, new)) # special case for first joint else: expr = """ float $x = %(newJnt)s.tx; float $y = %(newJnt)s.ty; float $z = %(newJnt)s.tz; float $mag = sqrt ( $x*$x + $y*$y + $z*$z ); %(name)s_Geo%(curr)s.sy = $mag - .5*%(newJnt)s.pipeLengthInBtwn0; %(name)s_Connector1AGeo%(curr)s.scaleY = %(name)s_Jnt0.globalConnectorThickness * 1/%(name)s_Geo%(curr)s.scaleY; %(name)s_Connector2AGeo%(curr)s.scaleY = %(name)s_Connector1AGeo%(curr)s.scaleY; %(name)s_Connector1AGeo%(curr)s.translateY = -.5 + %(name)s_Connector1AHist%(curr)s.height/2 + .1*%(name)s_Jnt0.globalConnectorOffset; %(name)s_Connector2AGeo%(curr)s.translateY = 0.5 - %(name)s_Connector1AHist%(curr)s.height/2 - .1*%(name)s_Jnt0.globalConnectorOffset; %(name)s_Connector1AGeo%(curr)s.scaleX = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector1AGeo%(curr)s.scaleZ = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector2AGeo%(curr)s.scaleX = 1 + %(name)s_Jnt0.globalConnectorRadius; %(name)s_Connector2AGeo%(curr)s.scaleZ = 1 + %(name)s_Jnt0.globalConnectorRadius; """ % { 'newJnt': newJnt, 'curr': new, 'name': name } print 'creating %s_PipeExpr1' % (name) pm.expression(s=expr, ae=1, n='%s_PipeExpr1' % (name)) ''' expr = """ %(pipeJnt)s.scaleX = %(root)s.globalPipeRadius + %(root)s.globalJointRadius; %(pipeJnt)s.scaleZ = %(pipeJnt)s.scaleX; """ % { 'pipeJnt': pipeJnt, 'root' : '%s_Jnt0' % (name) } print 'creating %s_PipeExpr%s' % (name, new) expression( s=expr, ae=1, n = '%s_PipeExpr%s' % (name, new)) ''' pipe.translate.lock() pipe.rotate.lock() #pipe.scale.lock() newJnts.append(newJnt) pm.select(newJnts)
def fit_view(): logger.debug("Fit View") pmc.select(clear=True) pmc.viewFit(all=True) return True
def addTwistJnts(numSegments, joints=None, name='C_split##_skinJnt'): ''' Args: numSegments: number of segments joints: the two joints in an array ['start_jnt', 'end_jnt'] name: the name, ## will be replaced with 01, 02 ... Returns: the list of new joints ['C_split01_jnt', ...] ''' if numSegments < 1: pm.error("The number of segments has to be greater than 0.. ") # for all selected joints joint = None twistJnts = [] if joints == None: joints = pm.ls(sl=1, type='joint') for joint in joints: prevJoint = joint child = pm.listRelatives(joint, children=1, type='joint') if child == []: print("Joint: " + str(joint) + " has no children joints.\n") continue else: print("Joint: " + str(joint) + " has children joints.\n") child = child[0] # axis radius = pm.getAttr("%s.radius" % joint) axis = getJointAxis(child) # make sure the rotation order on $joint is correct. rotOrderIndex = int(pm.getAttr("%s.rotateOrder" % joint)) # calculate spacing attr = ("t" + axis) childT = pm.getAttr("%s.%s" % (child, attr)) print 'childT is %s' % childT space = childT / numSegments # create a series of locators along the joint based on the number of segments. locators = [] for x in range(0, (numSegments - 1)): # align locator to joint locator = pm.spaceLocator() locators.append(locator) pm.parent(locator, joint) pm.setAttr("%s.t" % locator, (0, 0, 0)) # offset pm.setAttr("%s.%s" % (locator, attr), (space * (x + 1))) # insert a joint newJoint = pm.joint(n=name.replace("##", '%02d' % x)) snap(locator, newJoint) pm.parent(newJoint, joint) # pm.makeIdentity(newJoint,) twistJnts.append(newJoint) # get the position of the locator position = pm.xform(locator, q=1, rp=1, ws=1) # move the joint there pm.move(position, ws=1, pcp=1) pm.setAttr("%s.radius" % newJoint, radius) pm.setAttr("%s.rotateOrder" % newJoint, rotOrderIndex) prevJoint = newJoint pm.delete(locator) pm.select(joint) # mo_stringUtils.renameHierarchy() return twistJnts
def startPipe(basename='pipe', pipeRadius=0.2, jointRadius=0.02, subdivAxis=16, subdivJoint=8, jointLength=.8, connectorRadius=.1, connectorThickness=.2, connectorOffset=.001): print basename i = 1 name = basename + str(i) while pm.ls(name + '_Jnt0'): i += 1 name = basename + str(i) try: startPos = pm.selected()[0].getTranslation(ws=1) except: startPos = [0, 0, 0] pm.select(cl=1) rigGrp = pm.group(empty=True, n='%s_RigGrp' % name) geoGrp = pm.group(empty=True, n='%s_GeoGrp' % name) root = pm.joint(name=name + '_Jnt0') trans = pm.group(empty=True, n='%s_Elbow0' % name) pm.pointConstraint(root, trans) root.scale.lock() root.addAttr('globalPipeRadius', defaultValue=pipeRadius, min=.0001) root.globalPipeRadius.showInChannelBox(1) root.addAttr('globalJointRadius', defaultValue=jointRadius) root.globalJointRadius.showInChannelBox(1) root.addAttr('subdivisionsAxis', at='short', defaultValue=subdivAxis, min=4) root.subdivisionsAxis.showInChannelBox(1) root.addAttr('subdivisionsJoint', at='short', defaultValue=subdivJoint) root.subdivisionsJoint.showInChannelBox(1) root.addAttr('globalConnectorRadius', defaultValue=connectorRadius) root.globalConnectorRadius.showInChannelBox(1) root.addAttr('globalConnectorThickness', defaultValue=connectorThickness) root.globalConnectorThickness.showInChannelBox(1) root.addAttr('globalConnectorOffset', min=0, defaultValue=connectorOffset) root.globalConnectorOffset.showInChannelBox(1) root.radius.showInChannelBox(0) root.displayHandle = 1 root.setParent(rigGrp) trans.setParent(rigGrp) root.setTranslation(startPos) root.select() extendPipe(jointLength)
def create_VarFkCtrls(IdName, guideSurface, numberOfCtrls): # create controls ctrlGrp = pm.group(name=IdName + '_ctrls', empty=True, world=True) ctrlGrp.inheritsTransform.set(0) listOfCtrls = [] for currentCtrlIndex in range(numberOfCtrls): if numberOfCtrls > 1: FolliclePos = (1.0 / (numberOfCtrls - 1)) * currentCtrlIndex else: FolliclePos = (1.0 / (numberOfCtrls)) * currentCtrlIndex # create controlshape currentCtrl = pm.circle(name=('ctrl_vFK' + str(currentCtrlIndex + 1) + '_' + IdName), c=(0, 0, 0), nr=(1, 0, 0), sw=360, r=1.5, d=3, ut=0, tol=0.01, s=8, ch=False) currentCtrl[0].overrideEnabled.set(True) currentCtrl[0].overrideColor.set(4) # lock'n hide translates + scaleX currentCtrl[0].translateX.set(lock=True, keyable=False, channelBox=False) currentCtrl[0].translateY.set(lock=True, keyable=False, channelBox=False) currentCtrl[0].translateZ.set(lock=True, keyable=False, channelBox=False) currentCtrl[0].scaleX.set(lock=True) # add strength, position, radius attributes pm.addAttr(longName='rotateStrength', attributeType='float', keyable=True, defaultValue=1) pm.addAttr(longName='position', attributeType='float', keyable=True, min=0 - FolliclePos, max=1 - FolliclePos) pm.addAttr(longName='radius', attributeType='float', keyable=True, min=0.0001, defaultValue=0.3) # position min/max relative to defaultposition so ctrl can be zeroed out. Is remapped later back to 0 to 1 when connected to Follicle currentFollicle = create_follicle(guideSurface[0], uPos=FolliclePos, vPos=0.5) currentFollicle.simulationMethod.set(0) currentFollicle.collide.set(0) currentFollicle.flipDirection.set(True) currentFollicle = pm.listRelatives(currentFollicle, parent=True) # connect to strength multiplier rotateStrengthMultiplier = pm.shadingNode('multiplyDivide', asUtility=True, n=str(currentCtrl[0]) + '_strength_mult') currentCtrl[0].rotate >> rotateStrengthMultiplier.input1 pm.connectAttr(currentCtrl[0] + '.rotateStrength', rotateStrengthMultiplier + '.input2X', f=1) pm.connectAttr(currentCtrl[0] + '.rotateStrength', rotateStrengthMultiplier + '.input2Y', f=1) pm.connectAttr(currentCtrl[0] + '.rotateStrength', rotateStrengthMultiplier + '.input2Z', f=1) # compensate position zero value by current follicle position jntposZeroCompensate = pm.shadingNode('plusMinusAverage', asUtility=True, n=currentCtrl[0] + '_jntposZeroCompensate') pm.setAttr(jntposZeroCompensate + '.input1D[0]', pm.getAttr(currentFollicle[0].getShape() + '.parameterU')) pm.connectAttr(currentCtrl[0] + '.position', jntposZeroCompensate + '.input1D[1]', f=1) pm.connectAttr(jntposZeroCompensate + '.output1D', currentFollicle[0].getShape() + '.parameterU', f=1) # grouping buf = createBufGrp(currentCtrl)[0] pm.parent(buf, ctrlGrp, relative=True) pm.parent(currentFollicle, ctrlGrp) # connect follicle position to control buffer currentFollicle[0].translate >> buf.translate listOfCtrls.append(currentCtrl[0]) pm.select(clear=1) print('Successfully created ' + currentCtrl[0]) return listOfCtrls
def snap(driver, driven, typeCnx='parent', extraDrivers=(), skip=[]): ''' snaps objects and skips locked attributes to prevent errors... also this doesnt uses constraints to snap.. so The target objet could have keys if it is needed libUtil.snap('cube', 'target' , typeCnx='parent') Args: driver: driven: typeCnx: ['parent', 'parentCon', 1, 'p', 'P'] ['point', 'translate', 3, 't', 'T'] ['orient', 'rotate', 2, 'r', 'R'] ['scale', 'Scale', 4, 's', 'S'] extraDrivers: skip: Returns: ''' drivers = [driver] drivers.extend(extraDrivers) for i, driver in enumerate(drivers): if not isinstance(driver, pm.PyNode): drivers[i] = pm.PyNode(driver) if not isinstance(driven, pm.PyNode): driven = pm.PyNode(driven) # skip memory skipMemory = [] for s in skip: skipMemory.append(driven.attr(s).get()) dummy = pm.duplicate(driven, n=driven + 'dummy', parentOnly=1)[0] for attr in ('t', 'tx', 'ty', 'tz', 'r', 'rx', 'ry', 'rz', 's', 'sx', 'sy', 'sz'): dummy.attr(attr).unlock() con = pm.parentConstraint(mo=0, *(drivers + [dummy])) con.interpType.set(2) pm.delete(con) # pm.delete(pm.parentConstraint(mo=0, *(drivers + [dummy]) )) pm.delete(pm.scaleConstraint(mo=0, *(drivers + [dummy]))) # pm.delete( pm.parentConstraint(drivers, dummy, mo=0,)) t = pm.getAttr(dummy + '.translate') r = pm.getAttr(dummy + '.rotate') s = pm.getAttr(dummy + '.scale') pm.delete(dummy) # PARENT if typeCnx in ['parent', 'parentCon', 1, 'p', 'P']: i = 0 for at in ['tx', 'ty', 'tz']: if driven.attr(at).isLocked() == 0: driven.attr(at).set(t[i]) i = i + 1 i = 0 for at in ['rx', 'ry', 'rz']: try: driven.attr(at).set(r[i]) except: pass i = i + 1 # ROTATE ONLY elif typeCnx in ['orient', 'rotate', 2, 'r', 'R']: i = 0 for at in ['rx', 'ry', 'rz']: if driven.attr(at).isLocked() == 0: driven.attr(at).set(r[i]) i = i + 1 # TRANSLATE ONLY elif typeCnx in ['point', 'translate', 3, 't', 'T']: i = 0 for at in ['tx', 'ty', 'tz']: if driven.attr(at).isLocked() == 0: driven.attr(at).set(t[i]) i = i + 1 # SCALE ONLY elif typeCnx in ['scale', 'Scale', 4, 's', 'S']: i = 0 for at in ['sx', 'sy', 'sz']: if driven.attr(at).isLocked() == 0: driven.attr(at).set(s[i]) i = i + 1 # ALL elif typeCnx in ['all', 'All', 5, 'a', 'A']: i = 0 for at in ['tx', 'ty', 'tz']: if driven.attr(at).isLocked() == 0: driven.attr(at).set(t[i]) i = i + 1 i = 0 for at in ['rx', 'ry', 'rz']: if driven.attr(at).isLocked() == 0: driven.attr(at).set(r[i]) i = i + 1 i = 0 for at in ['sx', 'sy', 'sz']: if driven.attr(at).isLocked() == 0: driven.attr(at).set(s[i]) i = i + 1 # skip memory i = 0 for s in skip: driven.attr(s).set(skipMemory[i]) i = i + 1 pm.select(driven)
def buildVarFkFromUI(*args): # get inputs from UI inputCurve = pm.textField('input_inputCurve', query=True, text=True) IdName = pm.textField('input_IdName', query=True, text=True) numberOfCtrls = pm.intSliderGrp('slider_numOfCtrls', query=True, value=True) # check if input string is empty, default string or not existent if (inputCurve == '' or inputCurve == 'Draw a curve, 1 Joint per CV.'): pm.warning( 'You have to enter a curve. Select it and press the ">" button.') return # get input string's object pm.select(inputCurve) inputCurve = pm.selected() # check if input object exists if (pm.objExists(inputCurve[0]) != True): pm.warning( str(inputCurve) + ' does not exist. You have to enter a curve. Select it and press the ">" button.' ) return # continue if input is a transform with a nurbs curve shape, abort if not. if pm.nodeType(inputCurve[0]) == 'transform': if pm.nodeType(pm.listRelatives(inputCurve, shapes=True)[0]) == 'nurbsCurve': print('Curve is valid. Continuing...') else: pm.warning('Selected Transform is invalid. Please select Curve.') return else: pm.warning( 'Selected Object is invalid. Please select Curve (Transform).') return # workaround to get rid of unwanted characters by using maya's build in char check pm.select(clear=True) IdName = str(pm.group(name=IdName, empty=True)) if (IdName[0] == "|"): IdName = IdName.rsplit("|")[1] pm.delete() # check if rig with that IdName already exists and increment while pm.objExists(IdName): pm.warning('An object with the name \"' + IdName + '"\ already exists.') # get index from string indexList = [] for c in IdName[::-1]: if c.isdigit(): indexList.append(c) else: break indexList.reverse() index = int("".join(indexList)) # remove index from IdName IdName = IdName[0:-int(len(str(index)))] # add new index to IdName index += 1 IdName = IdName + str(index) pm.warning('New name is \"' + IdName + '"\.') buildVarFk(IdName, inputCurve, numberOfCtrls) return
def buildVarFk(IdName, inputCurve, numberOfCtrls): # main work calls # create joints on curve listOfJnts = create_jointChain(IdName, inputCurve) listOfJnts.pop() # pop endjoint pm.select(clear=True) # loft nurbs surface guideSurface = create_guideSurface(IdName, listOfJnts) # skinbind nurbs surface to jointchain pm.skinCluster(guideSurface, listOfJnts, tsb=True, skinMethod=0, maximumInfluences=1, dropoffRate=10.0) # add parametric attributes to joints addPositionOnSurfaceAttr(listOfJnts, guideSurface) # create controls listOfCtrls = create_VarFkCtrls(IdName, guideSurface, numberOfCtrls) # cleanup grouping # create main control mainCtrl = pm.curve(name=IdName, d=1, p=[(-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1), (-1, 1, 1), (-1, -1, 1), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (1, 1, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1)]) mainCtrl.getShape().overrideEnabled.set(True) mainCtrl.getShape().overrideColor.set(17) # create joint group listJnt1 = [listOfJnts[0]] # because createBufGrp expects a list jntGrp = createBufGrp(listJnt1)[0] jntGrp.rename(IdName + '_joints') # snap main control pivot to joint group pivot and parent joint group jntGrpPos = pm.xform(jntGrp, q=True, t=True, ws=True) jntGrpRot = pm.xform(jntGrp, q=True, ro=True, ws=True) pm.xform(mainCtrl, t=jntGrpPos, ro=jntGrpRot) pm.parent(jntGrp, mainCtrl) # parent control group ctrlGrp = listOfCtrls[0].getParent(2) pm.parent(ctrlGrp, mainCtrl, r=True) pm.xform(ctrlGrp, piv=jntGrpPos) # scale constrain world locator to main-ctrl as a reference point for scaling, feed into follicle. only for cosmetic reasons offsetLoc = pm.spaceLocator(n=IdName + '_ctrl_offsetLoc') offsetLoc.inheritsTransform.set(0) offsetLoc.visibility.set(0) pm.parentConstraint(mainCtrl, offsetLoc, maintainOffset=False) pm.scaleConstraint(mainCtrl, offsetLoc, maintainOffset=False) for obj in ctrlGrp.getChildren(): if pm.nodeType(obj.getChildren()[0]) != 'follicle': offsetLoc.rotate >> obj.rotate offsetLoc.scale >> obj.scale pm.parent(offsetLoc, ctrlGrp, r=True) inputCurve[0].visibility.set(False) pm.parent(inputCurve, mainCtrl) pm.parent(guideSurface, mainCtrl) print('Cleanup complete. Connecting Controls...') # generating ctrl output nodes and connecting to joints for jnt in listOfJnts: # reset list of outputs, important! otherwise every joints gets connected to all control-outputs for the previous joint(s) before too. rotateMultipliers = [] # create a layered texture node and strength multiplier for every joint to multiply all scale values scaleMultiplier = pm.shadingNode('layeredTexture', asUtility=True, n='util_' + jnt + '_scaleInput') i = 0 for ctrl in listOfCtrls: rotateMultiplier = create_ctrlOutput(ctrl, jnt) rotateMultipliers.append(rotateMultiplier) # connect ctrl scale to scale multiplier pm.connectAttr(ctrl + '.scale', scaleMultiplier + '.inputs[' + str(i) + '].color') pm.setAttr(scaleMultiplier + '.inputs[' + str(i) + '].blendMode', 6) # get remapDistance outValue and connect to scale multiplier input[i] alpha remapDist = pm.listConnections(rotateMultiplier, type='remapValue')[0] pm.connectAttr(remapDist + '.outValue', scaleMultiplier + '.inputs[' + str(i) + '].alpha') i += 1 # sum up rotate outputs of all controls and connect to joints # connect to sum +-avg node sum = pm.shadingNode('plusMinusAverage', asUtility=True, n='util_' + jnt + '_sum_rotate') for i in range(len(rotateMultipliers)): rotateMultipliers[i].output >> sum.input3D[i] pm.connectAttr(sum + '.output3D', jnt + '.rotate') # set last input to base value of 1, OOP methods does not work on sub attributes of layeredTexture i += 1 pm.setAttr(scaleMultiplier + '.inputs[' + str(i) + '].color', (1, 1, 1)) pm.setAttr(scaleMultiplier + '.inputs[' + str(i) + '].alpha', 1) pm.setAttr(scaleMultiplier + '.inputs[' + str(i) + '].blendMode', 0) # connect scale multiplier to joint scale YZ scaleMultiplier.outColor >> jnt.scale print('Successfully connected all control output to joint: ' + jnt + '.') # create buffer group for main control, buffer-function expects list pm.select(mainCtrl) createBufGrp(pm.selected()) print('Successfully created variable FK rig.'), pm.select(clear=True) return
def selectAll(self, args): layer = self.getAnim('Foxo_Controls') pm.select(pm.editDisplayLayerMembers(layer, q=True))
def create_jointChain(IdName='joint', inputCurve=pm.selected(), orientation='xyz'): # get number of CVs on InputCurve numberOfCvs = pm.getAttr(inputCurve[0] + '.cp', s=1) # create joints on world space cv locations Jnts = [] for i in range(0, numberOfCvs): pm.select(clear=True) currentCvPos = pm.pointPosition(inputCurve[0].cv[i], w=1) Jnt = pm.joint(name='_'.join(['bn', IdName, str(i + 1)])) pm.xform(Jnt, t=currentCvPos) Jnts.append(Jnt) # create end joint pm.select(clear=True) endJntPos = 0.1 * (pm.getAttr(Jnts[len(Jnts) - 1].translate) - pm.getAttr(Jnts[len(Jnts) - 2].translate)) + pm.getAttr( Jnts[len(Jnts) - 1].translate) endJnt = pm.joint(name='be_' + IdName, position=endJntPos, a=True) Jnts.append(endJnt) # set aim and orientation vectors, always yup aimDict = {} aimDict[orientation[0]] = 1 aimDict[orientation[1]] = 0 aimDict[orientation[2]] = 0 aimVec = (aimDict['x'], aimDict['y'], aimDict['z']) orientDict = {} orientDict[orientation[0]] = 0 orientDict[orientation[1]] = 0 orientDict[orientation[2]] = 1 orientVec = (orientDict['x'], orientDict['y'], orientDict['z']) # orient first joint JntAimConstrain = pm.aimConstraint(Jnts[1], Jnts[0], aimVector=aimVec, upVector=(0, 1, 0), worldUpType="scene") pm.delete(JntAimConstrain) Jnts[0].jointOrient.set(Jnts[0].rotate.get()) Jnts[0].rotate.set(0, 0, 0) # orient middle joints for i in range(1, len(Jnts) - 1): JntAimConstrain = pm.aimConstraint(Jnts[i + 1], Jnts[i], aimVector=aimVec, upVector=orientVec, worldUpType="objectrotation", worldUpVector=orientVec, worldUpObject=Jnts[i - 1]) pm.delete(JntAimConstrain) Jnts[i].jointOrient.set(Jnts[i].rotate.get()) Jnts[i].rotate.set(0, 0, 0) # orient last joint Jnts[len(Jnts) - 1].jointOrient.set(Jnts[len(Jnts) - 2].jointOrient.get()) # parent joints for i in range(1, len(Jnts)): pm.parent(Jnts[i], Jnts[i - 1], absolute=True) pm.select(Jnts[0]) print('Successfully created and oriented joint-chain. Continuing...') return Jnts
def spaceSwitchHeadSetup(self): mainFollowLoc = pm.spaceLocator(name='M_headFollowMain_loc') headFollowLoc = pm.spaceLocator(name='M_headFollowHead_loc') # reduce local scale for loc in [mainFollowLoc, headFollowLoc]: pm.setAttr(loc + 'Shape.localScaleX', 0.015) pm.setAttr(loc + 'Shape.localScaleY', 0.015) pm.setAttr(loc + 'Shape.localScaleZ', 0.015) mainFollowGrp = pm.group(name='M_headFollowMain_grp', em=True) headFollowGrp = pm.group(name='M_headFollowHead_grp', em=True) pm.parent(mainFollowLoc, mainFollowGrp) pm.parent(mainFollowGrp, 'main_ctrl') pm.parent(headFollowLoc, headFollowGrp) # pm.parent(headFollowGrp, 'M_head_ctrl') pm.move( mainFollowGrp, (self.headRootPos[0], self.headRootPos[1], self.headRootPos[2])) pm.move( headFollowGrp, (self.headRootPos[0], self.headRootPos[1], self.headRootPos[2])) neckCtrlNum = (len(pm.ls('M_spine*_jnt')) - 1) pm.select('M_spine%s_jnt' % neckCtrlNum) neckCtrl = pm.ls(sl=True)[0] neckCtrl = pm.PyNode(neckCtrl) neckPos = neckCtrl.getTranslation('world') headFollowHeadGrp = pm.group(n='M_followHead_grp') pm.parent(headFollowGrp, headFollowHeadGrp) pm.xform(headFollowGrp, piv=neckPos, ws=True) followOrientConst = pm.orientConstraint('M_headFollowMain_loc', 'M_headFollowHead_loc', headFollowHeadGrp, mo=True) print('NeckCtrl: %s' % neckCtrl) pm.parent('M_head_ctrl', neckCtrl) rigUtils.hideAttributes(ctrl='M_head_ctrl', trans=True, scale=True, rot=False, vis=True, radius=False) # add channel box attributes to switch space pm.addAttr('M_head_ctrl', ln="follow", at="enum", en="main:head:") pm.setAttr('M_head_ctrl.follow', e=True, keyable=True) # create connections from the follow attrs to the orientConstraint headFollowInvNode = pm.createNode('reverse', name='headFollow_inv') pm.connectAttr( 'M_head_ctrl.follow', 'M_followHead_grp_orientConstraint1.M_headFollowHead_locW1', f=True) pm.connectAttr('M_head_ctrl.follow', headFollowInvNode + '.inputX', f=True) pm.connectAttr( headFollowInvNode + '.outputX', 'M_followHead_grp_orientConstraint1.M_headFollowMain_locW0', f=True)
def keyLimb(self, args): preselection = pm.ls(sl=True) self.selectLimb(1) pm.setKeyframe() pm.select(preselection)
def create_ctrl_ik_leg(jnts, side='L', parent='DIRECTION', scale=1): ''' Args: jnts: joint dictionary side: 'R' or 'L' Returns: joint dictionary ''' color = biped.define_color(side) id = '%s_foot01' % side # check if exists if pm.objExists('%s_ikCtrl' % id): pm.select('%s_ikCtrl' % id) return '%s_ikCtrl Exists' % id # -- ik ctrl -- # jnts[id]['ikCtrl'] = curveLib.createShapeCtrl(type='cube', name='%s_ikCtrl' % id, scale=scale, color=color) # group and align zero = riggUtils.grpCtrl(jnts[id]['ikCtrl']) riggUtils.snap(jnts[id]['ctrlJnt'], zero, typeCnx='point') riggUtils.grpIn('%s_leg_ctrlGrp' % side, zero) # parent leg_ctrlGrp # limit riggUtils.cleanUpAttr(sel=[jnts[id]['ikCtrl']], listAttr=['sx', 'sy', 'sz'], l=0, k=0, cb=0) log_debug('limit') # gimbal gimbalCtrl = pm.duplicate(jnts[id]['ikCtrl'], n='%s_ikGimbalCtrl' % id)[0] pm.parent(gimbalCtrl, jnts[id]['ikCtrl']) pm.xform('%s.cv[0:]' % gimbalCtrl.getShape(), s=(.8, .8, .8), r=1) pm.addAttr(jnts[id]['ikCtrl'], ln='gimbal_vis', at='bool', k=1) jnts[id]['ikCtrl'].gimbal_vis >> gimbalCtrl.visibility # store attr of gimbal on main ctrl pm.addAttr(jnts[id]['ikCtrl'], ln='gimbal', dt='string') jnts[id]['ikCtrl'].attr('gimbal').set('%s' % gimbalCtrl, k=0, l=0, type='string') log_debug('gimal done') # -- pole vector -- # jnts[id]['pvecCtrl'] = curveLib.createShapeCtrl(type='sphere', name='%s_pvecCtrl' % id, scale=scale, color=color) # group and align zero = riggUtils.grpCtrl(jnts[id]['pvecCtrl']) log_debug('finding pole position') polePos = riggUtils.poleVectorPosition( startJnt=jnts['%s_leg01' % side]['ikJnt'], midJnt=jnts['%s_leg02' % side]['ikJnt'], endJnt=jnts['%s_foot01' % side]['ctrlJnt'], length=12, createLoc=0, createViz=0) log_debug('polepos is %s' % polePos) pm.xform(zero, ws=1, t=(polePos.x, polePos.y, polePos.z)) riggUtils.grpIn('%s_leg_ctrlGrp' % side, zero) # parent leg_ctrlGrp riggUtils.grpIn(parent, '%s_leg_ctrlGrp' % side) # parent to DIRECTION # limit riggUtils.cleanUpAttr(sel=[jnts[id]['pvecCtrl']], listAttr=['sx', 'sy', 'sz', 'rx', 'ry', 'rz'], l=0, k=0, cb=0) log_info("Done create_ctrl_ik_leg()") return jnts
import pymel.core as pm import re name_patern = 'OUTPUT' key_value = 2.0 mode = 1 #1 = key, 0 = delete bsn_attr_slot = 1 #0 = en, 1 = attr under the en name_filter = re.compile(r'({0})'.format(name_patern)) to_select_list = [] blendshape_list = pm.ls(type='blendShape') for blendshape in blendshape_list: if name_filter.search(blendshape.nodeName()): to_select_list.append(blendshape) pm.select(to_select_list[0:1]) for each in to_select_list[0:1]: if bsn_attr_slot == 0: if mode: pm.setKeyframe(each, v=key_value, at='en') else: pm.cutKey(each, at='en') elif bsn_attr_slot == 1: attr = pm.PyNode(each.nodeName() + '.' + 'weight[0]') if mode: pm.setKeyframe(attr, v=key_value) else: pm.cutKey(attr)