Пример #1
0
	def bdMirrorCon(self):
		print 'Mirror Controller'
		
		selection = pm.ls(sl=True)
		if selection.count > 0:
			for sel in selection:
				if ('L_' in sel.name()) or ('R_' in sel.name()):
					print sel.name()
					conGrp = sel.getParent()
					conGrpPos = conGrp.getTranslation(space='world')
					conGrpRot = conGrp.getRotation(space='world')
					
					exp = ['L_','R_']
					if 'R_' in conGrp.name():
						exp.reverse()
					print exp
					mirrorConGrp = pm.duplicate(conGrp,name = conGrp.name().replace(exp[0],exp[1]))[0]
					mirroCon = mirrorConGrp.getChildren()[0]
					mirroCon.rename(sel.name().replace(exp[0],exp[1]))
					mirroCon.getShape().overrideColor.set(self.conColors[exp[1]])
					
					mirrorConGrp.setTranslation([conGrpPos[0]*-1,conGrpPos[1],conGrpPos[2]])
					mirrorConGrp.setRotation([conGrpRot[0],conGrpRot[1],conGrpRot[2]*-1])
				else:
					pm.warning( 'Central controller, no need (sic) to mirror it!')
Пример #2
0
def delete_unused_nodes():
    """deletes unused shading nodes
    """
    num_of_items_deleted = pm.mel.eval('MLdeleteUnused')
    if num_of_items_deleted:
        # do not raise any error just warn the user
        pm.warning('Deleted unused nodes during Publish operation!!')
Пример #3
0
    def _unbuild_modules(self, strict=False, **kwargs):
        # Unbuild all children
        for module in self.modules:
            if not module.is_built():
                continue

            # If we are unbuilding a rig and encounter 'locked' modules, this is a problem
            # because we cannot touch it, however we need to free the grp_anm and grp_rig to
            # delete them properly.
            # In that situation we'll unparent the module grp_anm and grp_rig node.
            if module.locked:
                if module.grp_anm and module.grp_anm.exists() and module.grp_anm.getParent() == self.grp_anm.node:
                    pymel.warning(
                        "Ejecting {0} from {1} before deletion".format(module.grp_anm.name(), self.grp_anm.name()))
                    module.grp_anm.setParent(world=True)
                if module.grp_rig and module.grp_rig.exists() and module.grp_rig.getParent() == self.grp_rig.node:
                    pymel.warning(
                        "Ejecting {0} from {1} before deletion".format(module.grp_rig.name(), self.grp_rig.name()))
                    module.grp_rig.setParent(world=True)
            else:
                try:
                    module.unbuild(**kwargs)
                except Exception, e:
                    self.error("Error building {0}. Received {1}. {2}".format(module, type(e).__name__, str(e).strip()))
                    traceback.print_exc()
                    if strict:
                        raise (e)
Пример #4
0
	def copyPlayblast(self):
		blastFiles = []

		f=''
		wipPath = self.wipFolderEdit.text()

		selectedItems = self.wipAnimTable.selectedItems()
		
		if len(selectedItems):
			for item in selectedItems:
				if item.text() == 'Yes':
					animFile = self.wipAnimTable.item(item.row(),0).text()
					blastFile = self.hasPlayblast(animFile)
					wipBlastPath,blastFileName = os.path.split(blastFile)
					destPath = wipPath.replace('01_wip','03_preview')
					if destPath == wipPath:
						destPath = wipPath.replace('01_WIP','03_PREVIEW')
					dest = os.path.abspath(os.path.join(destPath,blastFileName))
					
					
					if os.path.isfile(blastFile):
						if os.path.isfile(dest):
							pm.warning('Blast exists already, will not overwrite ( save new version ? )')
						else:
							try:
								print("copying")
								shutil.copyfile(blastFile, dest)
								try:
									os.remove(blastFile)
								except OSError:
									pass
								self.bdPopulateFiles()
							except:
								pm.error('Could not copy blast file to preview')
Пример #5
0
	def getLastVersion(self):
		fileList = []
		baseNameList = []
		lastVersionList = []

		rows  = self.wipAnimTable.rowCount()
		for i in range(rows):
			print self.wipAnimTable.item(i,0)
			fileList.append(self.wipAnimTable.item(i,0).text().split('.')[0])
		for f in fileList:
			baseName = ''
			temp = f.split('_')
			if len(temp) > 5:
				for i in range(len(temp) -1 ):
					baseName += (temp[i] + '_')
				baseNameList.append(baseName[:-1])
			else:
				pm.warning('Didnt find versions for file %s'%f)
				continue

		print baseNameList
		tempSet = sorted(list(set(baseNameList)))
		for name in tempSet:
			if baseNameList.count(name) < 10:
				lastVersionList.append(name + '_0' +  str(baseNameList.count(name)))
			else:
				lastVersionList.append(name + '_' +  str(baseNameList.count(name)))

		return lastVersionList
Пример #6
0
	def setWipFolder(self):
		currentScene = pm.sceneName()
		if currentScene:
			projectPath,fileName = os.path.split(currentScene)
			wipFolder = ''
			try:
				wipFolder = pm.fileDialog2(dir=projectPath,ds=2,fm=3,okc='Select Folder')[0]
			except:
				pm.warning('No folder was selected')

			if wipFolder:
				self.wipFolderEdit.setText(wipFolder)
				self.wipFolderPath = wipFolder
				self.bdPopulateFiles()
		else:
			projectPath = pm.workspace.path
			charactersFolder = os.path.abspath(os.path.join(projectPath,'scenes','characters'))
			path = ''
			try:
				path = pm.fileDialog2(dir=charactersFolder,ds=2,fm=3,okc='Select Folder')[0]
			except:
				pm.warning('No folder was selected')
			if path:
				self.wipFolderEdit.setText(path)
				self.wipFolderPath = path
				self.bdPopulateFiles()
