Esempio n. 1
0
    def get_parent(self):
        """gets the parent node or creates one
        """
        import pymel.core as pm

        parent_node_name = self.parent_name
        nodes_with_name = pm.ls('|%s' % parent_node_name)
        parent_node = None
        if nodes_with_name:
            parent_node = nodes_with_name[0]

        if not parent_node:
            # create one
            previous_parent = None
            current_node = None
            splits = self.parent_name.split("|")
            for i, node_name in enumerate(splits):
                full_node_name = '|' + '|'.join(splits[:i + 1])
                list_nodes = pm.ls(full_node_name)
                if list_nodes:
                    current_node = list_nodes[0]
                else:
                    current_node = pm.nt.Transform(name=node_name)
                if previous_parent:
                    pm.parent(current_node, previous_parent, r=1)
                previous_parent = current_node

            # parent_node = pm.nt.Transform(name=parent_node_name)
            parent_node = current_node

        return parent_node
 def createUISet(self):
     self._childLayout = pm.columnLayout( adj=True )
     with self._childLayout:
         pm.text(l="Click cage mesh first, then shift+click target mesh, and click the menu item.")
         self.deformers = pm.ls(type="cage")
         for i in range(len(self.deformers)):
             frameLayout = pm.frameLayout( label=self.deformers[i].name(), collapsable = True)
             with frameLayout:
                 with pm.rowLayout(numberOfColumns=3) :
                     pm.button( l="Del", c=pm.Callback( self.deleteNode, self.deformers[i].name()))
                     pm.attrControlGrp( label="cage mode", attribute= self.deformers[i].cgm)
                     pm.attrControlGrp( label="blend mode", attribute= self.deformers[i].bm)
                 with pm.rowLayout(numberOfColumns=3) :
                     pm.attrControlGrp( label="rotation consistency", attribute= self.deformers[i].rc)
                     pm.attrControlGrp( label="Frechet sum", attribute= self.deformers[i].fs)                        
         self.deformers = pm.ls(type="cageARAP")
         for i in range(len(self.deformers)):
             frameLayout = pm.frameLayout( label=self.deformers[i].name(), collapsable = True)
             with frameLayout:
                 with pm.rowLayout(numberOfColumns=4) :
                     pm.button( l="Del", c=pm.Callback( self.deleteNode, self.deformers[i].name()))
                     pm.attrControlGrp( label="cage mode", attribute= self.deformers[i].cgm)
                     pm.attrControlGrp( label="blend mode", attribute= self.deformers[i].bm)
                     pm.attrControlGrp( label="constraint mode", attribute= self.deformers[i].constraintMode)
                 with pm.rowLayout(numberOfColumns=3) :
                     pm.attrControlGrp( label="rotation consistency", attribute= self.deformers[i].rc)
                     pm.attrControlGrp( label="Frechet sum", attribute= self.deformers[i].fs)                        
                     pm.attrControlGrp( label="constraint weight", attribute= self.deformers[i].constraintWeight)
Esempio n. 3
0
def pymelList(inout, args):
    if args==[]: pm.error('pymelList passed an empty list as args...exiting')
    # inout 0 : given a string returns a List of 2 of [list of PyNode from a space separated string, list of objects that don't exist as strings]
    # inout 1 : given a list returns a string of pynodes.name() in a space separated string
    if inout:
        pymelListStr=''
        for node in args:
            if isinstance (node, basestring): pymelListStr+=node+' '
            else: pymelListStr+=node.name() + ' '
        return pymelListStr
    else:
        #print 'object list is '+args
        pymelListStrList=[]
        pymelListNotExist=[]
        if args.split(' ')[:-1]==[]: objects=[args]
        else: objects = args.split(' ')
        
        for object in objects:
            #print 'running for '+object
            if pm.ls(object,r=True)!=[]:
                #print 'object: %s exists, adding to existing list' % object
                pymelListStrList.append(pm.PyNode(pm.ls(object,r=True)[0]))
            else:
                #print 'object: %s doesn\'t exist, adding to create list' % object
                pymelListNotExist.append(object)
        return [pymelListStrList, pymelListNotExist]
Esempio n. 4
0
def blend_search_and_create ( find_string, replace_string, blend_suffix = 'main_BS', double_namespace=False ):
	'''creates a blendshape between selected objects and targets based on find/replace strings and turns on
	:param find_string: string to find in the name of the transform.name()
	:type find_string: str or unicode
	:param replace_string: string to find in the name of the transform.name()
	:type find_string: str or unicode
	:param blend_suffix: suffix for blendshapes that are created
	:type double_namespace: str or unicode
	:param double_namespace: if we should search mpc style or not
	:type double_namespace: bool
	:rtype : list of pm.PyNode
	:usage :
		blend_search_and_create( 'INPUT', 'GEO', double_namespace=True )
	'''
	blends=[]
	for transform in pm.ls(sl=True):
		namespace = ''
		if double_namespace:
			namespace = '*:*:'
		target = pm.ls( '%s%s'%( namespace, transform.name().replace( find_string, replace_string ) ) )
		blend_name = transform.name().replace( find_string, blend_suffix )
		blend = pm.blendShape(transform, target, n=blend_name, frontOfChain=True)[0]
		blend_aliases = blend.listAliases()
		for blend_alias in blend_aliases:
			blend.attr(blend_alias[0]).set(1)
		blends.append( blend )
	return blends
Esempio n. 5
0
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 createUISet(self):
        self._childLayout = pm.columnLayout( adj=True )
        with self._childLayout:
            pm.text(l="Click cage mesh first, then shift+click target mesh, and click the menu item.")
            # cageDeformer specific
            deformers = pm.ls(type=deformerTypes[0])
            for node in deformers:
                frameLayout = pm.frameLayout( label=node.name(), collapsable = True)
                with frameLayout:
                    self.createCommonAttr(node)

            # cageDeformerARAP specific
            deformers = pm.ls(type=deformerTypes[1])
            for node in deformers:
                frameLayout = pm.frameLayout( label=node.name(), collapsable = True)
                with frameLayout:
                    self.createCommonAttr(node)
                    with pm.rowLayout(numberOfColumns=3) :
                        pm.attrControlGrp( label="constraint mode", attribute= node.ctm)
                        pm.attrFieldSliderGrp( label="constraint weight", min=1e-10, max=1000, attribute=node.cw)
                        pm.attrFieldSliderGrp(label="constraint radius", min=0.001, max=10.0, attribute=node.cr)
                    with pm.rowLayout(numberOfColumns=3) :
                        pm.attrFieldSliderGrp( label="iteration", min=1, max=20, attribute=node.it)
                        pm.attrControlGrp( label="tet mode", attribute= node.tm)
                        pm.attrFieldSliderGrp( label="translation weight", min=0.0, max=1.0, attribute=node.tw)
Esempio n. 7
0
	def setCamera(self):
		pm.mel.eval('setNamedPanelLayout "Single Perspective View"; updateToolbox();')
		sceneReferences = pm.getReferences()
		print sceneReferences
		camera = ''
		for item in sceneReferences :
			if sceneReferences[item].isLoaded():
				if referenceCam.lower() in sceneReferences[item].path.lower():
					print 'cam loaded already'
					camera = pm.ls(item + ':*',type='camera')[0]
					break
		
		print referenceCam
		stageCam = pm.ls(referenceCam + '*',type='camera')[0]
		print stageCam
		
		if stageCam:
			camera = stageCam
		if camera == '':
			if os.path.isfile(referenceCam):
				pm.createReference(referenceCam,namespace="CAM")
				camera = pm.ls('CAM:*',type='camera')[0]
			else:
				print 'No cam file, creating a default one'
				cameraList = pm.camera(n='playblastCam')
				camera = cameraList[1]
				cameraList[0].setTranslation([0,10,60])
Esempio n. 8
0
def copyAttribute(translation = True, rotation = True, scale = False, pivot = False):
	"""
	copies position,translation, scale or pivot of the second/parent object to the first/child object
	"""

	if len(pm.ls(sl = True)) > 1:
		child = pm.ls(sl = True)[0]
		parent = pm.ls(sl = True)[1]
	else:
		if len(pm.ls(sl = True)) == 1:
			pm.warning("Only One Object Selected")
		else:
			pm.warning("Nothing Selected")
		return

	if translation == True:
		parentTranslation = parent.getTranslation()
		child.setTranslation(parentTranslation)
	if rotation == True:
		parentRotation = parent.getRotation()
		#parentRotation = pm.xform(parent, q = True, rotatePivot = True)
		child.setRotation(parentRotation)
	if scale == True:
		parentScale = parent.getScale()
		child.setTranslation(parentScale)
	if pivot == True:
		pass

	return
def ReverseShape(  objs=None, axis='x' ):
	
	scaleValue = ( -1, 1, 1 )
	if axis == 'y':
		scaleValue = ( 1, -1, 1 )
	elif axis == 'z':
		scaleValue = ( 1, 1, -1 )
	elif axis != 'x':
		pm.warning('Axis was not correct, used "x" axis instead.')
	
	if objs == None:
		objs = pm.ls( sl=True )
	else:
		objs = pm.ls( objs )
	
	for obj in objs:
		try:
			shape = obj.getShape()
			if shape.type() == 'mesh':
				pm.select( shape.vtx[:] )
				pm.scale( scaleValue )
				pm.select( objs )
			elif shape.type() == 'nurbsCurve':
				pm.select( shape.cv[:] )
				pm.scale( scaleValue )
				pm.select( objs )			
		except:
			pm.warning("Object doesn't have a shape. Skipped!")

		'''
def DistGlobalScale ( dist=None, mainCtrl=None ) :
	
	if dist==None or mainCtrl==None :
		dist, mainCtrl = pm.ls (sl=True)
	else:
		dist = pm.ls( dist )[0]
		mainCtrl = pm.ls( mainCtrl )[0]
	if dist and mainCtrl:
		distShape = dist.getShape()

		distShapeOuts = pm.listConnections (distShape ,s=False, p =True)
		
		if len (distShapeOuts) != 0 :
		
			globalScale_mdn = pm.createNode ("multiplyDivide" , n = "globalScale_mdn" )
			
			distShape.distance >> globalScale_mdn.input1X
			
			mainCtrl.scaleY >> globalScale_mdn.input2X
			
			globalScale_mdn.operation.set ( 2 )
			
			for out in distShapeOuts:
				
				globalScale_mdn.outputX >> out
Esempio n. 11
0
def storeDeformerWeights(selection=True, type='rig_vertSnap'):
	'''
	Usage:
		storeDeformerWeights(selection=False)
		storeDeformerWeights(selection=True, type=['rig_vertSnap'])
		storeDeformerWeights(selection=False, type=['rig_vertSnap', 'wire'])
	'''
	
	deformers = pm.ls(type=type)
	if selection:
		if len(pm.ls(sl=True))==0:
			pm.error('select something numbnuts!')
		deformers = pm.ls(sl=True)[0].listHistory(type='rig_vertSnap')
	vsFile = {}
	for deformer in deformers:
		vs = Deformer(deformer)
		vs.initializeWeights()
		if len(vs.weightsList) > 0:
			vsFile[deformer.name()] = vs.weightsList
	try:
		filename = os.path.join( pm.fileDialog2(cap='Select a folder to store the weights', fm=3, okc='Select')[0], 'deformerWeights.json' )
	except:
		pm.error('Why did you cancel? :(')
	with open(filename, 'wb') as fp:
		print 'Storing weights in file:\n\t%s'%(filename)
		print '\t\tDeformers Stored:\n\t\t\t%s'%('\n\t\t\t'.join([deformer.name() for deformer in deformers]))
		json.dump(vsFile, fp, indent=4)
Esempio n. 12
0
def bdMirrorCtrl():
    selection = pm.ls(sl=True)
    if selection:
        try:
            source,target = pm.ls(sl=True)
        except:
            pm.warning('Select source and target controller')
            return
        
        sourceShape = source.getShape()
        if sourceShape.type() != 'nurbsCurve':
            pm.error('Selected source is not nurbs curve')
            return
        
        targetCvsPos =  [ (dt.Point(-x.x, x.y, x.z) ) for x in sourceShape.getCVs(space='world')]
        
        
        targetShape = target.getShape()
        
        if targetShape.type() != 'nurbsCurve':
            pm.error('Selected target is not nurbs curve')
            return        
        targetShape.setCVs(targetCvsPos,space='world')
        targetShape.updateCurve()
        
        
    else:
        print 'Select source and target controller'
    '''
