def makeCube(): squareCrv = dtLib.makeSquare() squareCrv2 = dtLib.makeSquare() squareCrv2.setRotation([90, 0,0]) squareCrv2.setTranslation([0,0.5,-0.5]) pm.makeIdentity(apply=True, translate=True, rotate=True, scale=True, normal=1) crvs = squareCrv2.getShapes() for current in crvs: pm.parent(current, squareCrv, relative=True, shape=True) pm.delete(squareCrv2) pm.select(squareCrv) dupCrv = pm.duplicate() dupCrv[0].setRotation([180, 0, 0]) dupCrv[0].setTranslation([0,0,-1]) pm.makeIdentity(apply=True, translate=True, rotate=True, scale=True, normal=1) crvs = dupCrv[0].getShapes() for current in crvs: pm.parent(current, squareCrv, relative=True, shape=True) pm.delete(dupCrv) #中央にピポットを移動 pm.select(squareCrv) pm.xform(cp=True) return pm.selected()
def add_text_shape(ctrl, text): text_curve = pm.PyNode( pm.textCurves(ch=False, font="Arial Black", text=text, name='text_curve')[0] ) text_curve_length = text_curve.boundingBox()[1][0] #max X text_curve_height = text_curve.boundingBox()[1][1] #max Y shapes = pm.listRelatives(text_curve, ad=True, type="shape") pm.xform(text_curve, piv=[0,text_curve_height,0], ws=True) pm.move(text_curve, 0, -text_curve_height , 0) scale = 1 / text_curve_length pm.scale(text_curve, scale, scale, scale) pm.makeIdentity(text_curve, apply=True, t=True, r=True, s=True) display_attr = ("%s_text_display"%text) if not ctrl.hasAttr(display_attr): ctrl.addAttr(display_attr, at='bool', k=True, dv=1) for s in shapes: pm.parent(s, ctrl, s=True, r=True) s.rename('%sText'%text) pm.connectAttr("%s.%s" %(ctrl.name(), display_attr), s.visibility) pm.delete(text_curve)
def build_between_points(cls, start_xform, end_xform, num_joints, name={'name':'chain'}, freeze=True, chain=True, parent=None, offset=False): """ Create joints based on given 3D spatial positions/rotations e.g. [[[10,5.3,1.4],[0,90,0]],...,nPos] Args: start_xform [pm.nt.Transform]: starting position end_xform [pm.nt.Transform]: ending position name (str): base name for the chain chain (bool): whether or not to make a chain, or isolated joints offset (bool): whether or not to build in offset groups for the joints parent (pm.nt.Transform): final parent of the joints, empty if kept at root level Returns: [pm.nt.Joint]: list of joints Usage: Joint.build_between_points(pm.ls(sl=True)[0], pm.ls(sl=True)[1], 5, chain=True, offset=True, freeze=True) """ xform_interps = transform.spatial_interpolate(pm.xform(start_xform, q=True, t=True, ws=True), pm.xform(end_xform, q=True, t=True, ws=True), num_joints) rotation_interps = transform.spatial_interpolate(pm.xform(start_xform, q=True, ro=True, ws=True), pm.xform(end_xform, q=True, ro=True, ws=True), num_joints) positions = [[xform_interp, rotation_interp] for xform_interp, rotation_interp in zip(xform_interps, rotation_interps)] return cls.build_from_points(positions, name=name, chain=chain, parent=parent, offset=offset, freeze=freeze)
def generate( self, radius = 10, iterations = 1 ): self.radius = radius self.iterations = iterations print( "%s radius %f iterations %i" % ( self.__class__.__name__, self.radius, self.iterations ) ) octahedronRadius = float(self.radius) / util.pow( float(2), float(self.iterations ) ) octahedron = self.mesh( radius = octahedronRadius ) octahedra = [ octahedron ] pm.polySoftEdge( angle = 0 ) octahedronHeight = octahedron[ 1 ].getSideLength() / util.sqrt( 2 ) for i in range( iterations ): mesh = self.__generateMesh( octahedra[ 0 ], octahedronHeight, octahedronRadius, ( i + 1 ) ) octahedronHeight *= 2 octahedronRadius *= 2 octahedra = [ mesh ] pm.xform( mesh[ 0 ], centerPivots = True ) print( "Construction complete" ) return mesh
def make_stabilized_node(nodeName=None, centered=True): ''' Very simple proc to generate a Stabilized node for raw MoCap tracking purposes... First selected node is used as the Aim axis, second selected is used as this aim's worldUp ''' RequiredMarkers = pm.ls(sl=True, l=True) #pos = pm.xform(WorldUpObj, q=True, ws=True, t=True) curve = pm.curve(ws=True, d=1, p=(0, 0, 0), k=0) if centered: AimAt = RequiredMarkers[0] WorldUpObj = RequiredMarkers[1] pm.pointConstraint(RequiredMarkers, curve) else: AimAt = RequiredMarkers[1] WorldUpObj = RequiredMarkers[2] pm.pointConstraint(RequiredMarkers[0], curve) pm.aimConstraint((AimAt, curve), weight=1, aimVector=(0, 0, 1), upVector=(0, 1, 0), worldUpType="object", worldUpObject=WorldUpObj) #Snap a curveKnot to the pivot of all referenceMarkers for node in RequiredMarkers: pm.curve(curve, a=True, ws=True, p=(pm.xform(node, q=True, ws=True, t=True))) pm.curve(curve, a=True, ws=True, p=(pm.xform(AimAt, q=True, ws=True, t=True))) return curve
def locatorGrid(width, height, depth, offset, centered=True): '''Create a grid of locators to test upon Args: width (int): Width of the grid height (int): Height of the grid offset (float): Adds an offset multiplier to the locator positions centered (bool): determines whether it's centered in world space Returns (pm.PyNode): The top group of the locator grid Usage: locatorGrid(5,5,5,2) ''' if not pm.objExists('locatorGrid'): grp=pm.group(em=True,n='locatorGrid') for d in range(0,depth): for w in range(0,width): for h in range(0,height): loc = pm.polyCube(w=.5, h=.5, d=.5, ch=0)[0] pm.move(loc,(w*offset,h*offset,d*offset), rpr=True) loc.setParent(grp) if loc.getShape().type() == "locator": loc.localScale.set(.2,.2,.2) if centered: pm.xform(grp, cp=1) pm.move(grp, (0, 0, 0), rpr=1) pm.makeIdentity(grp, apply=True, r=1,s=1,t=1) return grp
def buildChains(self, *args): """ Build joint chains based on locator positions. """ self.jointChain = [] self.ikChain = [] self.fkChain = [] loc1Pos = pm.xform(self.loc1, q=True, ws=True, t=True) loc2Pos = pm.xform(self.loc2, q=True, ws=True, t=True) loc3Pos = pm.xform(self.loc3, q=True, ws=True, t=True) jnt1='%s_shldrJnt'%self.prefix jnt2='%s_elbow1Jnt'%self.prefix jnt3='%s_wristJnt'%self.prefix self.jointChain.append(pm.PyNode(pm.joint(p=loc1Pos, n=jnt1))) self.jointChain.append(pm.PyNode(pm.joint(p=loc2Pos, n=jnt2))) self.jointChain.append(pm.PyNode(pm.joint(p=loc3Pos, n=jnt3))) #--- Orient the chain self.orientChain() #--- Creating duplicate ik/fk joint chains for each in pm.duplicate(self.jointChain, rc=True): # Slice off number maya adds during duplication each.rename('%s_ik' % each[:-1]) self.ikChain.append(pm.PyNode(each)) for each in pm.duplicate(self.jointChain, rc=True): each.rename('%s_fk' % each[:-1]) self.fkChain.append(pm.PyNode(each))
def transfer_shape(source, target, flip=True): """it will replace the shape of selected number 2 with the shapes of selected number 1""" target_shape = target.getShape(noIntermediate=True) target_shape_orig = get_orig_shape(target_shape) dup = pymel.duplicate(source, rc=1)[0] tmp = pymel.createNode('transform') pymel.parent(tmp, dup) pymel.xform(tmp, t=(0, 0, 0), ro=(0, 0, 0), scale=(1, 1, 1)) pymel.parent(tmp, w=1) for sh in dup.getShapes(noIntermediate=True): pymel.parent(sh, tmp, r=1, s=1) pymel.delete(dup) temp_grp_negScale = pymel.createNode('transform') pymel.parent(tmp, temp_grp_negScale) if flip: temp_grp_negScale.scaleX.set(-1) pymel.parent(tmp, target) pymel.delete(temp_grp_negScale) pymel.makeIdentity(tmp, t=True) # this brings translate values at 0 before scale freezing pymel.makeIdentity(tmp, apply=True, t=True, r=True, s=True) pymel.parent(tmp, w=1) color_info, vis_master = get_previous_controller_info(target) shapes_has_been_deleted = False for sh in tmp.getShapes(): if target_shape_orig: adapt_to_orig_shape(sh, target.getShape()) else: if not shapes_has_been_deleted: shapesDel = target.getShapes() if shapesDel: pymel.delete(shapesDel) shapes_has_been_deleted = True pymel.parent(sh, target, r=1, s=1) pymel.rename(sh.name(), target.name() + "Shape") if color_info[0]: if color_info[1]: sh.overrideEnabled.set(True) sh.overrideRGBColors.set(1) sh.overrideColorRGB.set(color_info[2]) else: sh.overrideEnabled.set(True) sh.overrideRGBColors.set(0) sh.overrideColor.set(color_info[2]) else: sh.overrideEnabled.set(False) if vis_master: vis_master.connect(sh.visibility) pymel.delete(tmp)
def set_newPivot(*args): sel = pm.ls(sl=True) source = sel[-1] piv = pm.xform (source, piv=True, q=True, ws=True) for obj in sel[:-1]: pm.xform (obj, ws=True, piv=(piv[0], piv[1], piv[2]) )
def setPosUv(vtxs,length,side,uvDistorted): startUv = pm.ls(pm.polyListComponentConversion(vtxs[0],fv=1,tuv=1),fl=1) if side == 'left': pm.polyEditUV(startUv,r=0,u=0,v=0) else: pm.polyEditUV(startUv,r=0,u=1,v=0) for i in range(1,len(vtxs)): vtx1Pos = pm.xform(vtxs[i-1],q=1,t=1,ws=1) vtx2Pos = pm.xform(vtxs[i],q=1,t=1,ws=1) vtx1PosVec = MVector(vtx1Pos[0],vtx1Pos[1],vtx1Pos[2]) vtx2PosVec = MVector(vtx2Pos[0],vtx2Pos[1],vtx2Pos[2]) dist = (vtx2PosVec - vtx1PosVec).length() factor=0.0 if uvDistorted: factor = dist / length else: factor = 1.0 / (len(vtxs) - 1) uv1 = pm.ls(pm.polyListComponentConversion(vtxs[i-1],fv=1,tuv=1),fl=1) uv2 = pm.ls(pm.polyListComponentConversion(vtxs[i],fv=1,tuv=1),fl=1) uv1Pos = pm.polyEditUV(uv1,q=1) uv2Pos = uv1Pos[1] + factor if side == 'left': pm.polyEditUV(uv2,r=0,u=0,v=uv2Pos) else: pm.polyEditUV(uv2,r=0,u=1,v=uv2Pos)
def generateShape(self, *args): sel = pm.ls(sl=1) if len(sel) != 4: pm.mel.warning('Must select: Neutral, TargetA, TargetB, TargetC meshes') return meshN = sel[0] meshA = sel[1] meshB = sel[2] meshC = sel[3] # Create new mesh new = pm.duplicate(meshN, n='Corrective')[0] # Per vertex, translate in world space: C-(A+B) for vtx in new.vtx: vert = vtx.split('.')[1] n_pos = pmd.Point(pm.xform( vtx, query=True, ws=True, t=True)) a_pos = pmd.Point(pm.xform( meshA + '.' + vert, query=True, ws=True, t=True)) b_pos = pmd.Point(pm.xform( meshB + '.' + vert, query=True, ws=True, t=True)) c_pos = pmd.Point(pm.xform( meshC + '.' + vert, query=True, ws=True, t=True)) aVec = a_pos - n_pos bVec = b_pos - n_pos cVec = c_pos - n_pos delta = cVec - (aVec + bVec) pm.move(vtx, delta, r=1)
def create_bind_proxy(jnt): if jnt.getChildren(): name=jnt.name() + "_bindProxy" distance = jnt.getChildren()[0].translateX.get() if not pm.objExists(name): proxy = pm.polyCylinder(r=0.25, h=0.5, sx=12, sy=4, sz=4, ax=[1,0,0], rcp=1, cuv=0, ch=0, name=name)[0] pm.xform(proxy, piv=[-0.5, 0, 0]) pm.parent(proxy, 'bind_proxy') pm.delete(pm.parentConstraint(jnt, proxy, mo=False)) proxy.scale.set(distance, distance, distance) try: jnt.addAttr('iterations', at='long', min=1, max=5, dv=3, k=True) jnt.addAttr('bind_proxy', at='message') except: pass else: proxy = pm.PyNode(name) pm.skinCluster( jnt, proxy, tsb=True) proxy.message >> jnt.bind_proxy
def __areaSkin(self,*args): geo = pm.ls(sl = 1)[0] skinCluster = mel.eval('findRelatedSkinCluster ' + geo) vertex = pm.polyEvaluate(geo,v = 1) joints = pm.skinCluster(skinCluster,q = 1,inf = 1) skinList = {} for num in range(0,vertex): vertex = geo + '.vtx[' + str(num) + ']' vertPos = pm.xform(vertex,q = 1,t = 1,ws = 1) tempDict = {} for joint in joints: jntPos = pm.xform(joint,q = 1,t = 1,ws = 1) dist = math.sqrt(pow(vertPos[0] - jntPos[0],2) + pow(vertPos[1] - jntPos[1],2) + pow(vertPos[2] - jntPos[2],2)) tempDict.setdefault(joint,dist) minDistVal = min(distVal for distVal in tempDict.values()) for joint in tempDict.keys(): if minDistVal == tempDict[joint]: if joint not in skinList: skinList[joint] = [] skinList[joint].append(vertex) for item in skinList.items(): joint = item[0] vertex = item[1] for vert in vertex: pm.skinPercent(skinCluster,vert,transformValue = (joint,1))
def create_hook(cls, asset="asset", side="c", part="part", snap_to=None, in_out='in'): """ Settings for generating hooks in the autorig. :parameters: asset: For naming convention. side: For naming convention. (l, r, c) part: For naming convention. snap_to: Object to snap to. in_out: default value. """ hook_name = NameUtils.get_unique_name(asset, side, part, "loc") hook = pm.createNode(settings.HOOK_NODE_TYPE, n=hook_name) if settings.HOOK_NODE_TYPE == "locator": hook = hook.getParent() hook.rename(hook_name) digit_type = 0 if in_out == 'out': digit_type = 1 hook.addAttr('hookType', at='float', dv=digit_type) hook.attr('hookType').lock(1) if snap_to: pm.xform(hook, ws=1, matrix=snap_to.wm.get()) return hook
def load_position(obj): '''Finds all of the positions for the selected object and applies them Args: obj (pm.PyNode): the object to apply to Returns (dict): position Usage: get_positions(pm.ls(sl=True)[0]) ''' #Current version folder nonsense folder = os.path.join( environ.POSITIONS, obj ) versionFolder = lib_env.folder_detectVersions( folder, versionUp = False ) if versionFolder: folder = versionFolder else: pm.warning('Folder does not exist') #Handling shit if os.path.exists(folder): os.chdir(folder) positions = [] for file in glob.glob("*.pos"): position = import_position(file) print position pm.xform(obj, t=position['translate'], ro=position['rotate'], s=position['scale'], ws=True) else: pm.warning('Object: %s does not have any deformers available in folder: %s'%(obj,folder))
def Snap(target, source, translation=True, rotation=True): ''' Snaps source object to target object. If point is True, translation will snap. If orient is True, orientation will snap. If source is None, then it looks for lists for translation,rotation and scale ''' #if source doesnt exists and passing in transform lists if not source: if isinstance(translation, list): pm.xform(target, ws=True, translation=translation) if isinstance(rotation, list): pm.xform(target, ws=True, rotation=rotation) return #translation if translation: trans = pm.xform(source, q=True, ws=True, translation=True) pm.xform(target, ws=True, translation=trans) #orientation if rotation: rot = pm.xform(source, q=True, ws=True, rotation=True) pm.xform(target, ws=True, rotation=rot)
def autoPoleVector( baseJnt=None, endJnt=None, side='L' ): baseJntPos = pm.xform( baseJnt, q=True, t=True, ws=True ) endJntPos = pm.xform( endJnt, q=True, t=True, ws=True ) pm.select(clear=True) poleVectorJnt_one = pm.joint( p=baseJntPos ) poleVectorJnt_two = pm.joint( p=endJntPos ) poleVectorIKstuff = pm.ikHandle( sj = poleVectorJnt_one, ee = poleVectorJnt_two, solver = "ikSCsolver" ) pv = pm.spaceLocator() pv.setParent( poleVectorJnt_two ) pv.translate.set( 0,0,0 ) pvZeros = ZeroGrp( pv ) pm.pointConstraint( poleVectorIKstuff[0], pvZeros[0] ) if side=='L': pv.translateX.set( 1 ) elif side=='R': pv.translateX.set( -1 ) pvZeros[0].setParent( poleVectorJnt_two ) return ( pv, poleVectorIKstuff, (poleVectorJnt_one, poleVectorJnt_two) )
def createCOG(*args): newCog = createCircle()[0] cvsToSelect = (newCOG.cv[::2]) pm.select(cvsToSelect) pm.xform(s = [.5, .5, .5]) return newCog
def GuideCrv ( startGuider=None , endGuider=None ): if startGuider==None or endGuider==None: startGuider,endGuider = pm.ls(sl=True) pm.select(clear=True) startJnt = pm.joint ( n = startGuider.name()+"_guideCrvJnt") pm.parent (startJnt , startGuider) startJnt.translate.set (0,0,0) startJnt.visibility.set (0) pm.setAttr ( startJnt.visibility , lock=True ) endJnt = pm.joint ( n = endGuider.name()+"_guideCrvJnt" ) pm.parent (endJnt , endGuider) endJnt.translate.set (0,0,0) endJnt.visibility.set (0) pm.setAttr ( endJnt.visibility , lock=True ) startJntPos = pm.xform ( startJnt , q=True , ws=True , t=True) endJntPos = pm.xform ( endJnt , q=True , ws=True , t=True) guideCrv = pm.curve ( degree=1 , p = (startJntPos ,endJntPos) , k=(1,2) ) pm.rename ( guideCrv , startGuider.name()+"_guideCrv") pm.skinCluster ( guideCrv , startJnt , endJnt ) guideCrv.inheritsTransform.set(0) guideCrv.template.set(1) pm.select(clear=True) return guideCrv
def mirrorPose(self): lf='lf_' rt='rt_' center = 'ctr_' sel = pm.ls(sl=1) pm.select(clear=True) commands = [] for s in sel: mirrorObject = "" if str(s).startswith(lf): mirrorObject = rt + s[3:] elif str(s).startswith(rt): mirrorObject = lf + s[3:] elif str(s).startswith(center): mirrorObject = center + s[4:] pos = pm.xform(s, q=1, ws=1, rp=1) rot = pm.xform(s, q=1, ws=1, ro=1) scale = pm.xform(s, q=1, r=1, s=1) commands.append( 'move %s %s %s -ws -rpr "%s"'%(-pos[0],pos[1],pos[2],mirrorObject) ) commands.append( 'rotate -a %s %s %s -ws "%s" '%(rot[0],-rot[1],-rot[2],mirrorObject) ) commands.append( 'scale %s %s %s "%s"'%(scale[0],scale[1],scale[2],mirrorObject) ) pm.select(mirrorObject,add=True) for c in commands: pm.mel.eval(c)
def FindPVposition( objs=pm.ls(sl=True) ): if not len(objs) == 3: pm.error( 'ehm_tools...findPVposition: objs arguments takes exactly 3 objects. %s was given.'%len(objs) ) base = objs[0] mid = objs[1] tip = objs[2] A = dt.Vector( pm.xform( base, q=True, t=True, ws=True ) ) B = dt.Vector( pm.xform( mid, q=True, t=True, ws=True ) ) C = dt.Vector( pm.xform( tip, q=True, t=True, ws=True ) ) AC = C - A AB = B - A D = A + ( (dt.dot(AB,AC.normal())) * AC.normal() ) # AB projected on AC position = B + B - D if (position[0] - B[0] < 0.001) and (position[1] - B[1] < 0.001) and (position[2] - B[2] < 0.001): pm.warning( 'ehm_tools...FindPVposition: Limbs were straight. None was returned!' ) return None else: return position
def change_distance(self): intervValue = self.interv_int.value() value = self.distance_float.value() pm.setAttr(rigLight+'.translateZ', value) pm.xform(vis_mainGrp, s=[value, value, value]) vis_mainGrp
def strokePath(node, radius=.1): """ Create a nurbs surface from a curve control """ curveNodes = separateShapes(node) for curveNode in curveNodes: shape = curveNode.listRelatives(type='nurbsCurve')[0] t = pm.pointOnCurve(shape, p=0, nt=1) pos = pm.pointOnCurve(shape, p=0) cir = pm.circle(r=radius)[0] pm.xform(cir, t=pos, ws=1) #align the circule along the curve l = pm.spaceLocator() pm.xform(l, t=[pos[0]+t[0], pos[1]+t[1], pos[2]+t[2]], ws=1) pm.delete(pm.aimConstraint(l, cir, aimVector=[0,0,1])) pm.delete(l) newxf = pm.extrude(cir, curveNode, rn=False, po=0, et=2, ucp=1, fpt=1, upn=1, scale=1, rsp=1, ch=1)[0] pm.delete(cir) pm.delete(curveNode.listRelatives(type='nurbsCurve')) parentShape(curveNode, newxf) if len(curveNodes) > 1: for i in range(1, len(curveNodes)): parentShape(curveNodes[0], curveNodes[i]) return curveNodes[0]
def getXProductFromNodes(midObj, topObj, btmObj): """ get a cross product based upon the position of the first three objects in objList Returns the cross product of two vectors: midObj to topObj and midObj to btmObj """ #get the vectors midPos = pm.xform(midObj, q=True, worldSpace=True, translation=True) topPos = pm.xform(topObj, q=True, worldSpace=True, translation=True) btmPos = pm.xform(btmObj, q=True, worldSpace=True, translation=True) topVector = [topPos[0] - midPos[0], topPos[1] - midPos[1], topPos[2] - midPos[2]] btmVector = [btmPos[0] - midPos[0], btmPos[1] - midPos[1], btmPos[2] - midPos[2]] #create a temporary vectorProduct node vp = pm.createNode("vectorProduct") #set to cross product vp.operation.set(2) vp.input1.set(btmVector) vp.input2.set(topVector) #store the cross product cp = vp.output.get() #delete the vector node pm.delete(vp) return cp
def getShapePos(*nodes, **kwargs): """ @return: dictionary of {shapePyNode: [pointPositionList],...} """ ws = kwargs.get('ws', False) if ws: space = 'world' else: space = 'preTransform' vertObjs, crvObjs, surfObjs = filterShapes(*nodes) result = {} for obj in vertObjs: assert isinstance(obj, pm.nodetypes.Mesh) result[obj] = obj.getPoints(space=space) for obj in crvObjs: assert (isinstance(obj, pm.nodetypes.NurbsCurve)) result[obj] = [] for i in range(obj.numCVs()): result[obj].append(pm.xform(obj.cv[i], q=True, ws=ws, t=True)) #this might have a bug? #result[obj] = obj.getCVs(space='world') #result[obj].append(.getPosition(space='world')) for obj in surfObjs: assert(isinstance(obj, pm.nodetypes.NurbsSurface)) result[obj] = [] for u in range(obj.numCVsInU()): for v in range(obj.numCVsInV()): result[obj].append(pm.xform(obj.cv[u][v], q=True, ws=ws, t=True)) return result
def ChangeNumberOfJoints(self, *args): self.blueprint_UI_instance.DeleteScriptJob() # Collect information from current spline module joints = self.GetJoints() numJoints = len(joints) newNumJoints = pm.intField(self.numberOfJointsField, query = True, value = True) startPos = pm.xform(self.GetTranslationControl(joints[0]), query = True, worldSpace = True, translation = True) endPos = pm.xform(self.GetTranslationControl(joints[numJoints - 1]), query = True, worldSpace = True, translation = True) hookObj = self.FindHookObjectForLock() rotateOrder = pm.getAttr("%s.rotateOrder" %joints[0]) sao_local = pm.getAttr("%s:module_grp.sao_local" %self.moduleNamespace) sao_world = pm.getAttr("%s:module_grp.sao_world" %self.moduleNamespace) # Delete current spline module self.Delete() # Create new spline module with new joint count newInstance = Spline(self.userSpecifiedName, hookObj, newNumJoints, startPos, endPos) newInstance.Install() # Apply previous attribute values newJoints = newInstance.GetJoints() pm.setAttr("%s.rotateOrder" %newJoints[0], rotateOrder) pm.setAttr("%s:module_grp.sao_local" %newInstance.moduleNamespace, sao_local) pm.setAttr("%s:module_grp.sao_world" %newInstance.moduleNamespace, sao_world) self.blueprint_UI_instance.CreateScriptJob() pm.select("%s:module_transform" %newInstance.moduleNamespace, replace = True)
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 generate( self, size = 10, iterations = 1, grid = 3, holes = [ 4, 10, 12, 13, 14, 16, 22 ] ): self.size = size self.iterations = iterations self.grid = grid self.holes = holes print( "%s radius %f iterations %i" % ( self.__class__.__name__, self.size, self.iterations ) ) cubeSize = float(self.size) / util.pow( float(self.grid), float(self.iterations) ) cube = self.mesh( width = cubeSize, height = cubeSize, depth = cubeSize ) cubes = [ cube ] for i in range( iterations ): mesh = self.__generateMesh( cubes[ 0 ], cubeSize, ( i + 1 ) ) cubeSize = cubeSize * self.grid cubes = [ mesh ] pm.xform( mesh[ 0 ], centerPivots = True ) print( "Construction complete" ) return mesh
def createLight(self, position): value = self.distance_float.value() if self.lightType_menu.currentIndex() == 1: light = pm.shadingNode('areaLight', asLight=True) pm.setAttr(light + '.intensity', 500) pm.setAttr(light + '.decayRate', 2) pm.setAttr(light + '.areaLight', 1) elif self.lightType_menu.currentIndex() == 2: light = pm.shadingNode('spotLight', asLight=True) pm.setAttr(light + '.intensity', 500) pm.setAttr(light + '.decayRate', 2) elif self.lightType_menu.currentIndex() == 3: light = pm.shadingNode('directionalLight', asLight=True) elif self.lightType_menu.currentIndex() == 4: light = pm.shadingNode('pointLight', asLight=True) pm.setAttr(light + '.intensity', 500) pm.setAttr(light + '.decayRate', 2) pm.rename(light, light_name) pm.xform(light, a=True, t=position) pm.xform(light, r=True, t=(0, 0, value)) return light
def mirror_nurb(patches, negative_x=True, reverse=False): """ Args: patches (pm.nt.Transform): nurbsies negative_x (bool): mirror from +x => -x or vice versa Usage: mirror_nurb(pm.ls(sl=True, type='transform'), negative_x=True, reverse=False) """ for patch in patches: shape = patch.getShape() cvu, cvv = shape.numCVsInU(), shape.numCVsInV() if reverse: cvu, cvv = shape.numCVsInV(), shape.numCVsInU() for column in range(cvv): even_odd = cvu % 2 for row in range(cvu/2): if negative_x: row_mirrored = row row = (row*-1) - 1 else: row_mirrored = (row*-1) - 1 pos = pm.xform(shape.cv[row][column], q=True,ws=True,t=True) pos_mirrored = [a*b for a,b in zip(pos, [-1,1,1])] pm.xform(shape.cv[row_mirrored][column], t=pos_mirrored, ws=True)
def matrixDisplay(o, ws=False): if isinstance(o, PyNode): m = xform(o, q=True, ws=ws, m=True) elif isinstance(o, dt.Matrix): m = list(o[0]) + list(o[1]) + list(o[2]) + list(o[3]) else: m = o print('[' + ', '.join([numf(n) for n in m[0:4]]) + ']') print('[' + ', '.join([numf(n) for n in m[4:8]]) + ']') print('[' + ', '.join([numf(n) for n in m[8:12]]) + ']') print('[' + ', '.join([numf(n) for n in m[12:16]]) + ']')
def joint_rotation(joints): ''' Checks through given joints for rotation values. Arguments: joints - list of joints to check. ''' invalid_joints = [] for joint in joints: rotation_values = pm.xform(joint, q=1, rotation=True) if rotation_values[0] != 0 or rotation_values[1] != 0 or rotation_values[2] != 0: invalid_joints.append(joint) return invalid_joints
def locatorOnCurveCVs(size=1, crv=None, prefix="lid"): locs = [] for i,cv in enumerate(crv.cv): pm.select( clear=1 ) cvPose = pm.xform( cv, q=1, t=1, ws=1 ) locs.append( pm.spaceLocator(name="%s_%s_loc"%(prefix,i)) ) locs[i].translate.set( cvPose ) locs[i].localScale.set(size,size,size) pm.delete( (locs[1],locs[-2]) ) locs.remove( locs[1] ) locs.remove( locs[-2] ) return(locs)
def clicked_guess_joint_side(self): # Set the side of a joint based on its X position. # # This is a quick way to set the side of joints. A good policy is # to label joints on the YZ plane as center joints, joints with mirrored # left and right counterparts as left and right, and joints that aren't # in the center but which aren't mirrored as having no side. This # doesn't do any mirror matching and just looks at the X position. for joint in pm.ls(sl=True, type='joint'): pos = pm.xform(joint, q=True, ws=True, t=True) side = 2 if pos[0] < -0.1 else 1 if pos[0] > 0.1 else 0 joint.side.set(side)
def assertLocationIs(obj=None, pos=None): '''Assert obj is located at position pos Attributes: obj -- Object to check. (pm.nt.Transform, pm.nt.Joint) pos -- pm.dt.Point=(x, y, z) ''' general.check_type(obj, 'obj', [pm.nt.Transform]) general.check_type(pos, 'pos', [pm.dt.Point]) return general.assertAlmostEquals( pm.dt.Point(pm.xform(obj, q=1, ws=1, t=1)), pos, 3)
def rightFingerToLeft(mayaFalse): rFingers = pm.listRelatives('*Character1_Ctrl_RightHand', ad=True) lFingers = pm.listRelatives('*Character1_Ctrl_LeftHand', ad=True) counter = 0 for i in rFingers: if i.find('Thumb') != -1: pm.xform(lFingers[counter], rotation=[ -1 * pm.getAttr(i.rx), pm.getAttr(i.ry), -1 * pm.getAttr(i.rz) ]) else: pm.xform(lFingers[counter], rotation=[ -1 * pm.getAttr(i.rx), -1 * pm.getAttr(i.ry), pm.getAttr(i.rz) ]) pm.setKeyframe(lFingers[counter], attribute=['rotateX', 'rotateY', 'rotateZ']) counter += 1
def wrapper(self, *args, **kws): control = func(self, *args, **kws) self.setColor(control) control.setTranslation(self.offset, 'world') pm.makeIdentity(control, apply=True) log.info('Control of type:{} name {} created along {}'.format( func.__name__, control.name(), self._axis)) if self.groupControl: Gp = pm.nt.Transform(name=self.name + 'Gp') control.setParent(Gp) self.controlGps.append(Gp) else: pm.xform(control, pivots=(0, 0, 0), ws=True, dph=True, ztp=True) if self.forceSetAxis: self.setAxis(control, self.axis) return control
def sanity_check_eyes(joints): pos = [pm.xform(node, q=True, ws=True, t=True) for node in joints] # We expect the character to be in the standard orientation: Y-up, facing up Z. Sanity check that # the eyes are somewhere up Y. if pos[0][1] <= 0 or pos[1][1] <= 0: log.error('The selected objects should be on positive Y.') return False # Check that the eyes are parallel on the X axis. if abs(pos[0][1] - pos[1][1]) > 0.001 or abs(pos[0][2] - pos[1][2]) > 0.001: log.warning('Warning: the selected objects aren\'t parallel on the X axis.') return True
def jointOnCurveCVs(size=1, crv=None, prefix="lid"): jnts = [] for i,cv in enumerate(crv.cv): pm.select( clear=1 ) cvPose = pm.xform( cv, q=1, t=1, ws=1 ) jnts.append( pm.joint(p=cvPose, name="%s_%s_jnt"%(prefix,i)) ) jnts[i].radius.set( size ) pm.joint( jnts[i], e=True, oj="xyz", sao="yup", zso=1, ch=1 ) pm.delete( (jnts[1],jnts[-2]) ) jnts.remove( jnts[1] ) jnts.remove( jnts[-2] ) return jnts
def onAWire4(self, locs, crv): locs = pm.listRelatives(locs, children=True, type="transform") crv = crv for x in locs: pos = pm.xform(x, q=1, ws=1, t=1) u = getUParam(pos, crv) #create point on curve node. Make sure Locators have suffix of _LOX name = x.replace("_LOC", "_PCI") pci = pm.createNode("pointOnCurveInfo", n=name) pm.connectAttr(crv + ".worldSpace", pci + ".inputCurve") pm.setAttr(pci + ".parameter", u) pm.connectAttr(pci + ".position", x + ".t")
def alignToMatcher(ctrl): try: matcher = getMatcher(ctrl) xform(ctrl, ws=True, t=xform(matcher, q=True, ws=True, t=True)) xform(ctrl, ws=True, ro=xform(matcher, q=True, ws=True, ro=True)) except Exception: warning('{0} does not have a matcher setup'.format(ctrl))
def alignToMatcher(ctrl): try: matcher = ctrl.matcher.listConnections()[0] xform(ctrl, ws=True, t=xform(matcher, q=True, ws=True, t=True)) xform(ctrl, ws=True, ro=xform(matcher, q=True, ws=True, ro=True)) except Exception: warning('{0} does not have a matcher setup'.format(ctrl))
def rigMake(mayaFalse): #check if not pm.ls( 'Locator_Pivot' ): #first, perform a check to see if locatorMake() has been performed. pm.confirmDialog(title=u'SER 武器リグ', message=u'先ず、ピボット設定をしてください。') return #rest of rig start constrLoc = pm.spaceLocator( name="Locator_Constraint") #creating locator to constraint the bone to weapJoint = pm.ls('*Joint_Weapon', type='joint')[0] pm.xform( constrLoc, ws=True, t=pm.xform(weapJoint, q=True, t=True, ws=True) ) #moving the newly created constraint locator to the translation position of the joint pm.parentConstraint(constrLoc, weapJoint, mo=False) contr1 = pm.circle(name='Controller_Weapon_Global', r=9, nr=[0, 1, 0]) contr2 = pm.circle(name='Controller_Weapon_Local', r=7, nr=[0, 1, 0]) pm.parent(contr2[0], contr1[0]) pm.xform(contr1, ws=True, t=pm.xform('Locator_Pivot', q=True, t=True, ws=True), ro=pm.xform('Locator_Pivot', q=True, ro=True, ws=True)) pm.delete( 'Locator_Pivot' ) #deleting locator pivot after rig controllers have been created. pm.parent(constrLoc, contr2[0]) R_Constr = pm.parentConstraint( pm.ls('*Helper_Weapon1')[0], contr1[0], name='Constraint_Weapon_Global') #parent constraint to right hand L_Constr = pm.parentConstraint(pm.ls('*Helper_Weapon2')[0], contr1[0]) #parent constraint to left hand pm.setAttr( 'Constraint_Weapon_Global.%s' % pm.listAttr('Constraint_Weapon_Global', k=True)[-1], 0) pm.setKeyframe('Controller_Weapon_Global') pm.setKeyframe('Controller_Weapon_Global', v=1, at='blendWeaponGlobal', itt='auto', ott='step') pm.setKeyframe('Constraint_Weapon_Global', v=1, at=pm.listAttr('Constraint_Weapon_Global', k=True)[-2]) #sets RH constraint to 1 pm.setKeyframe('Constraint_Weapon_Global', v=0, at=pm.listAttr('Constraint_Weapon_Global', k=True)[-1]) #sets LH constraint to 0
def animSave(_): output = [] for frame in range(int(animAPI.MAnimControl.maxTime().value() + 1)): pm.currentTime(frame) line = '' for i in pm.listRelatives( pm.ls(sl=True), ad=True, type='joint' ): # remove ", type = 'joint'" for control rig version if str( pm.listRelatives(i, parent=True) ) == "[nt.Joint(u'Character_Head')]" or str( pm.listRelatives(i, parent=True) ) == "[nt.Joint(u'Helper_Weapon2')]" or str( pm.listRelatives(i, parent=True) ) == "[nt.Joint(u'Helper_Weapon1')]" or i[:5] == 'Joint': continue if pm.objectType(i) == "locator": continue line = line + str(int(pm.currentTime( ))) + ' ' + i + ' ' + str( pm.xform(i, q=True, translation=True)) + ' ' + str( pm.xform(i, q=True, rotation=True)) + ' ' + str( pm.xform(i, q=True, scale=True, relative=True)) line = line.replace('[', '') line = line.replace(']', '') line = line.replace(',', '') line output.append(line) line = '' # writing pose into data defPose = open( r'\\p.sv\Prism\project\SER\user\chew\ref\animPose\taiso.pose', 'w') for i in output: defPose.write(i) defPose.write('\n') defPose.close() pass
def handSetup(leftArm, numFingers, makeThumb): #hand = Container('Hand', meters(0.20, 0.20) ) hand = makeCard(1, 'Hand', size=meters(0.20, 0.20)) # It makes sense that the wrist is oriented to the hand leftArm.end().customUp = hand.getUpArrow() placeJoints(hand, [(0, -.7)]) hand.joints[0].isHelper = True leftArm.end().orientTarget = hand.joints[0] hand.joints[0].setBPParent(leftArm.end()) xform(hand, ws=True, t=xform(leftArm.end(), q=True, ws=True, t=True)) moveCard.down(hand, meters(.1)) #hand.setParent( leftArm.end() ) xform(hand, ws=True, piv=xform(leftArm.end(), q=True, ws=True, t=True)) pointConstraint(leftArm.end(), core.dagObj.zero(hand), mo=True) [hand.attr('t' + a).lock() for a in 'xyz'] mod = 0.15 / (numFingers - 1) if numFingers > 1 else 0 for i, finger in enumerate(['Index', 'Middle', 'Ring', 'Pinky'][:numFingers]): card = makeCard(4, finger + '*', suffix='L') moveCard.to(card, leftArm.end()) moveCard.backward(card, meters(i * mod - 0.1)) moveCard.down(card, meters(0.20)) grp = group(card, n=finger + "_grp") card.setParent(grp) parentConstraint(hand, grp, mo=True) card.ry.set(90) card.joints[-1].isHelper = True #proxy.pointer( leftArm.end(), card.start() ) card.start().setBPParent(leftArm.end()) card.rigCommand = 'RotateChain' card.rigOptions = '-size 2 -visGroup fingers' if makeThumb: thumb = makeCard(4, 'Thumb*', suffix='L') moveCard.to(thumb, leftArm.end()) thumb.ry.set(-90) moveCard.to(thumb, leftArm.end()) moveCard.forward(thumb, meters(0.1)) moveCard.down(thumb, meters(0.1)) moveCard.closer(thumb, meters(0.05)) thumb.end().isHelper = True grp = group(thumb, n="Thumb_grp") parentConstraint(hand, grp, mo=True) #proxy.pointer( leftArm.end(), thumb.start() ) thumb.start().setBPParent(leftArm.end()) thumb.rigCommand = 'RotateChain' thumb.rigOptions = '-size 2 -visGroup fingers'
def toggle_pivot_positions(obj_list): last_obj = obj_list[-1] # selects last obj of list pivot = pm.xform(last_obj, q=True, rp=True, ws=True) state = next_pivot_state( last_obj) # Gets the next state for last selected obj for obj in obj_list: bbox = pm.xform(obj, q=True, ws=True, bb=True) center = [(bbox[0] + bbox[3]) / 2, (bbox[1] + bbox[4]) / 2, (bbox[2] + bbox[5]) / 2] bottom = [(bbox[0] + bbox[3]) / 2, bbox[1], (bbox[2] + bbox[5]) / 2] for i in range(0, 3): pivot[i] = round(pivot[i], 4) center[i] = round(center[i], 4) bottom[i] = round(bottom[i], 4) # Setting the pivot to match whatever state the last selected obj has if state == "origo": new_sel = pm.ls(obj) pm.move(0, 0, 0, (new_sel[0] + ".scalePivot"), (new_sel[0] + ".rotatePivot"), absolute=True) # Sets pivot to origo if state == "bottom": pm.xform(obj, piv=bottom, ws=True, absolute=True) # Sets pivot to bottom of Bounding Box if state == "center": pm.xform(obj, piv=center, ws=True, absolute=True) # Sets pivot to center pm.select(obj_list)
def scaleCtrlShapes(*args, **kwargs): """ Scale ctrl shapes and set line width :param args: Transform nodes to change :param kwargs: scale_mult | s: amount to scale ctrl curve, default 1 line_width | lw: line width thickness, ignores if not specified """ scale_mult = kwargs.pop('scale_mult', kwargs.pop('s', 1)) line_width = kwargs.pop('line_width', kwargs.pop('lw', None)) if kwargs: raise ValueError('--Unknown argument: {}'.format(kwargs)) ctrl_ls = makePyNodeList(args) for ctrl in ctrl_ls: shapes = ctrl.getChildren() if ctrl.nodeType() == 'nurbsCurve': shapes.append(ctrl) for shape in shapes: if 'nurbsCurve' in shape.nodeType(): curv_type = pm.getAttr('%s.form' % shape) # if curve open get curve points if curv_type == 0: num_cv = pm.getAttr('%s.cp' % shape, s=1) # else curve must be closed so get spans else: num_cv = pm.getAttr('%s.spans' % shape) for i in xrange(num_cv): cv_ws = pm.xform('{}.cv[{}]'.format(shape, i), t=True, q=True) pm.xform('{}.cv[{}]'.format(shape, i), t=[(cv_ws[0] * scale_mult), (cv_ws[1] * scale_mult), (cv_ws[2] * scale_mult)]) if line_width: shape.lineWidth.set(line_width)
def doRig(self): if not self.guideMoveall: self.doGuide() if pm.objExists(self.name + 'Moveall'): pm.delete(self.name + 'Moveall') self.drvGrp = pm.group(em=True, n=self.name + 'Sys_grp') self.drvGrp.visibility.set(False) self.cntrlGrp = pm.group(em=True, n=self.name + 'Ctrls_grp') self.moveall = pm.group(self.cntrlGrp, n=self.name + 'Constrained') self.cntrlList = [] for i in range(self.num): pm.select(cl=True) jnt = pm.joint(n=self.name + str(i + 1) + self.jntPrefix) pos = pm.xform(self.guideList[i], q=True, ws=True, t=True) pm.xform(jnt, ws=True, t=pos) drvName = self.drvSetup['nameTempl'] + str(i + 1) + '_drv' drv = controlTools.cntrlCrv(name=drvName, obj=jnt, connType='parent', **self.drvSetup) cntrlName = self.ctrlSetup['nameTempl'] + str(i + 1) cntrl = controlTools.cntrlCrv(name=cntrlName, obj=drv, connType='connection', offsets=1, **self.ctrlSetup) if self.hasMulti: mlt = pm.createNode('multiplyDivide') mlt.input2.set([-1, -1, -1]) cntrl.translate >> mlt.input1 mlt.output >> cntrl.getParent().translate self.cntrlList.append(cntrl) cntrl.getParent(2).setParent(self.cntrlGrp) drv.getParent().setParent(self.drvGrp)
def active_splineChest(cls, chestCtrl): ''' .. todo:: Implement even number of stomach joints ''' cls.alignToMatcher(chestCtrl) midJnt = chestCtrl.subControl['mid'].listRelatives(type='joint')[0] skin = listConnections(midJnt, type='skinCluster') curveShape = skin[0].outputGeometry[0].listConnections( p=True)[0].node() ikHandle = curveShape.worldSpace.listConnections(type='ikHandle')[0] chain = getChainFromIk(ikHandle) boundJoints = getConstraineeChain(chain) if len(boundJoints) % 2 == 1: switch_logger.debug('Mid point ODD moved, # bound = {}'.format( len(boundJoints))) i = int(len(boundJoints) / 2) + 1 xform(chestCtrl.subControl['mid'], ws=True, t=xform(boundJoints[i], q=True, ws=True, t=True)) else: i = int(len(boundJoints) / 2) xform(chestCtrl.subControl['mid'], ws=True, t=xform(boundJoints[i], q=True, ws=True, t=True)) switch_logger.debug('Mid point EVEN moved, # bound = {}'.format( len(boundJoints)))
def vecViz(vector, startTranform=[0,0,0], name="vecViz"): ''' Crates cone represenatation of vector between start and endpoint Args: vector: tfm: name: Returns: ''' """Visual aid for Vectors""" startPoint = om.MVector(startTranform[0], startTranform[1], startTranform[2]) endPoint = vector vec = vector loc = pm.spaceLocator(n=name) #cone for visulization height = vec.length() #pivot of cone is in center. for nicer look we shift it to base pointer = pm.polyCone(name=name+'_pointer', sx=4, r=0.25, h=height)[0] pm.xform(pointer, piv=(0,(-1*height/2),0), t=(0,(height/2),0),ro=(0,0,-90), os=1) pm.makeIdentity(pointer, a=1) #move locator to vector and cone to tfm loc.setTranslation(endPoint) #aim constrain cone to look at locator pm.delete(pm.aimConstraint(loc,pointer,aimVector=(1,0,0), mo=0)) # clean up pm.parent(loc,pointer) pointer.setTranslation(startPoint) return pointer
def set_pivot(cls, axis=0): """moves the object pivot to desired axis There are 7 options to move the pivot point to: c, -x, +x, -y, +y, -z, +z 0, 1, 2, 3, 4, 5, 6 :param int axis: One of [0-6] showing the desired axis to get the pivot point to """ from maya.OpenMaya import MBoundingBox, MPoint if not 0 <= axis <= 6: return for node in pm.ls(sl=1): # check if the node has children children = pm.ls(sl=1)[0].getChildren(ad=1, type='transform') # get the bounding box points # bbox = node.boundingBox() bbox = pm.xform(node, q=1, ws=1, boundingBox=1) bbox = MBoundingBox( MPoint(bbox[0], bbox[1], bbox[2]), MPoint(bbox[3], bbox[4], bbox[5]) ) if len(children): # get all the bounding boxes for child in children: if child.getShape() is not None: # child_bbox = child.boundingBox() child_bbox = pm.xform(child, q=1, ws=1, boundingBox=1) child_bbox = MBoundingBox( MPoint(child_bbox[0], child_bbox[1], child_bbox[2]), MPoint(child_bbox[3], child_bbox[4], child_bbox[5]) ) bbox.expand(child_bbox.min()) bbox.expand(child_bbox.max()) piv = bbox.center() if axis == 1: # -x piv.x = bbox.min().x elif axis == 2: # +x piv.x = bbox.max().x elif axis == 3: # -y piv.y = bbox.min().y elif axis == 4: # +y piv.y = bbox.max().y elif axis == 5: # -z piv.z = bbox.min().z elif axis == 6: # +z piv.z = bbox.max().z pm.xform(node, ws=1, rp=piv) pm.xform(node, ws=1, sp=piv)
def placement(self): grp2 = pm.ls("*offSet*") fols = pm.ls("*_fol") for num, fol in enumerate(fols): pos = pm.xform(fol, q=1, ws=1, t=True) oldName = fol.split("_") newName = oldName[0] + "_" + oldName[1] + "_" ctl = self.fControl(newName, num) pm.xform(grp2, ws=1, t=pos) loc = pm.spaceLocator(n="loc_{}".format(num)) pm.setAttr(loc + ".visibility", 0) pm.xform(loc, ws=1, t=pos) pm.pointConstraint(fol, loc) pm.orientConstraint(fol, loc) ctls = pm.ls("*fCTL", type="transform") for x in ctls: pm.transformLimits(x, tx=(-1, 1), etx=(1, 0)) pm.transformLimits(x, tx=(-1, 1), etx=(1, 1)) pm.transformLimits(x, ty=(-1, 1), ety=(1, 0)) pm.transformLimits(x, ty=(-1, 1), ety=(1, 1)) #if: #pm.transformLimits(x, ty=(-1,1), ety=(1,0)) #pm.transformLimits(x, ty=(-1,1), ety=(1,1)) grp3 = pm.ls("*woldSpace*", type="transform") locs = pm.ls("loc_?", "loc_??", type="transform") for x, y in sorted(zip(grp3, locs)): pm.parent(y, x) grp2 = pm.ls("*offSet*") for x, y in sorted(zip(grp2, locs)): pm.connectAttr(y + ".translate", x + ".translate", force=True) pm.connectAttr(y + ".rotate", x + ".rotate", force=True) #for x in grp2: #pm.delete(pm.normalConstraint("C_body_PLY", x, weight=1, aimVector=[0,0,1], upVector=[0,1,0], worldUpType="vector", worldUpVector=[0,1,0])) #grp = #for x in grp: #pm.orientConstraint("C_body_PLY", x, mo=True) pm.group(grp3, name="bsMan_faceRig_low_control_GRP")
def create_ik_fk_arm(): result_joints = pm.ls(sl=True) appendage_name = pm.textField("appendage_name_input", q=True, text=True) name_prefixes = get_name_prefixes(result_joints) # Create FK Joints and Controls fk_icon = pm.optionMenu("fk_icon_menu", query=True, value=True) fk_color = pm.optionMenu("fk_color_menu", query=True, value=True) fk_scale_list = [] for fk_curve in pm.listRelatives("FK_Icons_DO_NOT_DELETE_GRP"): fk_scale_list.append( pm.xform(fk_curve, query=True, worldSpace=True, scale=True)) fk_joints = attach_fk_to_joints(result_joints, fk_icon, fk_color, fk_scale_list) # Create IK Joints and Controls ik_icon = pm.optionMenu("ik_icon_menu", query=True, value=True) ik_color = pm.optionMenu("ik_color_menu", query=True, value=True) ik_icon_scale = pm.xform("IK_Test_CRV", query=True, worldSpace=True, scale=True) pv_icon = pm.optionMenu("pv_icon_menu", query=True, value=True) pv_pos = pm.xform("PV_Test_CRV", query=True, worldSpace=True, translation=True) pv_icon_scale = pm.xform("PV_Test_CRV", query=True, worldSpace=True, scale=True) ik_joints = attach_ik_to_joints(result_joints, appendage_name, name_prefixes[1], ik_icon, pv_icon, ik_color, pv_pos, ik_icon_scale, pv_icon_scale) blend_nodes = attach_fk_ik_to_blend_to_result(fk_joints, ik_joints, result_joints, name_prefixes) settings_icon = pm.optionMenu("settings_icon_menu", query=True, value=True) settings_color = pm.optionMenu("settings_color_menu", query=True, value=True) settings_pos = pm.xform("Settings_Test_CRV", query=True, worldSpace=True, translation=True) settings_icon_scale = pm.xform("Settings_Test_CRV", query=True, worldSpace=True, scale=True) settings_control = create_fk_ik_settings_control( appendage_name, name_prefixes[1], result_joints, blend_nodes, fk_joints, settings_icon, settings_color, settings_pos, settings_icon_scale) parent_joints_to_groups(appendage_name, name_prefixes, result_joints, fk_joints, ik_joints, settings_control) pm.delete("Test_Icons_DO_NOT_DELETE_GRP") pm.deleteUI(new_window)
def duplicate_selected_reference(cls): """duplicates the selected referenced object as reference """ all_selected_refs = [] for sel_node in pm.ls(sl=1): ref = sel_node.referenceFile() if ref not in all_selected_refs: all_selected_refs.append(ref) select_list = [] for ref in all_selected_refs: # get the highest parent ref if ref.parent(): while ref.parent(): ref = ref.parent() namespace = ref.namespace dup_ref = pm.createReference( ref.path, gl=True, namespace=namespace, options='v=0' ) top_parent = cls.get_no_parent_transform(ref) if top_parent: node = top_parent tra = pm.xform(node, q=1, ws=1, t=1) rot = pm.xform(node, q=1, ws=1, ro=1) sca = pm.xform(node, q=1, ws=1, s=1) new_top_parent_node = cls.get_no_parent_transform(dup_ref) pm.xform(new_top_parent_node, ws=1, t=tra) pm.xform(new_top_parent_node, ws=1, ro=rot) pm.xform(new_top_parent_node, ws=1, s=sca) # parent to the same group group = node.getParent() if group: pm.parent(new_top_parent_node, group) # select the top node select_list.append(new_top_parent_node) pm.select(select_list) return select_list
def connectStereoCameras(camera, stereo_cams, base_percent=0.7, interactive=False, threshod=0.001): if not pm.objExists(camera): print 'The given center camera does not exists: '+str(camera) return else: camera = pm.PyNode(camera) if not isinstance(stereo_cams, type([])): stereo_cams = [stereo_cams] stereoCameras = {} for s in stereo_cams: s = pm.PyNode(s) # constrain stereo camera to main camera pm.pointConstraint(camera, s, offset=(0,0,0), weight=1) pm.orientConstraint(camera, s, offset=(0,0,0), weight=1) # local pivot alignment rot_local = pm.xform(camera, query=True, os=True, rp=True) scale_local = pm.xform(camera, query=True, os=True, sp=True) local_pivot_bool = False for v in rot_local: if math.fabs(v) >= threshod: local_pivot_bool = True pm.xform(s, os=True, rp=tuple(rot_local)) break for v in scale_local: if math.fabs(v) >= threshod: local_pivot_bool = True pm.xform(s, os=True, sp=tuple(scale_local)) break if interactive and local_pivot_bool: pm.confirmDialog(title='Warning', message='Found non-zero value on local pivot attribute of camera!', button='OK', defaultButton='OK', cancelButton='OK', dismissString='OK') # connect attributes of cameras for a in ['focalLength', 'horizontalFilmAperture', 'verticalFilmAperture']: camera.attr(a) >> s.attr(a) try: filmFit = camera.attr('filmFit').get() if filmFit==0: filmFit = 1 camera.attr('filmFit').set(filmFit) s.attr('filmFit').set(filmFit) s.getShape().attr('stereo').set(2) s.getShape().attr('displayResolution').set(0) except: print traceback.format_exc() # create safe plane planes = createStereoSafePlanes(s) # add roundness ratio addRoundnessRatio(planes['safePlane'], planes['convergePlane']) stereoCameras.update( {s:{'camera':camera, 'safePlane':planes['safePlane'], 'convergePlane':planes['convergePlane'], 'node':s}} ) return stereoCameras
def _setValuesFromGuideData(cls, guide, data, idMap=None): pm.xform(guide.transform, translation=data["translation"], worldSpace=True) pm.xform(guide.transform, rotation=data["rotation"], worldSpace=True) pm.xform(guide.transform, scale=data["scale"], worldSpace=True) guide.setHandleColor(data.get("handleColor", (0.0, 0.0, 0.0)))
def resetDynamicPivot(pivot_control, key=True, rest=False): """ Resets the position of the dynamic pivot. Maintains world position of control driven by pivot. Args: pivot_control (pm.nodetypes.Transform): Pivot control that needs to be reset to zero position. key (boolean): If True, will key the pivot and parent control on the previous frame. rest (boolean): If True, will move pivot to the rest position. """ parent = pivot_control.getParent() matrix = parent.worldMatrix.get() rest_matrix = pm.PyNode(pivot_control.attr( pcfg.dynamic_pivot_rest).get()).worldMatrix.get() if key: current_frame = pm.currentTime(q=True) pm.setKeyframe(pivot_control, time=current_frame - 1) pm.setKeyframe(parent, time=current_frame - 1) pm.xform(pivot_control, ws=True, m=rest_matrix) if rest else mayamath.zeroOut(pivot_control) pm.xform(parent, ws=True, m=matrix) pm.xform(parent, ws=True, m=matrix) # called twice because Maya is stupid
def match_macro(source): if source.hasAttr('controller'): try: #joint_target = uf.meta_traverse(source = source, relation = 'child', tag = 'jointSkin')[0] control_grp = pm.ls(str(source).replace('_CTL','_GRP'))[0] child_controls = uf.meta_traverse(source = source, relation = 'child', tag = 'jointSkin')[0] target_locator = uf.nest_transform(name = str(source)+ '_target_position', action = 'child', target = source, transformObj = 'locator', transformRadius = 1.0) pm.parent(target_locator, world = True) brow_position = uf.average_position(*brow_controls) offset_joint = pm.joint(name = str(brow_main_control)+ '_offset_thing', relative = False, radius = 2, position = brow_position) pm.parent(offset_joint, world = True) offset_joint | target_locator except: pm.warning('problem finding target location') try: for micro_controller in brow_controls: joint_target_list = joint_target_list+ [uf.meta_traverse(source = control_object, relation = 'child', tag = 'jointSkin')[0]] final_position = uf.average_position(*joint_target_list) pm.xform(offset_joint, translation = final_position, worldSpace = True) pm.matchTransform(brow_main_grp, target_position, pos = True, rot = False, scale = False) pm.delete(offset_joint) pass except: pm.warning('problem finding target location') try: pm.delete(source, constraints = 1) pm.matchTransform(control_grp, joint_target, pos = True, rot = True, scale = False) except: pm.warning('failed to matchTransform') if '_R_' in str(control_object): pm.xform(control_object, euler = True, rotation = [0,0,180]) else: pass elif source.hasAttr('controller'): pass else: pm.warning('no controller or microController attr') pass pass
def hookJntsOnCurve(self, jntList, upList, jntCrv, upCrv): jntNPoC = pm.createNode('nearestPointOnCurve', n=self.name+'NPCjnt') jntGrpA = pm.group(empty=True, n=self.name + 'jntGrp') jntCrv.worldSpace[0] >> jntNPoC.inputCurve jntGrpA.translate >> jntNPoC.inPosition upNPoC = pm.createNode('nearestPointOnCurve', n=self.name+'NPCup') upGrpA = pm.group(empty=True, n=self.name + 'upGrpA') upCrv.worldSpace[0] >> upNPoC.inputCurve upGrpA.translate >> upNPoC.inPosition for jnt, up in zip(jntList, upList): wp = pm.xform(jnt, t=True, ws=True, q=True) pm.xform(jntGrpA, t=wp, ws=True) hookPoci = pm.createNode('pointOnCurveInfo', n=self.name+'CurveInfoA') jntCrv.worldSpace[0] >> hookPoci.inputCurve hookPoci.position >> jnt.translate hookPar = jntNPoC.parameter.get() hookPoci.parameter.set(hookPar) pm.tangentConstraint(jntCrv, jnt, aimVector=(-1, 0, 0), upVector=(0, 1, 0), worldUpType="object", worldUpObject=up) wp = pm.xform(up, t=True, ws=True, q=True) pm.xform(upGrpA, t=wp, ws=True) hookPoci = pm.createNode('pointOnCurveInfo', n=self.name+'CurveInfoB') upCrv.worldSpace[0] >> hookPoci.inputCurve hookPoci.position >> up.translate hookPar = upNPoC.parameter.get() hookPoci.parameter.set(hookPar) pm.delete(upNPoC, upGrpA, jntNPoC, jntGrpA)
def getDict(self): try: guideName = self.moveallGuideSetup['nameTempl'] + self.guideSulfix self.guideMoveall = pm.PyNode(guideName) jsonDict = self.guideMoveall.spineDict.get() dictRestored = json.loads(jsonDict) self.__dict__.update(**dictRestored) self.guideDict['moveall'][0] = self.guideMoveall.getTranslation( space='world').get() self.guideDict['moveall'][1] = tuple( self.guideMoveall.getRotation(space='object')) self.guideDict['moveall'][2] = tuple( pm.xform(self.guideMoveall, q=True, s=True, ws=True)) guideName = self.startGuideSetup['nameTempl'] + self.guideSulfix self.startGuide = pm.PyNode(guideName) self.guideDict['start'][0] = self.startGuide.getTranslation( space='object').get() self.guideDict['start'][1] = tuple( self.startGuide.getRotation(space='object')) guideName = self.midGuideSetup['nameTempl'] + self.guideSulfix self.midGuide = pm.PyNode(guideName) self.guideDict['mid'][0] = self.midGuide.getTranslation( space='object').get() self.guideDict['mid'][1] = tuple( self.midGuide.getRotation(space='object')) guideName = self.endGuideSetup['nameTempl'] + self.guideSulfix self.endGuide = pm.PyNode(guideName) self.guideDict['end'][0] = self.endGuide.getTranslation( space='object').get() self.guideDict['end'][1] = tuple( self.endGuide.getRotation(space='object')) guideName = self.endTipGuideSetup['nameTempl'] + self.guideSulfix self.endTipGuide = pm.PyNode(guideName) self.guideDict['endTip'][0] = self.endTipGuide.getTranslation( space='object').get() self.guideDict['endTip'][1] = tuple( self.endTipGuide.getRotation(space='object')) guideName = self.startTipGuideSetup['nameTempl'] + self.guideSulfix self.startTipGuide = pm.PyNode(guideName) self.guideDict['startTip'][0] = self.startTipGuide.getTranslation( space='object').get() self.guideDict['startTip'][1] = tuple( self.startTipGuide.getRotation(space='object')) except: pass