Пример #7
0
	def copyAnim(self):
		animFiles = []
		f=''
		wipPath = self.wipFolderEdit.text()

		selectedItems = self.wipAnimTable.selectedItems()

		if len(selectedItems):
			for item in selectedItems:
				if item.column() ==0:
					anim = item.text()
					print anim
					src = os.path.abspath(os.path.join(wipPath,anim))

					destPath = wipPath.replace('01_wip','03_preview')
					dest = os.path.abspath(os.path.join(destPath,anim))
					
					if os.path.isfile(src):
						if os.path.isfile(dest):
							pm.warning('Preview file exists already, will not overwrite ( save new version ? )')
						else:
							try:
								shutil.copyfile(src, dest)
							except:
								pm.error('Could not copy anim file to preview')
			
			self.bdPopulateFiles()
Пример #8
0
	def bdCreateCircleCon(self):
		print 'Circle Controller'
		test = mui.MQtUtil.findControl('createConBtn1')
		print test
		
		animConName = self.bdGetConName()
		if animConName != '':
			conSize = self.inputConSize.text()
			overrideColor = self.conColors[str(self.inputConSide.currentText())]
	
			if not conSize:
				conSize=1
				
			selection = pm.ls(sl = True)
			selPos = [0,0,0]
			selRot = [0,0,0]
			if selection:
				selPos = selection[0].getTranslation(space='world')
				selRot = selection[0].getRotation(space='world')
						
			circleCon = pm.circle(n = animConName ,nr=(0, 1, 0), c=(0, 0, 0),radius=float(conSize) ) [0]
			circleCon.getShape().overrideEnabled.set(1)
			circleCon.getShape().overrideColor.set(overrideColor)
			circleConGrp = pm.group(circleCon,name = circleCon.name() + '_GRP')
			circleConGrp.setTranslation(selPos)
			circleConGrp.setRotation(selRot)
		else:
			pm.warning('Need a name, aborting')
Пример #9
0
 def getCurrentTranslator(self, nodeName):
     """
     get the current translator for this node, querying and setting the default if not yet set
     """
     try :
         # asString allows for enum attributes as well
         transName = pm.getAttr(nodeName + ".aiTranslator", asString=True)
     except :
         transName = None
     translators = self.getTranslators()
     if not transName or transName not in translators:
         # set default
         transName = getDefaultTranslator(nodeName)
         if transName is None:
             if not translators:
                 pm.warning("cannot find default translator for %s" % nodeName)
                 return
             transName = translators[0]
         try :
             pm.setAttr(nodeName + ".aiTranslator", transName)
         except:
             pm.warning("cannot set default translator for %s" % nodeName)
             import traceback
             traceback.print_exc()
     return transName