Esempio n. 13
0
def bdLocOnJnt():
    try:
        rootJnt = pm.ls(sl=True)[0]
    except:
        pm.warning('Nothing selected')
        return
    try:
        crvPath  = pm.ls(sl=True)[1]
    except:
        pm.warning('No curve selected')
        return

    allJnt = rootJnt.listRelatives(f=True, ad=True,type='joint')
    allJnt = allJnt + [rootJnt]
    allJnt.reverse()

    locators = []
    for jnt in allJnt:
        print jnt
        loc = pm.spaceLocator(name = jnt.name().replace( '_jnt','_loc'))
        locGrp = pm.group(n = loc.name() + '_grp')

        tempCnstr = pm.pointConstraint(jnt,locGrp,mo=0);
        pm.delete(tempCnstr )
        locators.append(locGrp)

    bdMultiMotionPath(crvPath, locators)
    bdParentJntToLocs(allJnt)
Esempio n. 14
0
    def addItems(self, parent):
        column = 0
        self.renderLayers = self.getRenderLayers()    #    Get render layers
        self.renderLayerDict = {}    #    Dictionary to store layer name and the assosiated AOVS
        for layer in self.renderLayers:
            if str(layer.name()) not in self.renderLayerDict:
                self.renderLayerDict[str(layer.name())] = []    #    Add elements to Dictionary as Key with empty list as value
#            vrayRenderElements = pm.listConnections(layer, s=1, type='VRayRenderElement')    #    Find all the AOVS connected to each render layers and Append to the Dictionary self.renderLayerDict[Key] = Value
            vrayRenderElements = pm.ls(type='VRayRenderElement')
            for element in vrayRenderElements:
                if element.name() not in self.renderLayerDict[str(layer.name())]:
                    self.renderLayerDict[str(layer.name())].append(str(element.name()))
#            vrayRenderElementSets = pm.listConnections(layer, s=1, type='VRayRenderElementSet')
            vrayRenderElementSets = pm.ls(type='VRayRenderElementSet')
            for set in vrayRenderElementSets:
                if set.name() not in self.renderLayerDict[str(layer.name())]:
                    self.renderLayerDict[str(layer.name())].append(str(set.name()))
        panels = pm.getPanel( type='modelPanel' )    #    Get all the Model panels and Set show to None
        for panel in panels:
            if '|' in panel:
                panel = panel.split('|')[-1]
                pm.modelEditor(panel, e=1, allObjects=0)

        for key, values in self.renderLayerDict.iteritems():     #    Update tree widget with top parent node as render layer name and childs as Aovs
            pm.editRenderLayerGlobals(currentRenderLayer=key)    #    select current render layer and find the Aovs state (Enabled or Disabled)
            layer_item = self.addParent(parent, column, key, 'data Layers')
            for value in sorted(values):
                self.addChild(layer_item, column, value, 'data Aovs')