Пример #10
0
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!")

		'''
Пример #11
0
 def create_new_pose_prompt(self):
     if not pm.selected():
         pm.warning ("Please Select an Object")
         return
     
     namespace = pm.selected()[0].split(":")[0]
     targetObj = "%s:geo"%(namespace)           
             
     result = pm.promptDialog(
         title='Create New Pose',
         message='Enter Pose Name:',
         button=['OK', 'Cancel'],
         defaultButton='OK',
         cancelButton='Cancel',
         dismissString='Cancel')
     
     if result == 'OK':
         name = pm.promptDialog(query=True, text=True)
         directory = self.get_active_directory()
         
         path = os.path.join(directory, "%s.pose" %name)
         pose_obj = Pose(path)
         pose_obj.create()
         
         pose_obj.save_pose()
         pose_obj.update_thumbnail(targetObj)
         
         self.populate_library_layout()
Пример #12
0
    def copyZoobeAnimations(self,zoobeChar):
        print 'Importing Zoobe Animations'


        if zoobeChar:
            sourceChar = 'source:' + zoobeChar
            fuseChar = self.name

            rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma')

            zoobeCharFolder = os.path.join(ANIM_LIB_PATH,zoobeChar)
            if os.path.isdir(zoobeCharFolder):
                animFiles = [f for f in os.listdir(zoobeCharFolder) if (f.endswith('.ma') or f.endswith('.mb'))]
                animFile = '/home/zoobe/mixamo/testproject/incoming/animLib/violet/violet_angry_action_01.ma'
                #self.copyAnimation(animFile,sourceChar,fuseChar,0,300)

                for anim in animFiles:
                    print animFile
                    animPath = os.path.join(zoobeCharFolder,anim)
                    print animPath 
                    pm.openFile(animPath,f=1)
                    start = pm.playbackOptions(q=1,ast=1)
                    end = pm.playbackOptions(q=1,aet=1)
                    print start, end
                    self.copyAnimation(animPath,sourceChar,fuseChar,start,end)
                    print 'saving animation %s'%anim.split('.')[0]

                    self.saveAnimation(anim.split('.')[0])
            else:
                pm.warning('Did not find %s char folder'%zoobeChar)
Пример #13
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
Пример #14
0
def loadDeformerWeights(filename=None):
	'''
	Usage:
		loadDeformerWeights(filename='/jobs/mercedesFable_5402587/build/charTortoise/maya/export/WEIGHTS/tortoiseAFacial/extraWeights/deformerWeights/v03/deformerWeights.json')
		loadDeformerWeights()
	'''
	if not filename:
		try:
			filename = pm.fileDialog2(cap='Select a json file you stored', fm=1, okc='Load', ff='JSON (*.json)')[0]
		except:
			pm.error('file not found, whatever.')
	with open(filename, 'rb') as fp:
		data = json.load(fp)
		for key in data.keys():
			if pm.objExists(key):
				deformer = Deformer(pm.PyNode(key))
				print 'Loading weights for deformer:\t%s'%deformer
				for deformedShape in data[key].keys():
					if pm.objExists(deformedShape):
						print '\tLoading deformer weights on shape:\t%s'%deformedShape
						deformedTransform = pm.PyNode(deformedShape).getParent()
						#print data[key][deformedShape]
						deformer.setWeights(data[key][deformedShape], deformedTransform)
					else:
						pm.warning('Object %s does not exist to apply deformer weights to...skipping'%deformedShape)
			else:
				pm.warning('Deformer %s doesn\'t exist...skipping'%key)
Пример #15
0
def save_poseDeformerList(obj):
	'''stores poseDeformer files for the curreitnnt object
	Args:
		obj (pm.PyNode): the object to get deformers from
	Returns (boolean): whether the export worked on not
	Usage:
		save_poseDeformerList(pm.ls(sl=True)[0])
	'''
	poseDeformers = get_connectedPoseDeformers(obj)
	if poseDeformers:
		folder = os.path.join( environ.POSEDEFORMERS, obj )
		versionFolder = lib_env.folder_detectVersions( folder, versionUp=True )
		if versionFolder:
			folder = versionFolder
		else:
			folder = os.path.join(folder, 'v001')
		if not os.path.exists(folder):
			os.makedirs(folder)
		for poseDeformer in poseDeformers:
			file = os.path.join(folder, poseDeformer+'.ma')
			command = 'poseDeformer_export(\"%s\", \"%s\", -1)'%(poseDeformer,file)
			print command
			eval( command ) 
	else:
		pm.warning('Object %s has no pose deformers attached to it...'%obj)
Пример #16
0
def vPrint(txt, verb=2, type=0):
    """global verbose print function
        # gVerb = 2 print each step
        # gVerb = 1 print problemes
        # gVerb = 0 print nothing
        # type = 0 print
        # type = 1 warning
        # type = 2 error
    """
    global gVerb
    if verb <= gVerb:
        
        # to properly distinguish probleme from everything else
        if verb == 1:
            start = '\t1# '
        else:
            start = '\t # '
        
        # and then print everything
        if type == 0:
            print start + txt
        elif type == 1:
            pmc.warning(start + txt)
        else:
            pmc.error(start + txt)
Пример #17
0
def rig_makeBlockGeo(meshes, constrain=False, *args):
    '''
    Args:
        meshes (list(pm.nt.Transform)): meshes to cut up
        constrain (boolean): whether to constrain them or not
    Returns:
        list (pm.nt.Transform): list of block geometries created
    Usage:
        rig_makeBlockGeo(pm.ls(sl=True), constrain=True)
    '''
    blockgeos=[]
    joints=[]
    for mesh in meshes:
        skinCluster = rig_getConnectedSkinCluster(mesh)
        if skinCluster:
            joints+= skinCluster.getWeightedInfluence()
            if len(joints)==1:
                dup=pm.duplicate(mesh, n=mesh.name().replace('GEO','BLOCKGEO'))[0]
                blockgeos.append(dup)
                rig_unlockTransform(dup)
                pm.parentConstraint(joints[0], dup, mo=True)
            else:
                for joint in joints:
                    blockgeo = rig_makeBlockGeoFromJoint([mesh], joint)
                    if blockgeo:
                        if pm.objExists(blockgeo):
                            blockgeos+=blockgeo
                            pm.delete(blockgeo, ch=True)
                            if constrain:
                                for geo in blockgeo:
                                    rig_unlockTransform(geo)
                                    pm.parentConstraint(joint, geo, mo=True)
        else:
            pm.warning('No skinCluster detected on mesh %s' % mesh)
    return blockgeos
Пример #18
0
    def populateOutputs(self):
        self.publishAsComboBox.blockSignals(True)
        self.publishAsComboBox.clear()
                        
        if not self.selVizNode:
            return

        origName = pm.getAttr('%s.originalName'%self.selVizNode)      
        creature = bdNamingConventions.getCharacterFromFullname(origName)
   
        if creature in self.vampList:
            vampList = [NAMES_INFO[char]['fullname'] for char in self.vampList]
            vampList.sort()
            self.publishAsComboBox.addItems(vampList)   
        elif creature in self.wolfList and 'young' in creature:
            wolfList = [NAMES_INFO[char]['fullname'] for char in self.wolfList if 'young' in char]                     
            wolfList.sort()
            self.publishAsComboBox.addItems(wolfList) 
        elif creature in self.wolfList and 'young' not in creature:
            wolfList = [NAMES_INFO[char]['fullname'] for char in self.wolfList if 'young' not in char]                     
            wolfList.sort()
            self.publishAsComboBox.addItems(wolfList)
        else:
            pm.warning('Creature name %s not recognized' % creature)
            
        self.publishAsComboBox.blockSignals(False)    
Пример #19
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
Пример #20
0
    def exportAnimation(self):
        exportFolder = ASSETS_PATH + 'characters/' + self.name + '_std/animations/'
        exportAnimationsPath = os.path.join(CHARACTERS_PATH ,self.name,'animation')
        animFiles = []
        if os.path.isdir(exportAnimationsPath):
            animFiles = [f for f in sorted(os.listdir(exportAnimationsPath)) if f.endswith('.ma') or f.endswith('.ma') ]
        else:
            pm.warning('No animation files found, aborting!')
            return
        #self.logger.info('########### Exporting animations for OGRE ###########')
        for anim in animFiles:
            animFile = os.path.join(exportAnimationsPath,anim)
            pm.openFile(animFile,f=1)
            start = int(pm.playbackOptions(q=1,ast=1))
            end = int(pm.playbackOptions(q=1,aet=1))
            #ogreExport -all -outDir "P:/mixamo_character/assets/characters/EveBavaria_std/animations/" -skeletonClip "EveBavaria_action_unjured_walk_35" startEnd 0 34 frames sampleByFrames 1 -lu pref -scale 1.00 -skeletonAnims -skelBB -np bindPose

            cmd = 'ogreExport -all -outDir "'+ exportFolder + '"'
            cmd += ' -skeletonClip "' + anim.split('.')[0] + '"'
            if 'speak' in anim:
                cmd += ' startEnd 0 1' 
            else:
                cmd += ' startEnd ' + str(start) + ' ' + str(end)
            cmd += ' frames sampleByFrames 1 -lu pref -scale 1.00 -skeletonAnims -skelBB -np bindPose'

            pm.mel.eval(cmd)
Пример #21
0
def checkAndLoadPlugin(pluginName):
    """ Checks and loads plugin with GUI dialogs """
    if pm.pluginInfo(pluginName, query=True, loaded=True) == False:
        ans = pm.confirmDialog(
            title="Warning!!!",
            message="%s not loaded,,, \n Do you wish to load it now?" % pluginName,
            button=["YES", "NO"],
            defaultButton="YES",
            dismissString="NO",
        )
        if ans == "YES":
            try:
                pm.loadPlugin(pluginName)
                return True
            except RuntimeError:
                pm.warning("%s plugin not found in path!" % pluginName)
                pm.confirmDialog(
                    title="Warning!!!",
                    message="%s plugin not found!" % pluginName,
                    button=["OK"],
                    defaultButton="OK",
                    dismissString="OK",
                )
                return False  # TODO : Raise Plugin Not Found Error!
        if ans == "NO":
            return False
Пример #22
0
def uiAddWidgetSizeAnim(widget, onoff, size, size_offset=0):
    size_anim = None
    try:
        print widget
        size_anim = QtCore.QPropertyAnimation(widget, "geometry")
    except:
        pm.warning("Failed to create QPropertyAnimation ")
    geometry = widget.geometry()
    width = geometry.width()
    x, y, _, _ = geometry.getCoords()
    size_start = QtCore.QRect(x, y, width, int(not (onoff)) * size + size_offset)
    size_end = QtCore.QRect(x, y, width, onoff * size + size_offset)

    size_anim.setStartValue(size_start)
    size_anim.setEndValue(size_end)
    size_anim.setDuration(200)

    size_anim_curve = QtCore.QEasingCurve()
    if onoff:
        size_anim_curve.setType(QtCore.QEasingCurve.InQuad)
    else:
        size_anim_curve.setType(QtCore.QEasingCurve.OutQuad)

    size_anim.setEasingCurve(size_anim_curve)

    return size_anim
Пример #23
0
 def get_sel_nucleus(self):
     print 'get_sel_nuclues'
     cmd = 'ls -sl -dag -lf -l -type nucleus'
     self.Nucleus = pm.mel.eval(cmd)
     if not self.Nucleus:
         pm.warning('select some nuclues first.')
     print self.Nucleus
Пример #24
0
	def bdCreateCircleZCon(self):
		print 'Circle Z Controller'
		animConName = self.bdGetConName()
		if animConName!='':
			conSize = self.inputConSize.text()
			overrideColor = self.conColors[str(self.inputConSide.currentText())]
			if not conSize:
				conSize=1
				
			selection = pm.ls(sl = True)
			selPos = [0,0,0]
			selRot = [0,0,0]
			if selection:
				selPos = selection[0].getTranslation(space='world')
				selRot = selection[0].getRotation(space='world')
						
			circleCon = pm.circle(n = animConName ,nr=(0, 1, 0), c=(0, 0, 0),radius=int(conSize) )[0]
			circleCon.getShape().overrideEnabled.set(1)
			circleCon.getShape().overrideColor.set(overrideColor)
			
			circleConGrp = pm.group(circleCon,name = circleCon.name() + '_GRP')
			conCvs = circleCon.cv
			zDirectionPos = conCvs[5].getPosition(space = 'world')
			zDirectionPos[2] = zDirectionPos[2] * 1.25
			print zDirectionPos
			conCvs[5].setPosition(zDirectionPos)
			
			circleConGrp.setTranslation(selPos,space='world')
			circleConGrp.setRotation(selRot,space='world')
		else:
			pm.warning('Need a name, aborting')
Пример #25
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'
    '''
Пример #26
0
def transfer_rotation_to_joint_orient(obj):
    """
    In Maya it is not possible to do a "makeIdentity" command on a joint that is bound to a skinCluster.
    This method bypass this limitation.
    """
    mfn = obj.__apimfn__()

    rotation_orig = OpenMaya.MEulerRotation()
    mfn.getRotation(rotation_orig)
    rotation_xyz = rotation_orig.reorder(OpenMaya.MEulerRotation.kXYZ)

    # Apply existing jointOrient values
    orientation_orig = OpenMaya.MEulerRotation()
    mfn.getOrientation(orientation_orig)
    rotation_xyz *= orientation_orig

    def is_attr_accessible(attr):
        return not attr.isFreeToChange() == OpenMaya.MPlug.kFreeToChange

    if is_attr_accessible(obj.rotateX) or is_attr_accessible(obj.rotateY) or is_attr_accessible(obj.rotateZ):
        pymel.warning("Can't transfer rotation to joint orient. {0} rotation is locked.".format(obj.name()))
        return

    if is_attr_accessible(obj.jointOrientX) or is_attr_accessible(obj.jointOrientY) or is_attr_accessible(obj.jointOrientZ):
        pymel.warning("Can't transfer rotation to joint orient. {0} jointOrient is locked.".format(obj.name()))
        return

    obj.jointOrientX.set(math.degrees(rotation_xyz.x))
    obj.jointOrientY.set(math.degrees(rotation_xyz.y))
    obj.jointOrientZ.set(math.degrees(rotation_xyz.z))
    obj.rotateX.set(0)
    obj.rotateY.set(0)
    obj.rotateZ.set(0)
Пример #27
0
def ec_zero(attr="all"):
    selection = mc.ls(sl=True, type='transform')
    try:
        if attr == "sx" or attr == "sy" or attr == "sz":
            for i in range(0, len(selection)):
                mc.setAttr(selection[i]+"."+attr, 1.0)
        elif attr == "s":
            for i in range(0, len(selection)):
                mc.setAttr(selection[i]+"."+attr, 1, 1, 1, type="double3")
        elif attr == "all":
            for i in range(0, len(selection)):
                listat = mc.listAttr(selection[i], v=True, k=True)
                print "listat :"
                if listat is None:
                    print "ERROR: listat is None : %s" % selection[i]
                else:
                    for k in range(0, len(listat)):
                        if listat[k] == "scaleX" or listat[k] == "scaleY" or listat[k] == "scaleZ" or listat[k] == "scale" or\
                                        listat[k] == "visibility":
                            mc.setAttr(selection[i]+"."+listat[k], 1.0)
                        else:
                            mc.setAttr(selection[i]+"."+listat[k], 0.0)
        else:
            if attr == "t" or attr == "r":
                for i in range(0, len(selection)):
                    mc.setAttr(selection[i]+"."+attr, 0.0, 0.0, 0.0, type="double3")
            else:
                for i in range(0, len(selection)):
                    mc.setAttr(selection[i]+"."+attr, 0.0)
        py.headsUpMessage("Reset: %s attribute of object %s" % (attr, selection))
    except:
        py.warning("ERROR: %s attribute of %s is locked or otherwise unavailable to reset" % (attr, selection[i]))