Esempio n. 15
0
    def updateFileNamePrefix(self, *args):
        if self.rendererTabUiDict.has_key("common"):
            uiDict = self.rendererTabUiDict["common"]
        prefix = uiDict["fileNamePrefixField"].getText()

        sceneName = ".".join(pm.sceneName().basename().split(".")[:-1])
        if len(prefix) == 0:
            prefix = sceneName
            uiDict["imgname"].setLabel("File Name: " + sceneName)

        settings = pm.api.MCommonRenderSettingsData()
        pm.api.MRenderUtil.getCommonRenderSettings(settings)

        cams = [cam for cam in pm.ls(type="camera") if cam.renderable.get()]
        if len(cams) < 1:
            log.error("No renderable camera. please make at least one camera renderable.")
            prefix = ""
            for c in pm.ls(type="camera"):
                if "perspShape" in c:
                    cams.append(c)
                    break
        prefix = prefix.replace("<Camera>", cams[0].name())

        prefix = prefix.replace("<Scene>", sceneName)

        ext = self.renderNode.imageFormat.getEnums().keys()[self.renderNode.imageFormat.get()].lower()
        numberFormat = ""
        paddedFrameString = "{0:0" + str(settings.framePadding) + "d}."
        if settings.isAnimated():
            numberFormat = paddedFrameString.format(int(pm.SCENE.defaultRenderGlobals.startFrame.get()))
        completeFileName = "{prefix}.{numbering}{ext}".format(prefix=prefix, numbering=numberFormat, ext=ext)
        uiDict["imgname"].setLabel("File Name: " + completeFileName)
        """
Esempio n. 16
0
File: utils.py Progetto: mkolar/Tapp
def Connect(src, dst):

    pm.undoInfo(openChunk=True)

    alembics = src
    if not isinstance(src, list):
        alembics = pm.ls(src, dagObjects=True, type='transform')

    targets = dst
    if not isinstance(dst, list):
        targets = pm.ls(dst, dagObjects=True, type='transform')

    attrs = ['translate', 'rotate', 'scale', 'visibility']
    for node in targets:
        for abc in alembics:
            if node.longName().split(':')[-1] == abc.longName().split(':')[-1]:
                for attr in attrs:
                    pm.connectAttr('%s.%s' % (abc, attr),
                                   '%s.%s' % (node, attr),
                                   force=True)

                # securing primary shape is connected
                pm.connectAttr('%s.worldMesh[0]' % abc.getShape(),
                               '%s.inMesh' % node.getShape(),
                               force=True)

    pm.undoInfo(closeChunk=True)
Esempio n. 17
0
def ExtraControlForJnt( jnts=None ) :

	if not jnts:
		jnts = pm.ls( sl=True )
	else:
		jnts = pm.ls( jnts )
	
	
	for jnt in jnts:
		
		# duplicate joint
		pm.select( clear=True )
		newJnt = pm.joint( p = [0,0,0], name= '%s_extra'%jnt.name() )
		pm.delete( pm.pointConstraint( jnt, newJnt ) )
		pm.delete( pm.orientConstraint( jnt, newJnt ) )
		pm.parent( newJnt, jnt )
		newJnt.jointOrient.set( jnt.jointOrient.get() )
		
		# create control curve for joint
		ctrl = CubeCrv( name = '%s_ctrl'%jnt.name() )
		pm.delete( pm.pointConstraint( jnt, ctrl ) )
		pm.delete( pm.orientConstraint( jnt, ctrl ) )
		zeroAndOfs = ZeroGrp( ctrl )
		ctrl.translate >> newJnt.translate
		ctrl.rotate >> newJnt.rotate
		ctrl.scale >> newJnt.scale
        
		# make controls to move with base joints
		pm.parentConstraint( jnt, zeroAndOfs[0] )
		pm.scaleConstraint( jnt, zeroAndOfs[0] )
Esempio n. 18
0
def DistGlobalScale ( dist=None, mainCtrl=None ) :
	
	if dist==None or mainCtrl==None :
		dist, mainCtrl = pm.ls (sl=True)
	else:
		dist = pm.ls( dist )[0]
		mainCtrl = pm.ls( mainCtrl )[0]
	
	if dist and mainCtrl:
		
		if dist.type() == 'multiplyDivide':
			outAttr = 'outputX'
			distShape = dist
		else:
			outAttr = 'distance'
			if dist.type() == 'transform': # if transform node of distance node is selected, then select it's shape
				distShape = dist.getShape()
			else:
				distShape = dist
		
		distShapeOuts = pm.listConnections (distShape ,s=False, p =True)
		
		if len (distShapeOuts) != 0 :
		
			globalScale_mdn = pm.createNode ("multiplyDivide" , n = "globalScale_mdn" )
			
			distShape.attr( outAttr ) >> globalScale_mdn.input1X
			
			mainCtrl.scaleY >> globalScale_mdn.input2X
			
			globalScale_mdn.operation.set ( 2 )
			
			for out in distShapeOuts:
				
				globalScale_mdn.outputX >> out
 def testASetup(self):
     meshes = [
             "meshA",
             "meshB",
             "meshC",
             "meshD"
             ]
     self.meshes = pm.ls(meshes)
     keyable = [
             "controllerA",
             "controllerB",
             "controllerC",
             "controllerD",
             "main",
             ]
     self.keyableNodes = pm.ls(keyable)
     gui = GuiOverride()
     self.keyable = gui.allKeyableAttrs(self.keyableNodes)
     self.cc.setup(
             meshes = self.meshes,
             keyable = self.keyable,
             item = self.item,
             parentVis='main',
             prefix="testStandin"
             )
Esempio n. 20
0
def RigFK( jnts=None, side='L', ctrlSize=1.0, stretch=True, color='r' ):
	
	if not jnts:
		jnts = pm.ls( sl=True )
	else:
		jnts = pm.ls( jnts )
	# find color of the ctrls
	color = 'y'
	if side == 'L':
		color = 'r'
	elif side == 'R':
		color = 'b'
	
	shapes = []

	for jnt in jnts:
	
		if not jnt or not jnt.type()=='joint':
			pm.warning('ehm_tools...RigFK: %s was not a joint, skipped!'%jnt)

		
		shapes.append( (JntToCrv ( jnts = jnt , size = ctrlSize )).newShapes )
		LockHideAttr( objs=jnt, attrs='t' )
		LockHideAttr( objs=jnt, attrs='radius' )

		if stretch == True:
			# add length attribute and connect it to scale
			pm.addAttr (  jnt , ln = "length"  , at = "double"  , min = 0 , dv = 1 , k = True  )
			jnt.length >> jnt.scaleX
			LockHideAttr( objs=jnt, attrs='s' )

	Colorize( shapes=shapes, color=color )


	return shapes
def collectShaderInfoInLayer():
    sel = pm.ls(sl=True, dag=True, type='mesh')        
       
    shader_info_all_layers = []
    
    for renderlayer in pm.ls(type='renderLayer'):
        pm.editRenderLayerGlobals( currentRenderLayer=renderlayer )
        
        #// shader_info_layer stores the info for each seleted objs in CURRENT layer
        #// flush content of shader_info_layer 
        shader_info_layer = []
        for mesh in sel:
            SG_list = pm.listConnections(mesh, t='shadingEngine')
            #print SG_list
            
            if( SG_list == None ):
                continue
             
            if( len(SG_list) < 1 ):
                SG_list.append('initialShadingGroup')
            
            #// store mesh & material in CURRENT layer
            shader_info_layer.append( ( mesh, SG_list[0] ) )
            
        shader_info_all_layers.append( ( renderlayer, shader_info_layer ) )
        
    pm.editRenderLayerGlobals( currentRenderLayer='defaultRenderLayer' )          
    return shader_info_all_layers
Esempio n. 22
0
    def determineHanded(self, thumb, wrist): #thumb, wrist
        handed = ""

        objectJoint = pc.ls(thumb, type="joint")[0]
        objWorldMat = objectJoint.attr("worldMatrix").get()
        objTransformationMat = dt.TransformationMatrix(objWorldMat)
        objectTrans = objTransformationMat.getTranslation('world')
        
        
        tarJoint = pc.ls(wrist, type="joint")[0]    
        tarWorldMat = tarJoint.attr("worldMatrix").get()
        targetTransformationMat = dt.TransformationMatrix(tarWorldMat)
        targetTrans = targetTransformationMat.getTranslation('world')
        
        worldVector = dt.Vector(0,0,0)

        targetVector = (objectTrans - targetTrans)
        targetVector.normalize()
        
        targetUp = tarWorldMat[1][:3]
        targetUp.normalize()
        
        # find dot product between target and object
        dotProduct = dt.dot(targetUp, targetVector)
        
                
        if dotProduct > 0:
            handed = "R"
        if dotProduct <= 0:
            handed = "L"
            
        return handed
 def __init__(s, name):
     sel = pmc.ls(sl=True)
     pmc.select(clear=True)
     try:
         s.nodes = pmc.ls(name, r=True, type="objectSet") or [pmc.sets(n=name)]
     finally:
         pmc.select(sel, r=True)
Esempio n. 24
0
 def bdSwitchIKFK(self):
     if 'arm' in self.limb:
         print self.side + ' arm IK -> FK switch'
         
         for loc in self.fkArmCons:
             shadowLoc = pm.ls(self.namespace + self.side +  loc + 'LOC')[0]
             tempLoc = pm.duplicate(shadowLoc)
             pm.parent(tempLoc,w=True)
             
             fkCon = pm.ls(self.namespace + self.side +  loc + 'CON',type='transform')[0]
             tempCnstr = pm.orientConstraint(tempLoc,fkCon)
             
             pm.delete([tempCnstr,tempLoc])
             
         
         self.armSwitchCon.attr('ikFkBlend').set(1)
         
     elif 'leg' in self.limb:
         print self.side + ' leg IK->FK switch ' 
         
         for loc in self.fkLegCons:
             shadowLoc = pm.ls(self.namespace + self.side +  loc + 'LOC')[0]
             tempLoc = pm.duplicate(shadowLoc)
             pm.parent(tempLoc,w=True)
             
             fkCon = pm.ls(self.namespace + self.side +  loc + 'CON',type='transform')[0]
             tempCnstr = pm.orientConstraint(tempLoc,fkCon)
             
             pm.delete([tempCnstr,tempLoc])
             
         
         self.legSwitchCon.attr('ikFkBlend').set(1)            
Esempio n. 25
0
 def bdSwitchFKIK(self):
     if 'arm' in self.limb:
         print self.side + ' arm FK->IK switch ' 
         
         for loc in self.ikArmCons:
             shadowLoc = pm.ls(self.namespace + self.side +  loc + 'LOC')[0]
             tempLoc = pm.duplicate(shadowLoc)
             pm.parent(tempLoc,w=True)
             
             ikCon = pm.ls(self.namespace + self.side +  loc + 'CON',type='transform')[0]
             if ikCon.name().find('armIK') > 0:
                 tempCnstr = pm.parentConstraint(tempLoc,ikCon)
             else:
                 tempCnstr = pm.pointConstraint(tempLoc,ikCon)
             pm.delete([tempCnstr,tempLoc])
                    
         self.armSwitchCon.attr('ikFkBlend').set(0)
     
     elif 'leg' in self.limb:
         print self.side + ' leg FK->IK switch ' 
         
         for loc in self.ikLegCons:
             shadowLoc = pm.ls(self.namespace + self.side +  loc + 'LOC')[0]
             tempLoc = pm.duplicate(shadowLoc)
             pm.parent(tempLoc,w=True)
             
             ikCon = pm.ls(self.namespace + self.side +  loc + 'CON',type='transform')[0]
             if ikCon.name().find('legIK') > 0:
                 tempCnstr = pm.parentConstraint(tempLoc,ikCon)
             else:
                 tempCnstr = pm.pointConstraint(tempLoc,ikCon)
             pm.delete([tempCnstr,tempLoc])
                    
         self.legSwitchCon.attr('ikFkBlend').set(0)
Esempio n. 26
0
def bdRenameLipJoints(namespace):

	tsmCornerLipJoints = ['lip_corner_right_speak','lip_corner_left_speak']
	tsmLipJoints = ['upper_lip_right_speak','upper_lip_open_center_speak','upper_lip_center_speak','upper_lip_left_speak']

	capcomCornerLipJoints = ['Face_RMouthCorners','Face_LMouthCorners']
	capcomLipJoints = ['Face_RMouthTop2','Face_RMouthTop1','Face_LMouthTop1','Face_LMouthTop2']

	for jnt in capcomCornerLipJoints:
		toRename = pm.ls( namespace+ jnt)[0]
		try:
			toRename.rename(tsmCornerLipJoints[capcomCornerLipJoints.index(jnt)])
		except:
			print 'some shit happened'

	for jnt in capcomLipJoints:
		toRenameUpper = pm.ls(namespace + jnt,ap=True)[0]
		toRenameLower = pm.ls(namespace + jnt.replace('Top','Bottom'),ap=True)[0]
		try:
			toRenameUpper.rename(tsmLipJoints[capcomLipJoints.index(jnt)])    
		except:
			print 'some shit happened while renaming ', toRenameUpper.name()

		try:
			toRenameLower.rename(tsmLipJoints[capcomLipJoints.index(jnt)].replace('upper','lower'))    
		except:
			print 'some shit happened while renaming ', toRenameLower.name()   
Esempio n. 27
0
def bdConnectArms(namespace):
	print 'adasdasdasda'
	sides = {'Left':'L', 'Right':'R'}
	tsmArmChain = ['Arm_joint1','Arm_joint2','Arm_joint3','Arm_joint5','Arm_influence7_intermediate_constrain','Arm_joint6','Arm_joint7','Arm_joint8','Arm_joint7']
	capcomArmChain = ['Shoulder','ArmDir','Arm1','Arm2','Elbow','ARoll3','ARoll4','handRot','handXR'] 

	i=0

	for jnt in tsmArmChain:
		try:
			target = pm.ls(namespace + sides['Left'] + capcomArmChain[i])[0]
		except:
			print ' cant find', capcomArmChain[i]
			
		source = pm.ls(sides.keys()[1] + jnt )[0]
		i+=1

		pm.parentConstraint(source,target,mo=True)
		pm.scaleConstraint(source,target,mo=True)

	i=0

	for jnt in tsmArmChain:
		target = pm.ls(namespace + sides['Right'] + capcomArmChain[i])[0]
		source = pm.ls(sides.keys()[0] + jnt )[0]
		i+=1

		pm.parentConstraint(source,target,mo=True)        
		pm.scaleConstraint(source,target,mo=True)
def transferProxyTransforms():
    nodes = pm.ls(sl=True)

    attrsDict = {}
    attrs = ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz')
    
    for n in nodes:
        d = {}
        for a in attrs:
            d[a] = n.attr(a).get()
        attrsDict[n.nodeName()] = d
        
    #--------
    
    # adapt changes
    attrsDict['spine_mid_2_loc'] = attrsDict['spine_mid_loc']
    attrsDict['spine_mid_1_loc'] = attrsDict['spine_low_loc']
    
    nodes = pm.ls(sl=True)
    
    for n in nodes:
        if n.nodeName() in attrsDict.keys():
            for a, val in attrsDict[n.nodeName()].items():
                try:
                    n.attr(a).set(val)
                except:
                    pass
        else:
            print n + ' not found'
Esempio n. 29
0
def populateList():    
    # Get shader type
    shaderSel = pc.radioButtonGrp(uiWidgets['shaderType'], q=1, select=1)
    
    if shaderSel == 1:
        shaderType = 'lambert'
    elif shaderSel == 2:
        shaderType = 'blinn'
    elif shaderSel == 3:
        shaderType = 'phong'
        
    # Get shader prefix
    shaderPrefix = pc.textField(uiWidgets['shadersPrefix'], q=1, text=1)
    
    if len(shaderPrefix) == 0:
        listShaders = pc.ls(exactType=shaderType)
    else:
        listShaders = pc.ls(shaderPrefix+'*', exactType=shaderType)

    if len(listShaders) == 0:
        pc.confirmDialog(t="Error", message="No shaders fitting the given paramaters has been found.", icon='critical')
        exit(1)
    elif len(listShaders) > 0:
        pc.confirmDialog(t="Shaders found", message=str(len(listShaders))+" shader(s) found. Click confirm to continue.")
    else:
        exit("Unknown error.")
    
#    for info in infos.keys():
#        print "#######################"
#        print "### Shader: '%s'" % info
#        print " - Found %s shape(s)" % len(infos[info])
#        print "Shapes list: %s " % infos[info]
        
    return listShaders
Esempio n. 30
0
def bdAddSpreadMeta(side,finger,attr):
	fingerAnim = pm.ls(side + 'Fingers_CON',type='transform')[0]
	if finger != 'Thumb':
		startFingerJnt = pm.ls(side + finger + '_00_JNT')[0]
		pm.setDrivenKeyframe(startFingerJnt, at='rotateY', cd = fingerAnim.name() + '.' + attr , dv= 0 , v = 0)
		pm.setDrivenKeyframe(startFingerJnt, at='rotateY', cd = fingerAnim.name() + '.' + attr , dv= 10 , v = -10)
		pm.setDrivenKeyframe(startFingerJnt, at='rotateY', cd = fingerAnim.name() + '.' + attr , dv= -10 , v = 10)
Esempio n. 31
0
def getA( ):
    return pm.ls(sl=1)[0]
    What should I know after looking at this script?
        - How to get selected object in a Maya scene.
        - How to get attribute values from a object in Maya.
        - How to take values from one object and apply it to another in Maya.
        
    Questions you should ask yourself:
        
'''

import pymel.core as pm
'''
Catching Informatino
'''

# Select two object in your scene.
selected = pm.ls(sl=True)  # Returns selected objects in the scene.
print selected
# It will print out something like this (depends on what you have selected.)
# Result: [nt.Transform(u'control1_icon'), nt.Transform(u'control2_icon'), nt.Transform(u'control3_icon')] #
# Three transforms selected in our scene

# Creating objects
icon = pm.circle(nr=[0, 1, 0])
print icon
# [nt.Transform(u'nurbsCircle1'), nt.MakeNurbCircle(u'makeNurbCircle2')]
# Returns the transform and history node of the nurbs circle created.

# Getting object position
# Built in methon in pymel
# icon[0] is the transform node created above.
trans = icon[0].getTranslation()
Esempio n. 33
0
import maya.cmds as cmds
import pymel.core as pm
#Take 4 objects,randomly placed and lock one object's attribute.

#Statement01
selected_obj=pm.ls(sl=True)

for i in selected_obj:
   	pm.xform(i,t=(5,3,5))




#Statement02
selected_obj=pm.ls(sl=True) 
for i in selected_obj:
	try:
		pm.xform(i,t=(5,3,5))
	except:
		print(i+'Encountered a problem while moving')



#Statement03
selected_obj=pm.ls(sl=True)
try:
    pm.move(3,1,5)
except:
    pass
Esempio n. 34
0
        g = plateG / renderG
        b = plateB / renderB

        return r, g, b

    def createStandardColorCorrect(self):
        # get texture fileNode
        file_node = pm.listConnections(self.hdriNode.color,
                                       p=False,
                                       s=True,
                                       type='file')[0]
        self.colorCorrect_node = file_node

    def setStandarGain(self, r=1, g=1, b=1):
        self.colorCorrect_node.colorGain.set(r, g, b)

    def setPxrGain(self, r=1, g=1, b=1):
        self.hdriNode.lightColor.set(r, g, b)


if __name__ == "__main__":
    sel = pm.ls('PxrDomeLightShape1', 'aiSkyDomeLightShape1')

    for s in sel:
        # print(type(s))
        print(pm.objectType(s, isType='aiSkyDomeLight'))
        # Result: True #

    sel2 = pm.ls(type='PxrDomeLight')
    print(sel2)
Esempio n. 35
0
def createCgfxShader(shaders='', overwrite=1):
    '''
    'Converts' the materials that come with the Mixamo rig to cgfx shader. 
    Parameters:
    - shaders : If no shaders dictionary is defined,  it will use the DEFAULT_SHADERS
    - overwrite : default 1, it will overwrite the files in sourceimages . 
    
    In order not to manually create and assign shaders (which wil not work in maya batch mode), the cgfx materials are imported and assigned via connectiong them to the existing mesh shaders.
    '''

    global DEFAULT_SHADERS
    materialList = []

    if shaders:
        DEFAULT_SHADERS = shaders

    print 'Create cgfx shaders'
    diffuseFile = specFile = normFile = ''
    #get the materials starting from the shaders and looking for connections
    shadersList = [sh.name() for sh in pm.ls(type='shadingEngine')]
    #maya's default shaders, we will remove them from the list
    mayaShaders = ['initialParticleSE', 'initialShadingGroup']

    shadersList = set(shadersList) - set(mayaShaders)

    for sh in shadersList:

        mat = pm.listConnections('%s.surfaceShader' % sh)[0]
        #cleanup shaders, remove those that are not assigned to a mesh
        if pm.listConnections(sh, type='mesh'):
            materialList.append(mat)
        else:
            pm.delete(sh)

    diffuseFile = specFile = normFile = ''
    for mat in materialList:
        try:
            diffuseFile = pm.listConnections('%s.color' % mat)[0]
        except:
            pm.warning('No diffuse file found')
        try:
            specFile = pm.listConnections('%s.specularColor' % mat)[0]
        except:
            pm.warning('No spec file found')
        try:
            bumpFile = pm.listConnections('%s.normalCamera' % mat)[0]
            normFile = pm.listConnections('%s.bumpValue' % bumpFile)[0]
            pm.delete(bumpFile)
        except:
            pm.warning('No norm file found')
        try:
            setRangeNode = pm.listConnections('%s.cosinePower' % mat)[0]
            glossFile = pm.listConnections('%s.valueX' % setRangeNode)[0]
            pm.delete([glossFile, setRangeNode])
        except:
            pm.warning('No spec file found')

        cgfxShader = importCgfxShader(mat)

        #connects the file nodes to the cgfx material
        if diffuseFile:
            diffuseFile.outColor.connect(cgfxShader.diffuseMapSampler)
        if specFile:
            specFile.outColor.connect(cgfxShader.specularMapSampler)
        if normFile:
            normFile.outColor.connect(cgfxShader.normalMapSampler)
            pm.setAttr('%s.Bump' % cgfxShader, 5)

        #get the shaders for the materials
        shader = pm.listConnections("%s.outColor" % mat)[0]

        #connect the cgfx material to the mesh shader
        shader.surfaceShader.disconnect()
        cgfxShader.outColor.connect(shader.surfaceShader)
        print('Converted -> %s   to -> %s ' % (mat, cgfxShader))
        pm.delete(mat)

    cleanUpTextures(overwrite)
    createEyelashesShader()
Esempio n. 36
0
def makeShape(namesList, shape):
    #localNameList = ['winText', 'selName', 'grpName', 'offName', False, 'pieceName']
    print(namesList)

    shapes = []

    select(cl=True)
    if shape == 'DCircle':
        group(n=namesList[2])
        shapes.append(circle(nr=(0, 1, 0), c=(0, 0, 0), n=(namesList[5])))
        move(0, .25, 0)
        shapes.append(circle(nr=(0, 1, 0), c=(0, 0, 0), n=(namesList[5])))
        move(0, -.25, 0)
        shapes.append(
            curve(p=[(1, -.25, 0), (1, .25, 0)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, 10)
        shapes.append(
            curve(p=[(-1, -.25, 0), (-1, .25, 0)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, 10)
        shapes.append(
            curve(p=[(0, -.25, 1), (0, .25, 1)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, 10)
        shapes.append(
            curve(p=[(0, -.25, -1), (0, .25, -1)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, 10)
        shapes.append(
            curve(p=[(1, -.25, 0), (1, .25, 0)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, -10)
        shapes.append(
            curve(p=[(-1, -.25, 0), (-1, .25, 0)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, -10)
        shapes.append(
            curve(p=[(0, -.25, 1), (0, .25, 1)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, -10)
        shapes.append(
            curve(p=[(0, -.25, -1), (0, .25, -1)],
                  k=[0, 1],
                  d=1,
                  n=(namesList[5])))
        rotate(0, 0, -10)

        for s in shapes:
            select(s, add=True)

        makeIdentity(apply=True)
        delete(ch=True)
        pickWalk(d='down')

        shapesSel = pm.ls(sl=True, s=True)

        for s in shapesSel:
            parent(s, namesList[2], s=True, r=True)

    if shape == 'BCircle':
        shapes.append(circle(nr=(0, 1, 0), c=(0, 0, 0), n=(namesList[2])))

    if shape == 'BSquare':
        shapes.append(
            curve(p=[(1, 0, 1), (-1, 0, 1), (-1, 0, -1), (1, 0, -1),
                     (1, 0, 1)],
                  k=[0, 1, 2, 3, 4],
                  d=1,
                  n=(namesList[2])))

    select(cl=True)
    group(n=namesList[3])
    tempConstraint = pm.parentConstraint(namesList[1], namesList[3], mo=False)
    delete(tempConstraint)
    parent(namesList[2], namesList[3])
    tempAttr = namesList[2] + '.tx'
    setAttr(tempAttr, 0)
    tempAttr = namesList[2] + '.ty'
    setAttr(tempAttr, 0)
    tempAttr = namesList[2] + '.tz'
    setAttr(tempAttr, 0)
    tempAttr = namesList[2] + '.rx'
    setAttr(tempAttr, 0)
    tempAttr = namesList[2] + '.ry'
    setAttr(tempAttr, 0)
    tempAttr = namesList[2] + '.rz'
    setAttr(tempAttr, 90)

    select(namesList[2])
    makeIdentity(apply=True)

    select(namesList[1])
    ob = pm.selected()
    for n in ob:
        ro = n.getRotationOrder()

    select(namesList[2])
    ctrl = pm.selected()
    for n in ctrl:
        n.setRotationOrder(ro, True)

    pm.parentConstraint(namesList[2], namesList[1], mo=False)

    select(namesList[1])
    checkPar = listRelatives(p=True)
    hasPar = len(checkPar)

    if hasPar != 0:
        print(checkPar[0])
        checkConstraints = pm.parentConstraint(checkPar[0], q=True, tl=True)
        if checkConstraints != []:
            select(namesList[3])
            select(checkConstraints, add=True)
            parent()

    select(namesList[1])
    toDo = []
    check = listRelatives(c=True)
    checkPar = listRelatives(p=True)
    hasPar = len(checkPar)

    for c in check:
        select(c)
        childSel = ls(sl=True, tr=True)
        if len(childSel) > 0:
            child = childSel[0].type()
            if child == 'joint':
                toDo.append(childSel[0])
        else:
            select(cl=True)

    leftToDo = len(toDo)

    if leftToDo != 0:
        select(toDo[0])
Esempio n. 37
0
def getB( ):
    return pm.ls(sl=1)[1]
Esempio n. 38
0
 def __init__(self):
     self.selection = pm.ls(selection=True)
     self.output_texture_path = '/Users/kif/Documents/rr/dev/maya_txbkn/test/simple_cube/renders'
     self.image_width = 50
     self.cur_version_string = 'v001'
Esempio n. 39
0
def postRenderOptimizeTextures():
    for fileTexture in pm.ls(type="file"):
        if fileTexture.hasAttr("origFilePath"):
            fileTexture.fileTextureName.set(fileTexture.origFilePath.get())
            fileTexture.origFilePath.delete()
Esempio n. 40
0
    With main:
            def main():
                pass
                
            if __name__=='__main__':
                main()
"""
# ----------------------------------------------------------------------
# Import
# ----------------------------------------------------------------------
import pymel.core as pm