Пример #28
0
def FindDeformers ( shape=None , type=''):
	
	if shape==None:
		obj = pm.ls(sl=True)[0]
		shape = obj.getShape()
	
	if shape :
		# List Deformers
		history = pm.listHistory( shape, pruneDagObjects=True, interestLevel=2 ) 
		
		deformers = []
		
		for node in  history :
			nodeTypes = pm.nodeType( node, inherited=True )
		
			if 'geometryFilter' in nodeTypes:
				
				if type=='' and  nodeTypes[1] != 'tweak' :
					deformers.append(node)
			
				elif nodeTypes[1] == type and nodeTypes[1] != 'tweak':
					deformers.append(node)
		
		return deformers
	else:
		pm.warning('No shape found.')
Пример #29
0
def add_to_bake_layer( layer = None, objects = None ):

  
  # Get the node for the bake Layer  
  
  layer_node = get_bake_layer( layer )
  if layer_node == None:
    pmc.error( 'add_to_bake_layer requires one "BakeLayer" node.')
  
  # get the list of nodes for the objects
  
  if objects == None:
    pmc.warning( 'No objects specified, using selection' )
    obj_list = pmc.ls( sl = True, typ = 'transform' ) 
  
  elif isinstance( objects, pmc.nt.Transform ):
    obj_list = [ objects ]
  
  elif isinstance( pmc.PyNode( objects ), pmc.nt.Transform ):
    obj_list = [ pmc.PyNode( objects ) ]
    
  elif isinstance( object, [ tuple, list ] ):
    obj_list = objects
    
  else:
    pmc.error( 'Objects supplied for add_to_bake_layer command were invalid' )

  if len( obj_list ) < 1:
    pmc.error( 'No valid objects were supplied or selected for the bake_layer_command' )
  
  # Make connections
    
  for obj in obj_list:
    
    multi_connect(layer_node, 'lm', obj, 'bake')
Пример #30
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)
Пример #31
0
def make_shelf_icon(name,
                    icon_path,
                    command_str,
                    source_type="python",
                    annotation=None):
    """
    make an icon on the current shelf
    Args:
        name (str): the string name for this shelf item
        icon_path (str): the path to the image to use for the shelf item
        command_str (str): the command to run when pressing this shelf item
        source_type (str): the type of command, mel or python
        annotation (str): the tool-tip annotation to display on hovering over this shelf item

    Returns:
        returns the button just created
    """
    # type: (str, str, str, str, str) -> pm.uitypes.ShelfButton
    icon_path = os.path.normpath(icon_path)

    # Maya requires all paths to be forward slash for internal use
    if platform.system().startswith("Win"):
        icon_path = icon_path.replace("\\", "/")

    try:
        current_shelf = pm.uitypes.ShelfLayout(
            pm.mel.eval('tabLayout -q -st $gShelfTopLevel;'))

        for item in [
                x for x in current_shelf.getChildren()
                if isinstance(x, pm.uitypes.ShelfButton)
        ]:
            if name == item.getLabel():
                item.delete()

        # you must set the active parent before creating shelf buttons or they will be parented under maya's main window
        pm.setParent(current_shelf)

        shelf_button = pm.shelfButton(label=name)
        shelf_button.setSourceType(source_type)
        shelf_button.setCommand(command_str)
        shelf_button.setImage(icon_path)
        if annotation:
            shelf_button.setAnnotation(annotation)

        return shelf_button

    except Exception as e:
        pm.warning(
            "Something went wrong making the shelf item: {}\n Exception Msg: {}"
            .format(name, e.message))
Пример #32
0
def loop_to_joints(s=0.025):
    """Convert a mesh loop edge selection to a nurbs curve that has
    joints (w/ tweak controls) at each vertex. Opens dialog for naming."""
    edges = pmc.selected(flatten=True)
    cage = edges[0].node()

    try:
        n = make_dialog("Name of this curve/region?") + "{}"
    except TypeError:
        pmc.warning("Aborted.")
        return

    c = pmc.PyNode(pmc.polyToCurve(n=n.format("_rider"))[0])
    verts = set([v for e in edges for v in e.connectedVertices()])
    grp = pmc.group(em=True, n=n.format("_grp"))
    c.setParent(grp)
    jn = ""

    for i, v in enumerate(verts):
        pmc.select(c)
        pmc.selectMode(component=True)
        pmc.select(c.u[i])
        pmc.refresh()
        jn = make_dialog("Name of this joint?", jn)
        poci = pmc.nt.PointOnCurveInfo(n=n.format(jn + "_poci"))
        c.ws >> poci.inputCurve
        poci.parameter.set(i)
        ctrl_grp = pmc.group(em=True, n=n.format(jn + "_offset"))
        ctrl_grp.setParent(grp)
        ctrl = pmc.sphere(r=s, s=1, nsp=1, ch=0,
                          n=n.format(jn + "_tweakCtrl"))[0]
        ctrl.setParent(ctrl_grp)
        j = pmc.joint(n=n.format(jn + "_rig"))
        j.setParent(ctrl)
        j.hide()

        poci.position >> ctrl_grp.translate
        nCon = pmc.normalConstraint(cage, ctrl_grp)
        poci.nt >> nCon.worldUpVector

        # remove graph cluster
        nCon.crp.disconnect()
        nCon.crt.disconnect()
        nCon.cro.disconnect()
        nCon.cpim.disconnect()
        nCon.ct.disconnect()

        poci.position >> nCon.constraintTranslate
        grp.wim >> nCon.cpim

    pmc.selectMode(object=True)
Пример #33
0
 def colorCode(self):
     if self.override_color:
         try:
             top_obj = pm.PyNode(
                 self.target_objs[0])  # get the first of the target objects
         except:  # if target object does not exist display the warning
             pm.warning(
                 "Object {} not found. Make sure the correct scene is loaded."
                 .format(self.target_objs[0]))
             return
         color = utils.getOverrideColor(
             top_obj)  # set the override color (see utils.py)
         if color:
             self.color = color
Пример #34
0
def toMObject(*sNameList):

    mSelList = om.MSelectionList()
    mObjList = []

    for i, sName in enumerate(sNameList):

        try:
            mSelList.add(sName)
        except Exception, e:
            pm.warning('{0} : "{1}"'.format(e, sName))
        else:
            node = mSelList.getDependNode(i)
            mObjList.append(node)
Пример #35
0
def mergeBlendshapes():
    """For selected surfaces, merge their blendshape driver objects into one,
    preserving all connections. If two targets have the SAME NAME, they are
    MERGED!"""
    surfs = su.getSelectedSurfs(withAttr="layeredTexture")
    if len(surfs) < 2:
        pmc.warning("Select at least two surfaces.")
        return
    # ensure no duplicate drivers
    drivers = list(set([s.blendDriver.inputs(shapes=True)[0] for s in surfs]))
    #newName = rcu.avgMayaName([d.name() for d in drivers])
    top = drivers.pop()
    with bkTools.mayaSceneUtil.MayaUndoChunkManager():
        # top.getTransform().rename(newName+"_DAG")
        # top.rename(newName)
        for old in drivers:
            # output flag refers to numeric attributes
            for attr in old.listAttr(ud=True, output=True, k=True):
                outputs = attr.outputs(plugs=True)
                if not outputs:
                    # if it's not connected, ignore it...
                    continue

                n = attr.attrName()
                try:
                    topAttr = getattr(top, n)
                except AttributeError:
                    # if the user changed min/max before, they can do it again
                    top.addAttr(n, min=0, max=2, k=True)
                    topAttr = getattr(top, n)

                try:
                    i = attr.inputs(plugs=True)[0]
                except IndexError:
                    pass
                else:
                    if not topAttr.inputs():
                        i >> topAttr

                for o in outputs:
                    topAttr >> o

            # connect new driver shape to all surf message
            for oldSurf in old.message.outputs(type="transform"):
                top.message >> oldSurf.blendDriver

            for par in old.listRelatives(allParents=True):
                bkTools.mayaSceneUtil.addShapeToTrans(top, par)

            pmc.delete(old)
    def LoadNurb(self, nurbName):

        if len(nurbName) > 0:
            pm.select(nurbName)

            #check if added shape is a NURB
            shapes = cmds.listRelatives(str(nurbName))
            if pm.objectType(shapes, isType='nurbsCurve'):

                global NURB
                NURB = pm.ls(selection=True)[0]

            else:
                pm.warning('Please select a nurb curve instead')
Пример #37
0
def unload(plugin):
    """
    Unloads given plugin

    Args:
        plugin (string): plugin to unload
    """
    if pm.pluginInfo(plugin, q=True, loaded=True):
        pm.pluginInfo(plugin, e=True, autoload=False)

        try:
            pm.unloadPlugin(plugin)
        except RuntimeError:
            pm.warning(plugin + ' could not be unloaded!')
Пример #38
0
def transferPriCtlWeightsFromOri():
    '''
    '''
    import rigger.builds.ori.data as ori_data
    priCtlMappings = ori_data.priCtlMappings
    
    for pCtl, weightsTable in priCtlMappings.items():
        attrName = pCtl + '_weight_'
        for bndName, weight in weightsTable.items():
            try:
                bnd = pm.PyNode(bndName)
                bnd.attr(attrName).set(weight)
            except pm.MayaNodeError as e:
                pm.warning('Does not exist: ' + bndName)
Пример #39
0
    def get_asset_v(self, node):
        d_v = {'modv': '', 'rigv': ''}
        if isinstance(node, type('')):
            try:
                node = pm.PyNode(node)
            except:
                pm.warning('Can not figure out what ' + str(node) +
                           ' is, ignored!')
                return d_v

        if pm.referenceQuery(node, isNodeReferenced=True):
            #maya2scenegraphXML.setArbAttr([n_name], 'rigVersion', str(m.attr('rigVersion').get()) if m.hasAttr('rigVersion') else '', 'string')
            if node.hasAttr('modVersion'):
                d_v['modv'] = str(node.getAttr('modVersion'))
            if node.hasAttr('rigVersion'):
                d_v['rigv'] = str(node.getAttr('rigVersion'))
        elif node.nodeType() == 'assemblyReference':
            l_children = pm.listRelatives(node, c=True)
            if len(l_children) == 0:
                return d_v

            n = l_children[0]
            if n.type() == 'transform':
                if n.hasAttr('modv'):
                    d_v['modv'] = n.getAttr('modv')
                if n.hasAttr('rigv'):
                    d_v['rigv'] = n.getAttr('rigv')
            elif n.type() == 'gpuCache':
                gpu_file = n.getAttr('cacheFileName')
                tokens = gpu_file.split('/')
                if not 'publish' in tokens:
                    return d_v

                i = tokens.index('publish')
                if not len(tokens) > i + 1:
                    return d_v

                v_tokens = tokens[i + 1].split('.')
                if not (len(v_tokens) == 4 and v_tokens[1] in ['mod', 'rig']
                        and v_tokens[-1][1:].isdigit()):
                    return d_v
                d_v[v_tokens[1] + 'v'] = v_tokens[-1][1:]

                if v_tokens[1] == 'rig':
                    asset_xml = '/'.join(
                        tokens[:i +
                               2]) + '/scene_graph_xml/' + v_tokens[0] + '.xml'
                    d_v['modv'] = self.modv_from_xml(asset_xml)

        return d_v