# ----------------------------------------------------------------------
# Configuration
# ----------------------------------------------------------------------
sel = pm.ls(sl=1)
ob_sel = []
cur_rl = pm.editRenderLayerGlobals(q=1, crl=1)
er = pm.editRenderLayerAdjustment(cur_rl, q=1, lyr=1)

# ----------------------------------------------------------------------
# Main Script
# ----------------------------------------------------------------------
print('Object ID')
print(pm.editRenderLayerAdjustment(query=True, alg=True))
if cur_rl != 'defaultRenderLayer':
    for x in sel:
        try:
            ob_sel.append(x)
            if str(pm.getAttr(x.vrayObjectID)) == str(0):
                pm.editRenderLayerAdjustment(x.vrayObjectID)
Esempio n. 41
0
"""

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

__author__ = 'timmyliang'
__email__ = '*****@*****.**'
__date__ = '2020-11-25 17:25:41'


import pymel.core as pm
import pymel.core.datatypes as dt

thersold = 0.015

sel_list = pm.ls(pm.pickWalk(d='down'),type="mesh")
for sel in sel_list:
    
    for BS in pm.ls(sel.listConnections(),type="blendShape"):
        grp = BS.inputTarget[0].inputTargetGroup
        for idx in (grp.getArrayIndices()):
            components = grp[idx].inputTargetItem[6000].inputComponentsTarget.get()
            points = grp[idx].inputTargetItem[6000].inputPointsTarget.get()
             
            if not components or not points:
                continue
            verts = ["%s.%s" % (sel,vtx) for vtx in components]
            verts = [vtx.__melobject__() for pt,vtx in zip(points,pm.ls(verts,fl=1)) if dt.Vector(pt).length() > thersold]
            print(idx,verts)
            
Esempio n. 42
0
    def create(self):
        self.setWindowTitle("Hafarm")
        self.setWindowFlags(QtCore.Qt.Tool)
        self.resize(300, 90)  # re-size the window
        self.mainLayout = QtWidgets.QVBoxLayout(self)

        self.jointTitle = QtWidgets.QLabel(" Redshift render ")
        self.jointTitle.setStyleSheet("color: white;background-color: black;")
        self.jointTitle.setFixedSize(300, 30)
        # self.jointList = QtWidgets.QListWidget(self)
        # self.jointList.resize(300, 300)
        # for i in range(10):
        #     self.jointList.addItem('Item %s' % (i + 1))

        self.cameraLabel1 = QtWidgets.QLabel("Select renderable camera:")
        self.renderable_cameras = QtWidgets.QComboBox()
        self.renderable_cameras.insertItems(0, [
            str(x.getParent())
            for x in pm.ls(cameras=True) if x.visibility.get() == True
        ])  #if x.renderable.get() == True])

        # self.skinTitle = QtWidgets.QLabel(" Current Skin Weights")
        # self.skinTitle.setStyleSheet("color: white;background-color: black;")
        # self.skinTitle.setFixedSize(300,30)

        self.startFrameLabel1 = QtWidgets.QLabel("Start frame")
        self.endFrameLabel2 = QtWidgets.QLabel("End frame")
        # self.displayInfLabel3 = QtWidgets.QLabel("Inf3");
        # self.displayInfLabel4 = QtWidgets.QLabel("Inf4");

        self.infLabelLayout = QtWidgets.QHBoxLayout()
        self.infLabelLayout.addWidget(self.startFrameLabel1)
        self.infLabelLayout.addWidget(self.endFrameLabel2)
        # self.infLabelLayout.addWidget(self.displayInfLabel3)
        # self.infLabelLayout.addWidget(self.displayInfLabel4)

        self.startFrame1 = QtWidgets.QLineEdit(
            str(int(pm.SCENE.defaultRenderGlobals.startFrame.get())))
        self.endFrame2 = QtWidgets.QLineEdit(
            str(int(pm.SCENE.defaultRenderGlobals.endFrame.get())))
        # self.displayWeight3 = QtWidgets.QLineEdit("0");
        # self.displayWeight4 = QtWidgets.QLineEdit("0");

        self.weightLayout = QtWidgets.QHBoxLayout()
        self.weightLayout.addWidget(self.startFrame1)
        self.weightLayout.addWidget(self.endFrame2)
        # self.weightLayout.addWidget(self.displayWeight3)
        # self.weightLayout.addWidget(self.displayWeight4)

        self.skinWeightGrid = QtWidgets.QGridLayout()
        self.skinWeightGrid.addLayout(self.infLabelLayout, 0, 0)
        self.skinWeightGrid.addLayout(self.weightLayout, 1, 0)

        self.groupLabel1 = QtWidgets.QLabel("Host Group:")
        self.group_list = QtWidgets.QComboBox()
        self.group_list.insertItems(
            0, ('allhosts', 'grafika', 'render', 'old_intel', 'new_intel'))

        self.queueLabel1 = QtWidgets.QLabel("Queue:")
        self.queue_list = QtWidgets.QComboBox()
        self.queue_list.insertItems(0, ('cuda', ))

        self.hold = QtWidgets.QCheckBox("Job on hold")

        self.priorityLabel = QtWidgets.QLabel("Priority")
        self.priority = QtWidgets.QLineEdit(
            str(const.hafarm_defaults['priority']))
        self.priority.setFixedWidth(60)

        self.priorityLayout = QtWidgets.QHBoxLayout()
        self.priorityLayout.addWidget(self.priorityLabel)
        self.priorityLayout.addWidget(self.priority)

        self.priorityGrid = QtWidgets.QGridLayout()
        self.priorityGrid.addLayout(self.priorityLayout, 0, 0,
                                    QtCore.Qt.AlignLeft)

        self.submitButton = QtWidgets.QPushButton("Submit")
        self.submitButton.clicked.connect(self.submit)
        self.submitButton.setFixedSize(50, 20)

        self.mainLayout.addWidget(self.jointTitle)
        self.mainLayout.addWidget(self.cameraLabel1)
        self.mainLayout.addWidget(self.renderable_cameras)
        # self.mainLayout.addWidget(self.jointList)
        # self.mainLayout.addWidget(self.skinTitle)
        self.mainLayout.addLayout(self.skinWeightGrid)
        self.mainLayout.addWidget(self.groupLabel1)
        self.mainLayout.addWidget(self.group_list)
        self.mainLayout.addWidget(self.queueLabel1)
        self.mainLayout.addWidget(self.queue_list)
        self.mainLayout.addWidget(self.hold)
        self.mainLayout.addLayout(self.priorityGrid)
        # self.mainLayout.addWidget(self.color)
        # self.mainLayout.addWidget(self.position)
        self.mainLayout.addWidget(self.submitButton)
Esempio n. 43
0
def attachGuideToScalp():
    xgGuides = pm.ls(type='xgmSplineGuide')
    for xgGuide in xgGuides:
        xgmMakeGuide = xgGuide.toMakeGuide.connections()[0]
        xgmMakeGuide.outputMesh.connect(xgGuide.inputMesh, f=True)
Esempio n. 44
0
def preRenderOptimizeTextures(destFormat = "exr", optimizedFilePath = ""):
    for fileTexture in pm.ls(type="file"):
        fileNamePath = path.path(fileTexture.fileTextureName.get())
        log.debug("Check file texture:" + fileNamePath)
        
        if not fileNamePath.exists():
            log.debug("file texture could not be found, skipping.")
            continue
            
        if fileNamePath.ext[1:] == destFormat:
            log.debug("file texture is already an " + destFormat + " skipping.")
            continue
        
        if fileTexture.useFrameExtension.get():
            log.debug("file texture is animated skipping.")
            continue

        # path will contain either contain a leading slash for 
        # unix /server/textures/file.exr
        # or a drive in windows like c:
        # or a dfs name like //server/textures.... 
        optimizedFilePath = path.path(optimizedFilePath)
        log.debug("optimizedFilePath " + optimizedFilePath)
        if fileNamePath[1] == ":":
            localPath = optimizedFilePath / fileNamePath[3:]
        if fileNamePath.startswith("//"):
            localPath = optimizedFilePath / fileNamePath[2:]
        if fileNamePath.startswith("/"):
            localPath = optimizedFilePath / fileNamePath[1:]
        localPath += ".exr"
        localPath = path.path(localPath)
        log.debug("local path " + localPath.realpath())
        localPath = localPath.realpath()
        
        doConvert = True
        if localPath.exists():
            if isOlderThan(fileNamePath, localPath):
                log.debug(localPath + " already exists and is older then original file. No conversion needed.")
                doConvert = False
        
        if doConvert:
            # make it a exr
            if not makeExr(fileNamePath.realpath(), path.path(localPath.replace(".exr", "_t.exr")).realpath()):
                log.debug("Problem converting " + fileNamePath)
                continue
            
            #shutil.copy(localPath.replace(".exr", "_t.exr"), localPath)
            # executable: maketiledexr(.exe)
            cmd = "maketiledexr"
            
            cmd += " " + localPath.replace(".exr", "_t.exr") + " " + localPath
            
            try:
                subprocess.call(cmd, shell = True)
            except:
                log.warning("Conversion to tiled exr failed " +  str(sys.exc_info()[0]) + " - skipping")
                continue 
            
            os.remove(localPath.replace(".exr", "_t.exr"))
        
        if not fileTexture.hasAttr("origFilePath"):
            fileTexture.addAttr("origFilePath", dt="string")
        fileTexture.origFilePath.set(fileNamePath)
        fileTexture.fileTextureName.set(localPath)
Esempio n. 45
0
    def export(self, **kwargs):
        # the category is just a folder below the library path
        assetCategory = kwargs.setdefault('assetCategory', 'default')

        # if no name is specified it uses the scene name
        assetName = kwargs.setdefault('assetName',
                                      pm.sceneName().basename()[:-3])

        # an asset can have a .txt file associated with it. This should
        # help to clarify the contents of an asset
        assetDescription = kwargs.setdefault('assetDescription')

        # by default the exportAll command is called
        exportType = kwargs.setdefault('type', 'all')

        # if true automatically sets the camera to frame the exported objs
        autoFrame = kwargs.setdefault('autoFrame', True)

        breakRef = kwargs.setdefault('breakRef', False)

        # if the scene was not saved it has no name
        if assetName == '':
            raise Exception('Asset Name not specified')

        if exportType == 'selected' and not pm.selected():
            # if nothing is selected, stop the execution here
            raise Exception('Nothing Selected')

        # create the folders if they don't exist
        self.checkPath(os.path.join(self.libraryPath, assetCategory))
        assetPath = os.path.join(self.libraryPath, assetCategory, assetName)
        self.checkPath(assetPath)

        # save the selection now because enableIsolateSelect clears it
        selection = pm.selected()
        mpanel = pm.paneLayout('viewPanes', q=True, pane1=True)
        # disable selection highlighting and wireframe on shaded
        wireframeOnShadedState = pm.windows.modelEditor(mpanel,
                                                        q=True,
                                                        wireframeOnShaded=True)
        pm.windows.modelEditor(mpanel,
                               e=True,
                               sel=False,
                               wireframeOnShaded=False)
        # set background color
        originalBackgroundColor = pm.general.displayRGBColor('background',
                                                             q=True)
        pm.general.displayRGBColor('background', 0.3, 0.3, 0.3)
        # set the camera
        cam = pm.ls(pm.modelPanel(mpanel, q=True, cam=True),
                    type='transform')[0]
        if autoFrame:
            wTrans = cam.getTranslation(ws=True)
            wRot = cam.getRotation(ws=True)
            try:
                cam.rx.set(-10)
                cam.ry.set(30)
                pm.viewFit()
            except:
                pass

        pm.general.refresh()

        if exportType == 'selected':
            # hide everything that is not selected for the playblast
            pm.mel.eval('enableIsolateSelect %s %d' % (mpanel, 1))

        # RENDER ICON
        # this is a simple playblast of the current frame
        # image is saved as .jpg with an _icon suffix
        pm.animation.playblast(cf=assetPath + '/' + assetName + '_icon.jpg',
                               format='image',
                               compression='jpg',
                               widthHeight=[128, 128],
                               frame=[pm.animation.currentTime()],
                               orn=False,
                               os=True,
                               v=False,
                               percent=100)
        if autoFrame:
            try:
                # reset camera
                cam.setTranslation(wTrans, ws=True)
                cam.setRotation(wRot, ws=True)
            except:
                pass

        if exportType == 'selected':
            # show the scene again. the user shouldn't notice
            pm.mel.eval('enableIsolateSelect %s %d' % (mpanel, 0))

        # reenable selection highlighting and reset wireframe on shaded to what it was before
        pm.windows.modelEditor(mpanel,
                               e=True,
                               sel=True,
                               wireframeOnShaded=wireframeOnShadedState)

        #reset the background color to what it was before
        pm.general.displayRGBColor('background', originalBackgroundColor[0],
                                   originalBackgroundColor[1],
                                   originalBackgroundColor[2])

        # EXPORT FILE
        # reselect the selection, isolate select clears it.
        pm.select(selection)
        if exportType == 'all':
            self.fixNamespaces(
                self.removeStudentLic(
                    pm.system.exportAll(assetPath + '/' + assetName + '.ma',
                                        preserveReferences=not breakRef,
                                        force=True)))
        if exportType == 'selected':
            self.fixNamespaces(
                self.removeStudentLic(
                    pm.system.exportSelected(assetPath + '/' + assetName +
                                             '.ma',
                                             preserveReferences=not breakRef,
                                             force=True)))

        # SAVE DESCRIPTION
        # newlines are saved
        if assetDescription:
            text_file = open(assetPath + '/' + assetName + '.txt', 'wt')
            text_file.write(assetDescription.encode('utf8'))
            text_file.close()
Esempio n. 46
0
def set_all_draw_mode(draw_mode):
    standins = pmc.ls(type="aiStandIn")

    for standin in standins:
        logger.debug("Now processing: {}".format(standin))
        standin.mode.set(draw_mode)
# Youtube Link: https://youtu.be/rFIH1yvGYSo

# Organize objects to display layer in Maya using Python

# importing nessory modules
import pymel.core as pm

# Getting the top level transform node
assemblies = pm.ls(assemblies=True)

# Creating the ignore list.
excludeType = ['persp', 'top', 'side', 'front']

# Empty list created for adding assemblies
finalAssemblies = []

# Looping through all assemblies
for each in assemblies:
    # Checking whether each item is not in exclude list. if avaliable it will be ignored
    if each not in excludeType:
        # Adding each item from list if not avaliable in exclude list
        finalAssemblies.append(each)

# Getting the list of catagories with out duplicates.

# empty list to store catagories
catagory = []

# Looping through final assemblies
for each in finalAssemblies:
    # Splitting the name based on "_"
Esempio n. 48
0
    def getReferenceLocators(self, refNodes):
        locators = []
        for shape in pm.ls(refNodes[0].namespace() + '*:*', type='locator'):
            locators.append(shape.getParent())

        return locators
def copySkin2Object():
    """copies skincluster from skinned geometry to another object with no skin"""
    geomObjects = pm.ls(sl=True)
    skinnedObjectJoints = getObjectJoints()
    logger.debug(skinnedObjectJoints)
    skinClusterCopied = pm.skinCluster(geomObjects[1], skinnedObjectJoints)
Esempio n. 50
0
    def reference(self, **kwargs):
        assetCategory = kwargs.setdefault('assetCategory')
        assetName = kwargs.setdefault('assetName')
        environmentVariable = kwargs.setdefault('environmentVariable', None)
        groupLocator = kwargs.setdefault('groupLocator', True)
        selectable = kwargs.setdefault('selectable', False)

        if not assetCategory or assetCategory == '-':
            raise Exception('No asset specified')
        if not assetName or assetName == '-':
            raise Exception('No asset specified')

        # build the reference Path and check if this asset exists
        referencePath = absolutePath = os.path.join(self.workspacePath,
                                                    self.libraryFolder,
                                                    assetCategory, assetName)

        if environmentVariable:
            referencePath = absolutePath.replace(self.workspacePath,
                                                 '$' + environmentVariable)

        if not os.path.exists(absolutePath):
            raise Exception('Asset %s does not exist' % absolutePath)

        # check namespaces
        if not pm.system.namespace(exists=assetCategory):
            pm.system.namespace(add=assetCategory)

        if not pm.system.namespace(exists=assetCategory + ':' + assetName):
            pm.system.namespace(add=assetCategory + ':' + assetName)

        # multiple references are supported, namespace is incremented by 1 every time
        namespace = ':' + assetCategory + ':' + assetName + ':' + 'r%s' % 1
        count = 1
        while pm.system.namespace(exists=namespace, r=True):
            count += 1
            namespace = ':' + assetCategory + ':' + assetName + ':' + ('r%s' %
                                                                       count)

        # create the reference
        newNodes = pm.system.createReference(referencePath + '/' + assetName +
                                             '.ma',
                                             namespace=namespace,
                                             groupReference=groupLocator,
                                             groupLocator=groupLocator,
                                             returnNewNodes=True,
                                             shd='shadingNetworks')

        refNode = pm.referenceQuery(newNodes[0], rfn=True, tr=True)
        refNode = pm.ls(refNode)[0]

        # rename the annotation and the top locator
        if groupLocator:
            annotationNode = pm.ls(newNodes, type='annotationShape')[0]
            annotationNode.getParent().v.set(False)
            pm.setAttr(annotationNode.text, assetName)
            pm.rename(annotationNode.root(), namespace + ':srt')
            annotationNode.root().lsx.set(10)
            annotationNode.root().lsy.set(10)
            annotationNode.root().lsz.set(10)

            # set the group transform to reference
            # so the contents can't be selected by accident
            if (not selectable):
                topTransforms = pm.listRelatives(annotationNode.root(),
                                                 type='transform')
                for transform in topTransforms:
                    pm.setAttr(transform.overrideEnabled, True)
                    pm.setAttr(transform.overrideDisplayType, 2)

        return newNodes
Esempio n. 51
0
# Deleting an interface.
# Interface must exist to use the command, or it will generate an error.
# pm.deleteUI('interface_name')

# Much check to see if the window exists first.

win_exists = pm.window(win_name, exists=True)
if win_exists:
    pm.deleteUI(win_name)

# -----------------------------------------------------------------------------
# Check to see if an attribute object exists
# -----------------------------------------------------------------------------

attribute_name = 'index_curl'
selected = pm.ls(sl=True)[0]
attr_exists = pm.attributeQuery(attr_name, node=selected[0], exists=True)

# -----------------------------------------------------------------------------
# Rename first and last item of a list.
# -----------------------------------------------------------------------------

selected = pm.ls(sl=True)
# len command returns how many items are inside of a list. (Chapter 4)
if len(selected) > 1:
    selected[0].rename('first')
    selected[-1].rename(
        'last')  # -1 index works from the end of the list. (Chapter 4)

# -----------------------------------------------------------------------------
# Converting Values
Esempio n. 52
0
 def loadSelectionSetWin(self):
     allsets = pm.ls(et='objectSet')
     for s in allsets:
         pm.textScrollList("selSetList", e=1, append=s)
Esempio n. 53
0
    def update_selection_list(self):
        sel = pm.ls(sl=1)
        if not sel or self.isHidden():
            return

        self.add_list_item([str(obj) for obj in sel])
Esempio n. 54
0
    def yetiLink(self):
        '''
		examine yeti
		'''
        self.allConnect()

        if 'pgYetiMaya' in pm.allNodeTypes():
            yetiNodeList = pm.ls(type='pgYetiMaya')
            yetiList = [node.getParent() for node in yetiNodeList]
            if yetiList:
                if not pm.objExists('yeti_G'):
                    OpenMaya.MGlobal_displayError('Not yeti_G Group')
                    return
                if not pm.objExists('yeti_setup_G'):
                    OpenMaya.MGlobal_displayError('Not yeti_setup_G Group')
                    return

                yetiGroup = pm.PyNode('yeti_G')
                if self.main.showMod not in yetiGroup.v.inputs(p=True):
                    self.main.showMod.connect(yetiGroup.v, f=True)

                if not self.main.hasAttr('yeti'):
                    self.main.addAttr('yeti',
                                      at='long',
                                      min=0,
                                      max=1,
                                      dv=0,
                                      k=True)

                if pm.PyNode('yeti_show_G') not in self.main.yeti.outputs():
                    self.main.yeti.connect('yeti_show_G.v', f=True)

                conAttrList = []

                for shape in yetiNodeList:
                    if shape.cacheFileName.get():
                        yeti = shape.getParent()
                        cons = yeti.listRelatives(type='parentConstraint')

                        if not cons:
                            OpenMaya.MGlobal_displayError(
                                'Not do %s node parentConstraint' % yeti)
                        else:
                            conAttrs = [
                                attr.listAttr(ud=True)[0] for attr in cons
                            ]

                            conAttrList += conAttrs

                        if not self.main.hasAttr('abc'):
                            self.main.addAttr('abc',
                                              at='enum',
                                              en="efx:anim:",
                                              k=True)
                            self.main.abc.set(1)

                        if self.main.abc not in shape.fileMode.inputs(p=True):
                            self.main.abc.connect(shape.fileMode, f=True)

                if conAttrList:
                    for att in conAttrList:
                        if self.main.abc not in att.inputs(p=True):
                            self.main.abc.connect(att, f=True)

                self.setMesh('pgYetiMaya')

                if conAttrList:
                    self.displayDialog(
                        '总控abc属性已关联yeti的约束节点和cache属性! 蒙皮模型已设置不可渲染, 并隐藏锁定!')
                else:
                    self.displayDialog(
                        '总控abc属性已关联yeti的cache属性! 蒙皮模型已设置不可渲染, 并隐藏锁定! 约束节点没有!')
        else:
            return False
    def option_box_apply(self):
        # Get the selected blendShapes.
        src_blend_shape = self.get_src_blend_shape_name()
        dst_blend_shape = self.get_dst_blend_shape_name()
        if not src_blend_shape or not dst_blend_shape:
            log.info('No blend shapes are selected')
            return

        src_blend_shape = pm.ls(src_blend_shape)[0]
        dst_blend_shape = pm.ls(dst_blend_shape)[0]

        if not src_blend_shape:
            pm.warning('No source blend shape is selected')
            return

        if not dst_blend_shape:
            pm.warning('No target blend shape is selected')
            return

        # These were selected from the UI, so unless the scene changed while the dialog was
        # open these should always be blendShape nodes.
        assert isinstance(
            src_blend_shape, pm.nodetypes.BlendShape
        ), 'Node %s isn\'t a blend shape' % src_blend_shape.nodeName()
        assert isinstance(
            dst_blend_shape, pm.nodetypes.BlendShape
        ), 'Node %s isn\'t a blend shape' % dst_blend_shape.nodeName()

        # Get the selected blend shape targets to retarget.
        blend_shape_targets = self.get_selected_src_blend_shape_targets()
        blend_shape_indices = [
            target.index() for target in blend_shape_targets
        ]
        if not blend_shape_indices:
            pm.warning('No blend shape targets are selected')
            return

        src_blend_shape_targets = pm.ls(
            pm.blendShape(src_blend_shape, q=True, g=True))
        dst_blend_shape_targets = pm.ls(
            pm.blendShape(dst_blend_shape, q=True, g=True))

        # Retarget the specified meshes.
        idx = pm.optionMenu(self.src_mesh_option_group, q=True,
                            select=True) - 1
        src_node = self.src_meshes[idx]

        idx = pm.optionMenu(self.dst_mesh_option_group, q=True,
                            select=True) - 1
        dst_node = self.dst_meshes[idx]

        if src_blend_shape == dst_blend_shape and src_node == dst_node:
            pm.warning('The source and destination blend shapes are the same')
            return

        # Check the selected nodes.
        assert src_node is not None, 'The source node %s isn\'t a mesh' % dst_node.nodeName(
        )
        assert dst_node is not None, 'The destination node %s isn\'t a mesh' % dst_node.nodeName(
        )
        src_node = src_node.getTransform()
        dst_node = dst_node.getTransform()

        connect_weights = pm.checkBoxGrp('connectWeightsToSource',
                                         q=True,
                                         value1=False)
        use_cvwrap = pm.checkBoxGrp('useCvWrap', q=True, value1=False)
        redst_blend_shapes(src_node,
                           dst_node,
                           src_blend_shape,
                           dst_blend_shape,
                           blend_shape_indices,
                           connect_weights=connect_weights,
                           use_cvwrap=use_cvwrap)
Esempio n. 56
0
                        "--sceneFolder",
                        help="scenegraph xml folder to get abc files",
                        default="")
    parser.add_argument("-u",
                        "--usdFolder",
                        help="put usd files in this folder",
                        default="")
    parser.add_argument(
        "-n",
        "--assetName",
        help=
        "asset name of the usda file,we use the scenegraph xml name if -n is empty",
        default='')

    args = None
    temp_args, unknow = parser.parse_known_args()
    args = vars(temp_args)

    return args


import maya.cmds as cmds
import pymel.core as pm

print "\n\n\n\n------------------------------------------------------------------"

file_name = "/home/xukai/Documents/TestProgramFactory/testing/mayapy/test.ma"
cmds.file(file_name, o=True, f=True)
for x in pm.ls():
    print x
Esempio n. 57
0
numP = 10
UVvalue = 'U'
definition = 20
layers = None


#####################################
def bla(surface, UVvalue=UVvalue, definition=definition, layers=layers):
    pass


#DON'T TOUCH LOWER PART OF THIS SCRIPT
history = True
#set the nurbs
pm.select(hi=True)
nurbsSurf = pm.ls(sl=1, type='nurbsSurface')[0]
#edit surface precision
pm.setAttr(nurbsSurf + '.curvePrecision', 14)

#if auto mode is On look for the biggest len with scale values
if auto == True:
    scaleX = nurbsSurf.getParent().scaleX.get()
    scaleZ = nurbsSurf.getParent().scaleZ.get()
    if scaleX > scaleZ:
        UVvalue = 'U'
    if scaleX < scaleZ:
        UVvalue = 'V'

#check if you can use the script to use the history on the orig shape
create = pm.connectionInfo(nurbsSurf + '.create', sfd=True)
if create == '' or create == []:
Esempio n. 58
0
def Selection():
    index = MPalette.getColor(parent=maya_main_window())

    for node in pm.ls(selection=True):
        node.overrideEnabled.set(True)
        node.overrideColor.set(index)
def mantleCreate(charaHeight = 2): #default 2, 160cm height
    
    curTime = pm.currentTime(query = True)
    
    if charaHeight == 5: #5 = motion character
        #create an exception to create key at the -100f + offset the rig into the right position
        pm.currentTime(-100, edit = True)
        mel.eval('source kkCharaSetup;\nkkCharaSetup();\nkkCharaBindPose_ex body;') #calling t-pose script from kkTools
        
    
    locM = pm.spaceLocator(name = 'locM')
    pm.xform(locM, ws = True, translation = [8.17948246602115e-16, 126.43254364390185, -8.830608530289298], scale = [3, 3, 3]) #shifting it into place
    locR = pm.spaceLocator(name = 'locR')
    pm.xform(locR, ws = True, translation = [-10, 124.043, -9.221], scale = [3, 3, 3]) #shifting it into place
    locRR = pm.spaceLocator(name = 'locRR')
    pm.xform(locRR, ws = True, translation = [-14, 129, -1.6], scale = [3, 3, 3]) #shifting it into place
    locL = pm.spaceLocator(name = 'locL')
    pm.xform(locL, ws = True, translation = [10, 124.043, -9.221], scale = [3, 3, 3]) #shifting it into place
    locLL = pm.spaceLocator(name = 'locLL')
    pm.xform(locLL, ws = True, translation = [14, 129, -1.6], scale = [3, 3, 3]) #shifting it into place
    
    heightPosition = {} #order of data is M, R, RR, L, LL
    heightPosition['1'] = [0, 117.518, -8.237], [-9.25, 115.129, -8.627], [-11, 120.1, -1.00], [9.25, 115.129, -8.627], [11, 120.1, -1] #1 = 150cm
    heightPosition['1sim'] = [0, 77.696 -9.781], [-19, 77.696, -9.919], [-28, 120.1, -1], [19, 77.696, -9.919], [28, 120.1, -1]
    heightPosition['2'] = [8.17948246602115e-16, 126.43254364390185, -8.830608530289298], [-10, 124.043, -9.221], [-14, 129, -1.6], [10, 124.043, -9.221], [14, 129, -1.6] #2 = 160cm
    heightPosition['2sim'] = [0, 80, -11.002], [-21.549, 80, -10.513], [-31, 129, -1.6], [21.549, 80, -10.513], [31, 129, -1.6]
    heightPosition['3'] = [0, 133.789, -13.546], [-11, 131.4, -13.936], [-15, 136.357, -4.721], [11, 131.4, -13.936], [15, 136.357, -4.721] #3 = 170cm
    heightPosition['3sim'] = [0, 79, -15.717], [-25.5, 79, -15.228], [-32, 136.357, -4.721], [25.5, 79, -15.228], [32, 136.357, -4.721]
    heightPosition['4'] = [0, 157.786, -14.305], [-12, 155, -14.695], [-20, 160.353, -4.5], [12, 155, -14.695], [20, 160.353, -4.5] #4 = 180cm
    heightPosition['4sim'] = [0, 100, -16.476], [-25.75, 100, -15.987], [-37, 160.353, -4.5], [25.75, 100, -15.987], [37, 160.353, -4.5]
    heightPosition['5'] = [8.17948246602115e-16, 126.43254364390185, -8.830608530289298], [-10, 124.043, -9.221], [-14, 129, -1.6], [10, 124.043, -9.221], [14, 129, -1.6] #5 = 160cm, same as 160 but for motion
    heightPosition['5sim'] = [0, 80, -11.002], [-21.549, 80, -10.513], [-31, 129, -1.6], [21.549, 80, -10.513], [31, 129, -1.6]
    
    
    #translating the locators to their position
    pm.xform('locM', ws = True, translation = heightPosition[str(charaHeight)][0], scale = [3, 3, 3])
    pm.xform('locR', ws = True, translation = heightPosition[str(charaHeight)][1], scale = [3, 3, 3])
    pm.xform('locRR', ws = True, translation = heightPosition[str(charaHeight)][2], scale = [3, 3, 3])
    pm.xform('locL', ws = True, translation = heightPosition[str(charaHeight)][3], scale = [3, 3, 3])
    pm.xform('locLL', ws = True, translation = heightPosition[str(charaHeight)][4], scale = [3, 3, 3])
    
    
    
    locList = [locM, locR, locRR, locL, locLL]
    locDict = {}
    locSimList = []
    
    for i in locList:
        sim = pm.duplicate(i, name = i[:3] + '_sim' + i[3:])
        locSimList.append(sim[0])
        locDict[i] = sim
    
    #translating the sim locators to their positions
    pm.xform('loc_simM', ws = True, translation = heightPosition[str(charaHeight) + 'sim'][0], scale = [3, 3, 3])
    pm.xform('loc_simR', ws = True, translation = heightPosition[str(charaHeight) + 'sim'][1], scale = [3, 3, 3])
    pm.xform('loc_simRR', ws = True, translation = heightPosition[str(charaHeight) + 'sim'][2], scale = [3, 3, 3])
    pm.xform('loc_simL', ws = True, translation = heightPosition[str(charaHeight) + 'sim'][3], scale = [3, 3, 3])
    pm.xform('loc_simLL', ws = True, translation = heightPosition[str(charaHeight) + 'sim'][4], scale = [3, 3, 3])
    
    if charaHeight == 5:
        pm.xform(locList, locSimList, translation = [0, 2.5, -3], relative = True, worldSpace = True)
    
    
    #____________________________________________________________________________________________________________________________________________________
    
    mantContr = mel.eval('curve -d 1 -p -0.5 1 0.866025 -p 0.5 1 0.866025 -p 0.5 -1 0.866025 -p 1 -1 0 -p 1 1 0 -p 0.5 1 -0.866025 -p 0.5 -1 -0.866025 -p -0.5 -1 -0.866026 -p -0.5 1 -0.866026 -p -1 1 -1.5885e-007 -p -1 -1 -1.5885e-007 -p -0.5 -1 0.866025 -p -0.5 1 0.866025 -p -1 1 -1.5885e-007 -p -0.5 1 -0.866026 -p 0.5 1 -0.866025 -p 1 1 0 -p 0.5 1 0.866025 -p 0.5 -1 0.866025 -p -0.5 -1 0.866025 -p -1 -1 -1.5885e-007 -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 -k 15 -k 16 -k 17 -k 18 -k 19 -k 20 -k 21 -k 22 -k 23 -n "controller1" ;')
    mantContr = pm.rename(mantContr, 'mantle_Control')
    pm.addAttr(mantContr, longName = 'Drag', attributeType = 'short', keyable = True, defaultValue = 5, minValue = 0) #adding drag attribute
    #hiding attributes on mantleControl
    pm.setAttr(mantContr + '.translateX', keyable = False)
    pm.setAttr(mantContr + '.translateY', keyable = False)
    pm.setAttr(mantContr + '.translateZ', keyable = False)
    pm.setAttr(mantContr + '.rotateX', keyable = False)
    pm.setAttr(mantContr + '.rotateY', keyable = False)
    pm.setAttr(mantContr + '.rotateZ', keyable = False)
    pm.setAttr(mantContr + '.scaleX', keyable = False)
    pm.setAttr(mantContr + '.scaleY', keyable = False)
    pm.setAttr(mantContr + '.scaleZ', keyable = False)
    
    
    pm.select(deselect = True)#deselect so it won't be the child of anything
    mantleParent = pm.joint(name = 'mantleParent', position = pm.xform('locM', query = True, worldSpace = True, translation = True), radius = 2.5)#creating mantle parent
    
    
    #main joints
    jointList = {}
    for i in locList:
        pm.select(deselect = True)#deselect so it is parented to world
        j = pm.joint(name = 'joint' + i[3:], position = pm.xform(i, query = True, worldSpace = True, translation = True), radius = 2.5)
        jointList[j] = None
        #setting transform and rotation limits
        if i[2:5] == 'cR':
            pm.transformLimits(j, rotationX = [-4, 90], rotationY = [-90, 45], rotationZ = [-45, 25], erx = [True, True], ery = [True, True], erz = [True, True])
        elif i[2:5] == 'cM':
            pm.transformLimits(j, rotationX = [-4, 90], rotationY = [-45, 45], rotationZ = [-50, 50], erx = [True, True], ery = [True, True], erz = [True, True])
        elif i[2:5] == 'cL':
            pm.transformLimits(j, rotationX = [-4, 90], rotationY = [-45, 90], rotationZ = [-25, 45], erx = [True, True], ery = [True, True], erz = [True, True])
    
    #main sims
    for i in jointList:
        pm.select(i) #selecting so it is parented to parent joint
        sim = pm.joint(name = 'sim' + i[5:], position = pm.xform('loc_sim'+i[5:], query = True, worldSpace = True, translation = True), radius = 1.5)
        jointList[i] = sim
        pm.xform(pm.ls(sl = True)[0], translation = (pm.getAttr(pm.ls(sl = True)[0].translate) * 0.5)) #this shortens the length of the sim joint by half
        if i[5:] == 'LL' or i[5:] == 'RR':#orienting joint so it move appropriately from UpperArm2
            print('re-orient' + i)
            pm.joint(i, edit = True, orientJoint = 'xyz', secondaryAxisOrient = 'zup', zeroScaleOrient = True) 
            
    
    
    
    pm.select(deselect = True)
    
    for i in jointList: #selecting joints
        pm.select(i, add = True)
    
    pm.parent(pm.ls(sl = True), mantleParent)
    
    #calc
    calcList = []
    mantGroup = pm.group(name = 'mantleGroup', world = True, empty = True)#creating calc joints
    for i in pm.listRelatives(mantleParent):
        cal = pm.duplicate(i, name = i[:7] + '_Calc', parentOnly = True)
        pm.parent(cal, mantGroup)
        spaceLoc = pm.spaceLocator(name = 'simLoc_' + i[5:])#creating simloc locator
        pm.xform(spaceLoc, ws = True, translation = pm.xform('sim' + i[5:], query = True, translation = True, ws = True))#moving it to the right place
        
        #creating expression to drive the SimLoc's translations
        pm.expression(object = spaceLoc, name = spaceLoc + '_translationExp', string = '$f = `currentTime -q`;\n$lastposX = `getAttr -t ($f - mantle_Control.Drag) %s.translateX`;\n%s.translateX = %s.translateX - (%s.translateX - $lastposX) + %s;\n$lastposY = `getAttr -t ($f - mantle_Control.Drag) %s.translateY`;\n%s.translateY = %s.translateY - (%s.translateY - $lastposY) + %s;\n$lastposZ = `getAttr -t ($f - mantle_Control.Drag) %s.translateZ`;\n%s.translateZ = %s.translateZ - (%s.translateZ - $lastposZ) + %s;' %(cal[0], spaceLoc, cal[0], cal[0], pm.getAttr('sim'+i[5]+'.translateX'), cal[0], spaceLoc, cal[0], cal[0], pm.getAttr('sim'+i[5]+'.translateY'), cal[0], spaceLoc, cal[0], cal[0], pm.getAttr('sim'+i[5]+'.translateZ')))
        
        '''
        '$f = `currentTime -q`;\n
        $lastposX = `getAttr -t ($f - mantle_Control.Drag) %s.translateX`;\n
        %s.translateX = %s.translateX - (%s.translateX - $lastposX);\n
        $lastposY = `getAttr -t ($f - mantle_Control.Drag) %s.translateY`;\n
        %s.translateY = %s.translateY - (%s.translateY - $lastposY) - 25.627;\n
        $lastposZ = `getAttr -t ($f - mantle_Control.Drag) %s.translateZ`;\n
        %s.translateZ = %s.translateZ - (%s.translateZ - $lastposZ);' %(cal[0], spaceLoc, cal[0], cal[0], cal[0], spaceLoc, cal[0], cal[0], cal[0], spaceLoc, cal[0], cal[0])
        '''
        
        
        pm.parent(spaceLoc, mantGroup)
        if not cal[0][5:7] == 'RR' and not cal[0][5:7] == 'LL':
            calcList.append(cal[0])
        #creating transform limits for calc joints
        pm.transformLimits(cal[0], rotationX = [-5, 360], enableRotationY = [True, False])
    
    pm.delete('simLoc_RR', 'simLoc_LL', 'jointRR_Calc', 'jointLL_Calc')#deleting the RR and LL simlocs that we won't need
    pm.parent(mantleParent, 'spine2')#parenting main joints into joint hierarchy
    
    #calcDriver
    calcDriver = pm.duplicate(mantleParent, parentOnly = True, name = 'mantleCalcDriver')#creating calcDriver joints
    for i in pm.listRelatives(mantleParent):
        j = pm.duplicate(i, name = i[:7] + '_CalcDriver', parentOnly = True)
        pm.parent(j, calcDriver)
    
    
    #create the constraints for calcDriver -> calc
    for i in calcList:
        pm.parentConstraint(i + 'Driver', i, mo = False)
    
    #create IK
    
    for i in pm.listRelatives('mantleGroup', type = 'transform'):#constraining IKs to calc locators
        if i.find('Loc') != -1:
            ik = pm.ikHandle(name = 'ikHandle' + i[7], sj = 'joint' + i[7], ee = pm.listRelatives('joint' + i[7])[0], solver = 'ikRPsolver')[0]
            #take out the translation limit first
            #pm.transformLimits(ik, translationZ = [-100, -1], etz = [False, True]) #setting a limit on the z transform of the IK handle, so it won't go past the body and penetrate
            pm.setAttr(ik+'.poleVectorX', 0) #adjusting the polevectors to 0, so it won't flip and be weird
            pm.setAttr(ik+'.poleVectorY', 0)
            pm.setAttr(ik+'.poleVectorZ', 0)
            pm.parent(ik, mantleParent)
            pm.parentConstraint(i, ik, mo = False)
    
    pm.parentConstraint('L_upperarm2', 'jointLL', mo = True)
    pm.parentConstraint('R_upperarm2', 'jointRR', mo = True)
    
    pm.delete(locList, locSimList) #deleting unnecessary stuff used to create the rig
    
    if charaHeight == 1:#importing mantle Mesh
        cmds.file('K:/design/maya/data/tool/scData/Mant/mantMesh/mantMesh150.ma', i = True)
    elif charaHeight == 2:
        cmds.file('K:/design/maya/data/tool/scData/Mant/mantMesh/mantMesh160.ma', i = True)
    elif charaHeight == 3:
        cmds.file('K:/design/maya/data/tool/scData/Mant/mantMesh/mantMesh170.ma', i = True)
    elif charaHeight == 4:
        cmds.file('K:/design/maya/data/tool/scData/Mant/mantMesh/mantMesh180.ma', i = True)
    else:
        cmds.file('K:/design/maya/data/tool/scData/Mant/mantMesh/mantMesh160.ma', i = True)
        pm.xform('mantMesh', translation = [0, 2.5, -3], worldSpace = True, relative = True)
    
    if not charaHeight == 0:
        pm.skinCluster(pm.listRelatives(mantleParent), mantleParent, 'mantMesh', toSelectedBones = True)
        pm.select('mantMesh')
        mel.eval('source kkCharaSetup;kkCharaSetup_charaWeight_r;')#imports weights from data embedded inside already
        
    if charaHeight == 5:
        pm.select(deselect = True)
        mel.eval('global string $pickrPrefix="";abxPickerSelect " L_knee_ctrl R_knee_ctrl L_hand_ctrl R_elbow_ctrl R_hand_ctrl L_elbow_ctrl head R_wrist_ctrl R_shoulder L_wrist_ctrl L_shoulder neck spine2 spine1 waist hips pelvis R_foot_ctrl L_foot_ctrl L_toe_ctrl R_toe_ctrl";')
        pm.cutKey(time = -100)
        pm.currentTime(0, edit = True)
        
        pm.currentTime(curTime, edit = True) #end
    pm.select(deselect = True)
    
    #outliner management
    pm.xform(mantContr, translation = pm.xform(mantleParent, query = True, worldSpace = True, translation = True), worldSpace = True) #moving Mantle Control to 
    pm.xform(mantContr, translation = [0, 0, -5], worldSpace = True, relative = True)  #offset to the back a little
    pm.parentConstraint(mantleParent, mantContr, mo = True) #constraining controller to mantle parent
    pm.parent(mantContr, 'mantMesh', 'CharaA')
    
    print(u'EKKO マントリッグインストールしました。')
Esempio n. 60
0
dfmedShps = [x for x in pm.listRelatives(ad=True, type="mesh") if "Deformed" in x.name()]
for dfmedShp in dfmedShps:
	trsf = pm.listRelatives( dfmedShp, parent=True )
	shp = [ x for x in pm.listRelatives( trsf ) if not "Deformed" in x ]
	if shp:
		shp[0].setAttr("intermediateObject", False)
		pm.delete(dfmedShp)


##############################################
# Select Joint Hierarchy Excluding End Joint #
##############################################
import pymel.core as pm

selJnts = pm.ls(sl=True)
bndJnts = [x for x in pm.listRelatives(selJnts, ad=True, type="joint") if pm.listRelatives(x, c=True, type="joint")]
pm.select(selJnts, bndJnts, r=True)



####################################
# Bake Posints Animation to Joints #
####################################
import pymel.core as pm

pntJntDic = {}

# Create joints
selPnts = pm.ls(sl=True, fl=True)