Пример #40
0
    def NgSkin(self):
        if mc.objExists('*ngSkinToolsData_skinCluster1*'):

            pm.textScrollList(self.outputWin,
                              edit=True,
                              append=['    Warning: Contains NgSkin Nodes'])
            pm.warning("Warning: Contains NgSkin Nodes")

        else:
            pm.textScrollList(self.outputWin,
                              edit=True,
                              append=['Result: No NgSkin Nodes'])
            print("// Result: //")
            print("// Result: No NgSkin Nodes //")
Пример #41
0
def publish(event, *args):
    '''
    Publish an event, which runs any associated actions.
    '''
    global _registeredActions

    for action in _registeredActions[event].values():
        # Catch errors
        try:
            action(*args)
        except Exception:
            #print( traceback.format_exc() )
            warning('An error occurred in {0} when {1} was published'.format(
                action, event))
Пример #42
0
def load_guide_xforms(f=None):
    """Load guide xforms from the given file and attempt to
    match objects in the current scene to the saved values."""
    if not f:
        f = pmc.fileDialog2(ff="*.json", fileMode=1)[0]

    data = readJson(f)
    for obj, x in data.items():
        try:
            pmc.xform(obj, t=x["t"], ro=x["r"], s=x["s"])
        except:
            pmc.warning("Problem with {}. Skipped!".format(obj))
    else:
        print("Loaded guide xforms from {}".format(f))
Пример #43
0
 def createTextureNode(self, textureName, textureType):
     if os.path.exists(os.path.join(self.dirname, textureName)):
         colorTex = pm.shadingNode('file',
                                   asTexture=True,
                                   isColorManaged=True,
                                   name='%s_%s' %
                                   (self.baseFilename, textureType))
         colorTex.fileTextureName.set(
             os.path.join(self.envDirname, textureName))
         if len(self.fileTokens) > 2:
             colorTex.uvTilingMode.set('UDIM (Mari)')
         return colorTex
     else:
         pm.warning('%s Texture not found' % textureName)
Пример #44
0
 def _copy_vert_order(self):
     mapping_methods = self._get_inf_mapping_methods()
     target_meshes = self.target_meshes
     if self.use_selection:
         target_meshes = skinutils.get_skinned_meshes_from_selection()
     for target_mesh in target_meshes:
         if target_mesh == self.source_mesh:
             pm.warning(
                 'Skipping target mesh {}. Target mesh must be a different mesh than the source mesh.'
                 .format(target_mesh.shortName()))
             continue
         skinutils.copy_weights_vert_order(self.source_mesh,
                                           target_mesh,
                                           mapping_methods=mapping_methods)
    def LoadMesh(self, meshName):

        if len(meshName) > 0:
            pm.select(meshName)

            #check if added shape is a mesh
            shapes = cmds.listRelatives(str(meshName))
            if pm.objectType(shapes, isType='mesh'):

                global collision_mesh
                collision_mesh = pm.ls(selection=True)[0]

            else:
                pm.warning('Please select a mesh instead')
Пример #46
0
def makeSimpleSurf(name="UNTITLED_SURF_RIG"):
    """Create a 2x3 span nurbs plane at the average position of selection
    with the average normal."""
    sel = getSymSelection()
    if sel:
        vts = getConnectedCmpnts(sel, "Vertices")
        normal = getPolyAvgNormal(vts)
        pos = sum(v.getPosition("world") for v in vts) / len(vts)
    else:
        pmc.warning("No guide edges selected, surface created at origin.")
        normal = (1, 0, 0)
        pos = (0, 0, 0)

    return pmc.nurbsPlane(u=3, v=2, ch=0, axis=normal, p=pos, n=name)[0]
Пример #47
0
def remove_namespace_from_reference():
    """Converted a referenced file with name space to one without namespace"""
    # Check if there are namespaces
    if pm.listReferences():
        # Get the First reference file
        ref = pm.listReferences()[0]
        # Get the path
        path = ref.path
        # Remove the path name
        ref.remove()
        # Reload the reference
        pm.createReference(path, namespace=":", mergeNamespacesOnClash=False)
    else:
        pm.warning("No namespaces found")
Пример #48
0
    def set_bnd(self, bnd):
        temp = []
        for jnt in bnd:
            if self.side != '':
                find = pm.ls(jnt.replace('_SIDE_', self.side))
            else:
                find = pm.ls(jnt)
            if find:
                temp.append(find[0])
            else:
                pm.warning('Bind joint {} not found'.format(jnt))
                return None

        return temp[:]
Пример #49
0
 def _source_load_button_clicked(self):
     try:
         sel = pm.selected()[0]
         self.source_mesh = sel
         if not skinutils.get_skincluster(sel):
             pm.warning(
                 'Selected node is not a skinned mesh. Please select a skinned mesh.'
             )
             self.source_mesh = None
     except IndexError:
         pm.warning('Please select a skinned mesh in the scene.')
         self.source_mesh = None
     self._do_source_line_edit_background_color()
     self._refresh_arrow_color()
    def button_command(self):
        """
        Gets all selected items and applies it to the lineEdit
        """
        import pymel.core as pm

        if not pm.selected():
            pm.warning('Nothing Selected')
            return

        txt = ''
        for sel in pm.selected():
            txt += '{}, '.format(sel.name())
        return txt.rstrip(', ')
Пример #51
0
def lcBake_open_lightmap_folder(*args, **kwargs):
    ''' '''
    global lct_cfg

    dir = pm.textField(prefix + '_textField_texture_path',
                       query=True,
                       text=True)
    lightmapDir = os.path.normpath(os.path.join(dir, 'lightMap'))
    if os.path.exists(lightmapDir):
        lcPath.Path.openFilePath(lightmapDir)
    elif os.path.exists(dir):
        lcPath.Path.openFilePath(dir)
    else:
        pm.warning('Path not found: {0}'.format(dir))
Пример #52
0
def createTrailMesh(*args):
    startVertices = pm.ls(sl=1, fl=1)
    if len(startVertices) != 2:
        pm.warning('Select 2 vertices to have the width of the trail')
        return

    vert1 = startVertices[0]
    vert2 = startVertices[1]

    pathCrv = createCurveFromPoints(vert1, vert2)
    dirVec = getPlaneDirection(pathCrv)
    tempPoly = createStartPoly(vert1, vert2, dirVec)
    extrudeTrail(tempPoly, pathCrv)
    createTrailUv(tempPoly)
Пример #53
0
    def openScriptFileInEditor(self):
        if not 'VSCODE_PATH' in os.environ:
            pm.warning(
                'Add VSCODE_PATH to environment to enable script editing')
            return

        vscode = os.environ['VSCODE_PATH']
        sceneName = pm.sceneName()
        if not sceneName:
            pm.warning('Save the scene to enable script editing')
            return

        scriptsFilename = os.path.splitext(sceneName)[0] + '_scripts.py'
        subprocess.Popen([vscode, scriptsFilename])
Пример #54
0
 def mirrorChoice(axis):
     if axis == "                       - X AXIS -":
         adbTransform.Transform(
             pm.selected()).mirror(axis='x')
     elif axis == "                       - Y AXIS -":
         adbTransform.Transform(
             pm.selected()).mirror(axis='y')
     elif axis == "                       - Z AXIS -":
         adbTransform.Transform(
             pm.selected()).mirror(axis='z')
     elif axis == "               - Choose Axis Mirror -":
         pass
     else:
         pm.warning('Choice None Existant')
Пример #55
0
def setLockOnMeshes(lock):
    """
    Locks or unlocks all the transforms under piper skinned nodes that have mesh shapes.

    Args:
        lock (int): Mode to set on meshes. 0 is unlocked, 1 is locked.
    """
    meshes = getMeshes()
    for mesh in meshes:
        try:
            mesh.overrideEnabled.set(1)
            mesh.overrideDisplayType.set(lock)
        except RuntimeError as error:
            pm.warning('Can\'t set lock on mesh! ' + str(error))
Пример #56
0
 def createModule(self):
     moduleNameEdit = self.attrGroup.findChild(QtGui.QLineEdit,'moduleNameEdit')
     moduleName = moduleNameEdit.text()
     moduleNumJntSpin = self.attrGroup.findChild(QtGui.QSpinBox,'numJntSpin')
     moduleNumJnt = moduleNumJntSpin.value()
     
     if moduleName:
         moduleExists = pm.ls(moduleName)
         if not moduleExists:
             newModule = module.Module(name=moduleName,nJnt = moduleNumJnt)
             newModule.createModule()
             self.modulesList[newModule.name] = {'Joint Number':moduleNumJnt,'Module Controller':newModule.moduleCtrl}
         else:
             pm.warning('Module "%s" exists already'%moduleName)
Пример #57
0
 def proxyPlane(axis):
     if axis == "                       - X AXIS -":
         adbProxy.plane_proxy(
             pm.selected(), 'proxy_plane', 'x')
     elif axis == "                       - Y AXIS -":
         adbProxy.plane_proxy(
             pm.selected(), 'proxy_plane', 'y')
     elif axis == "                       - Z AXIS -":
         adbProxy.plane_proxy(
             pm.selected(), 'proxy_plane', 'z')
     elif axis == "               - Create Proxy Plane -":
         pass
     else:
         pm.warning('Choice None Existant')
Пример #58
0
 def __changeRy(self):
     self.ry = pm.windows.textField(self.tRy, q=True, text=True)
     try:
         if self.ry is None or len(self.ry) < 1:
             self.ry = self.defaultnum
         elif int(self.ry) == 0:
             raise ValueError
         else:
             self.ry = int(self.ry)
         d = u'当前输出的贴图宽度为:%s' % (str(self.ry))
     except ValueError:
         self.ry = self.defaultnum
         d = u'数值错误,设置缺省贴图宽度为:%s' % (str(self.ry))
     pm.warning(d)
Пример #59
0
    def LightsLocator(self):
        if mc.objExists('*x__light_constraint__grp__*'):

            pm.textScrollList(self.outputWin,
                              edit=True,
                              append=['Result: Contains a light grp '])
            print("// Result:  //")
            print("// Result: Contains a light grp //")

        else:
            pm.textScrollList(self.outputWin,
                              edit=True,
                              append=['Warning: NO LIGHT CONSTRAINT GROUP'])
            pm.warning('Warning: NO LIGHT CONSTRAINT GROUP')
Пример #60
0
def build():
    '''
    '''
    mesh = nt.Mesh(u'CT_hat_simplegeoShape')
    placementGrp = nt.Transform(u'CT_placement_grp')

    #---------------------------------------------------------------------- bind
    if 'bind' in data.build_actions:
        bindGrp = face.createBndsFromPlacement(placementGrp)
        pm.refresh()
    else:
        bindGrp = nt.Transform(u'CT_bnd_grp')

    #--------------------------------------------------------- sec motion system
    if 'sec_motion_system' in data.build_actions:
        face.buildSecondaryControlSystem(placementGrp, bindGrp, mesh)
        pm.refresh()

    #------------------------------------------------------------ pri ctl system first
    if 'primary_ctl_system_first' in data.build_actions:
        # run a simple first pass
        # which can be used to block out mappings
        bndsForPriCtls = data.all_bnds_for_priCtls
        priCtl.setupPriCtlFirstPass(bindGrp, bndsForPriCtls)
        priCtl.driveAttachedPriCtlsRun(bindGrp)

    #------------------------------------------------------------ pri ctl system second
    if 'primary_ctl_system_second' in data.build_actions:
        if data.priCtlMappings:
            # if priCtlMappings is set up, use the data
            priCtlMappings = data.priCtlMappings
            priCtl.setupPriCtlSecondPass(priCtlMappings)
            priCtl.driveAttachedPriCtlsRun(bindGrp)
            pm.refresh()
        else:
            pm.warning('no data for pri ctl system')

    #-------------------------------------------------------------- load weights
    if 'load_weights' in data.build_actions:
        priCtlWeights = data.priCtlWeights
        priCtl.setPriCtlSecondPassWeights(priCtlWeights)
        pm.refresh()

    #--------------------------------------------------------------------- clean
    if 'clean' in data.build_actions:
        print 'clean'
        face.cleanFaceRig()
        pm.select(cl=True)
        pm.refresh()