コード例 #1
0
    def custom_sets(self, *args):
        self.log.clear()
        self.log.insertText('Create Custom Sets...\n')
        self.log.insertText('\nFind all controls under the groups: \n  "Placer", "rig_arc", and "Face_UI|Panels"\n\nGenerate two sets as result : \n  "ctrlSet" contains all tagged controls\n  "_NON_TAGGED_CURVES" contains all non-tagged controls\n')
                
        ctrlSets = pm.ls("*ctrlSet")
        if not ctrlSets:
            self.controlSet = pm.sets(empty=True, name = "ctrlSet")
        
        grps = [grp for grp in ['Placer', 'rig_arc'] if pm.objExists(grp)]
        pm.select(grps, hi=True)
        all_curve = pm.ls(sl=True, type="nurbsCurve")
        pm.select(clear=True)

        all_ctrl = [ctrl.getParent() for ctrl in all_curve]
        
        if pm.objExists('Panels'):
            pm.select('Panels', hi=True)
            all_facial_curve = pm.ls(sl=True, type="nurbsCurve")
            pm.select(clear=True)
            all_ctrl.extend([curve.getParent() for curve in all_facial_curve if curve.getParent().tz.isLocked()]) 
            #pm.sets(all_ctrl, name="_ALL_CURVES")
        
        no_tags = [ctrl for ctrl in all_ctrl if not pm.attributeQuery ('ClientAnimCtrl', node= ctrl, ex=True)]
        pm.sets(no_tags, name="_NON_TAGGED_CURVES")
        
        tags = [ctrl for ctrl in all_ctrl if pm.attributeQuery ('ClientAnimCtrl', node= ctrl, ex=True)]
        self.controlSet.addMembers(tags)
コード例 #2
0
    def test_clusterPlane(self):
        fr = FollowRibbon.FollowRibbon(name="blah")
        plane = pm.nurbsPlane(axis=[0, 1, 0], patchesU=8, patchesV=1, lengthRatio=0.1, ch=0)[0]
        ctrls = []
        ctrls.append(pm.circle(n="blah_ctrl_01")[0].name())
        ctrls.append(pm.circle(n="blah_ctrl_02")[0].name())
        mainGrp = pm.group(em=1, name="main")

        result = fr._clusterPlane(plane=plane, controls=ctrls, mainGrp="main")

        self.testLib.assertListEqual(result, ["blah_cluster_01Handle", "blah_cluster_02Handle"])
        self.assertTrue(pm.objExists("blah_cluster_01"))
        self.assertTrue(pm.objExists("blah_cluster_02"))

        self.assertTrue(pm.listRelatives(result[0], parent=True), "main")
        self.assertTrue(pm.listRelatives(result[1], parent=True), "main")

        self.assertTrue(pm.listRelatives(result[0], parent=1)[0], "blah_ctrlsGrp")
        self.assertTrue(pm.listRelatives(result[1], parent=1)[0], "blah_ctrlsGrp")

        hist = pm.listHistory(plane)
        hitA = 0
        hitB = 0
        for each in hist:
            if each.name() == "blah_cluster_01":
                hitA = 1
            if each.name() == "blah_cluster_02":
                hitB = 1
        self.assertTrue(hitA)
        self.assertTrue(hitB)

        self.assertTrue(pm.isConnected("blah_ctrl_01.translate", "blah_cluster_01Handle.translate"))
        self.assertTrue(pm.isConnected("blah_ctrl_02.translate", "blah_cluster_02Handle.translate"))
コード例 #3
0
ファイル: objSet.py プロジェクト: TianD/TianD_KX_TOOL
def createObjectSet(setName, objLst = [], exclusiveness = False, partition = None, increment = False):
    '''
    create an objectSet.
    @param    setName           string         :    This objectSet's name.
    @param    objLst            list           :    Objects which belongs this objectSet.
    @param    exclusiveness     bool           :    Whether is this objectSet mutually exclusive with another objectSet in one partition.
    @param    partition         node or string :    When exclusiveness flag is True, partitin should be assigned a partition node. Ignore when exclusiveness flag is False.
    @param    increment         bool           :    Whether to use the existed one or create an increment one When the named objectSet has been existed.
                                                    If the existed objectSet will be used, ignore exclusiveness flag and partition flag.
    @result                     node 
    '''
    useExisted = False
    if not pm.objExists(setName):
        objSet = pm.sets(em=1, name = setName)
    elif pm.objExists(setName) and increment :
        setName = name.compileNodeName(setName)
        objSet = pm.sets(em=1, name = setName)
    else:
        objSet = pm.PyNode(setName)
        useExisted = True
        
    if not useExisted and exclusiveness :
        partition.addMember(objSet)
    
    if objLst:
        #objSet.addMembers(objLst)
        pm.sets(objSet, e=1, forceElement = objLst)
    
    return objSet
コード例 #4
0
ファイル: skinTools.py プロジェクト: AtonLerin/Maya_Tools
    def dictToDatas(self, dict_datas):

        """
        !@Brief Get dict datas of skinCluster and push datas to class variables.
        This function is for import.
        """

        if not dict_datas:
            raise RuntimeError("\n\tDict datas is empty or invalid !!!\n")

        #   Check if skin node exists
        #   If skin node doesn't exist set variable with string name
        if pmc.objExists(dict_datas["SKIN_NODE"]):
            self.SKIN_NODE = pmc.PyNode(dict_datas["SKIN_NODE"])
        else:
            self.SKIN_NODE = dict_datas["SKIN_NODE"]

        #   Check if shape node exists
        #   If shape node doesn't exist set variable with string name
        if pmc.objExists(dict_datas["SHAPE"]):
            self.SHAPE = pmc.PyNode(dict_datas["SHAPE"])
        else:
            self.SHAPE = dict_datas["SHAPE"]

        #   Set skin datas
        self.INFLUENCES = dict_datas["INFLUENCES"]
        self.WEIGHTS = dict_datas["WEIGHTS"]
        self.MAX_INFLUENCES = dict_datas["MAX_INFLUENCES"]
        self.MAINTAIN_MAX_INFLUENCES = dict_datas["MAINTAIN_MAX_INFLUENCES"]
        self.SKINNING_METHOD = dict_datas["SKINNING_METHOD"]
        self.USE_COMPONENTS = dict_datas["USE_COMPONENTS"]
        self.BIND_PRE_MATRIX = dict_datas["BIND_PRE_MATRIX"]
        self.BASE_POINT = dict_datas["BASE_POINT"]
コード例 #5
0
def create_control(control, module):
    """ Creates a control for the rig, checking for existing controls or creating
    Args:
        control (str, pm.nt.Transform): can be anything really, just as long as it exists
    Returns:
        (pm.nt.Transform): the resulting transform of the control
    """
    is_new = False
    # Check if default control was created
    if pm.objExists('grow_CTRL') and not pm.objExists(control):
        control = pm.PyNode('grow_CTRL')
    
    # Create the control if control doesn't exist
    elif not pm.objExists(control):
        control = pm.circle(n='grow_CTRL')
        # Flat control in Y...
        control[1].normalY.set(1)
        control[1].normalZ.set(0)
        control = control[0]
        is_new = True
        
    # If it's a string and we weren't passed a PyNode we need to check existing nodes
    elif isinstance(control, basestring):
        control = pm.PyNode(control)
        
    setup_control_global_attrs(control, module)
    
    return control, is_new
コード例 #6
0
ファイル: mr_wireframe.py プロジェクト: borgfriend/MayaTools
def create_wireframe_rl(name="wireframe"):
    """
    Creates wireframe material
    Creates wireframe layer
    Adds all geometry and rendercam to the renderlayer
    
    @param name: str layername
    """
    mat_name = "%s_mat" % name

    if not pm.objExists(mat_name):        
        material_node = pm.shadingNode("lambert", n=mat_name, asShader=True)
        material_node.setColor([1, 1, 1])
        
        material_sg_node = pm.sets(renderable=True, noSurfaceShader=True, empty=True, name="%sSG" % mat_name)
        material_sg_node.miContourEnable.set(1)
        material_sg_node.miContourColor.set([0,0,0])
        material_sg_node.miContourWidth.set(1.5)
        material_node.outColor >> material_sg_node.surfaceShader
        
        if not pm.objExists(name):
            render_layer = pm.createRenderLayer(n=name)
            render_layer.setCurrent()
            render_layer.addMembers(pm.ls(geometry=True, cameras=True))
            material_sg_node.message >> render_layer.shadingGroupOverride
コード例 #7
0
    def check(self, *args):
        self.log.insertText("Checking Master Node... \n")
        
        if pm.objExists('master'):
            master_node = pm.PyNode("master")
        else :
            self.log.insertText("  Master Node does not exists \n")
            return False
        
        attrs = ['objectName',
                 'arc_file_path',
                 'arc_file_name',
                 'arc_asset_name',
                 'arc_asset_dept',
                 'arc_asset_version',
                 'ClientAsset']
        
        status = True
        for attr in attrs:
            msg = "%s.%s"%(master_node, attr)
            self.log.insertText("  %s" %(msg.ljust(40, '.')))
            if not pm.objExists('%s.%s'%(master_node, attr)):
                self.log.insertText("FAIL \n")
                status = False
                if master_node not in self.result.getAllItems():
                    self.result.append(master_node)
            else:
                self.log.insertText("OK \n")

        return status
コード例 #8
0
ファイル: aw_scatterParticle.py プロジェクト: AndresMWeber/aw
	def _prep(self,args):
		basename=self.inputName.getText()
		nparticle=pm.ls(sl=True)[0]
		if not pm.objExists(self.inputBar.getText()):
			pm.error ('GEO plane doesn\'t exist')
		geo = pm.PyNode(self.inputBar.getText())
		if not isinstance(nparticle.getShape(), pm.nt.NParticle):
			pm.error('Your selection is not an nParticle object')
        #create an instancer
		tempCube=pm.polyCube(n='temp_iinst_GEO',w=.01,h=.01,d=.01,ch=0)
		

		self.instancer=pm.PyNode(pm.particleInstancer(nparticle,name=(nparticle.name().replace('_NPARTICLE','_INSTANCER')),addObject=True,object=tempCube[0],cycleStep=1,cycleStepUnits='Frames',levelOfDetail='Geometry',rotationUnits='Degrees',rotationOrder='XYZ',position='worldPosition',rotation='rotPP',scale='scalePP',objectIndex='indexPP'))

		pm.delete(tempCube)
		#group the nparticle + instancer
		group=pm.group(n=(nparticle.name().replace('_NPATICLE','_lodA_GRP')))
		nparticle.setParent(group)
		self.instancer.setParent(group)
        #nCache itR
		
		if not pm.objExists( nparticle.name().replace('_NPARTICLE','_NUCLEUS') ):
			pm.error('Nucleus doesn\'t exist!')
		nucleus = nparticle.name().replace('_NPARTICLE','_NUCLEUS')
        #delete everything unnecessary that might cause issues
		print geo, nucleus
		print 'issue?'
		pm.delete(geo, nucleus)
		print 'issue?'
		pm.select(nparticle)
		mm.eval('performCreateNclothCache 1 \"add\";')
		pm.confirmDialog(m='WARNING, DO NOT SAVE AFTER THIS STEP',t='DONT SAVE!')
コード例 #9
0
ファイル: __init__.py プロジェクト: loichuss/maya
def __restorePosingRIG__(elts):

    if elts==None:
        # get each objects from rigShapesSet
        if pmc.objExists('RIG_bindPose'):
            elts = pmc.sets('RIG_bindPose', query=True)
        fromSelection=False
    else:
        fromSelection=True
    
    if elts:
        for elt in elts:
            if fromSelection:
                if pmc.objExists(elt.name()+'_storedPos'):
                    obj = elt.name()+'_storedPos'
                    attrs = pmc.listAttr(elt, keyable=True)
                    for i in range(len(attrs)):
                        try:
                            pmc.PyNode(elt+'.'+attrs[i]).set(pmc.PyNode(obj+'.'+attrs[i]+'_stored').get())
                        except:
                            vp.vPrint('No data founded from %s in rigPosingSet set' % elt.name(), 1)
                else:
                    vp.vPrint('Object %s doesn\'t exist' % (elt.name()+'_storedPos'), 1)
            else:
                if pmc.objExists(elt.name().replace('_storedPos', '')):
                    obj = pmc.PyNode(elt.name().replace('_storedPos', ''))
                    attrs = pmc.listAttr(obj, keyable=True)
                    for i in range(len(attrs)):
                        try:
                            pmc.PyNode(obj+'.'+attrs[i]).set(pmc.PyNode(elt+'.'+attrs[i]+'_stored').get())
                             
                        except:
                            vp.vPrint('No data founded from %s in rigPosingSet set' % elt.name(), 1)
                else:
                    vp.vPrint('Object %s doesn\'t exist' % elt.name().replace('_storedPos', ''), 1)
コード例 #10
0
ファイル: lib_deformer.py プロジェクト: creuter23/tools
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)
コード例 #11
0
def create_module(name):
    """ Creates a top group from an object name
        For now, just dummy checking if the suffix is all caps
    Args:
        name (str): name to parse or use
    Returns (pm.nt.Transform): resulting group node
    """
    module = {}
    if name.split('_')[-1].isupper():
        name = '_'.join( name.split('_')[:-1] )
    
    grp_name = '%s_GRP'%name
    if pm.objExists(name):
        top_group = pm.PyNode(name)
    elif pm.objExists(grp_name):
        top_group = pm.PyNode(grp_name)
    else:
        top_group = pm.group(em=True, n='%s_GRP'%name)
    
    module['top_group'] = top_group
    
    for subgroup in ['skeleton','model','parts','controls']:
        subgroup_name = '%s_%s_GRP'%(name, subgroup)
        if not pm.objExists(subgroup_name):
            module[subgroup] = pm.group(em=True, n=subgroup_name)
            module[subgroup].setParent(top_group)
            top_group.addAttr('%s_vis'%subgroup,
                              at='long',
                              k=True,
                              dv=1, min=0, max=1)
            top_group.attr('%s_vis'%subgroup).connect(module[subgroup].visibility)
        else:
            module[subgroup] = pm.PyNode(subgroup_name)
    
    return module
コード例 #12
0
ファイル: __init__.py プロジェクト: loichuss/maya
def __restoreShapes__(elts):

    if elts==None:
        # get each objects from rigShapesSet
        if pmc.objExists('rigShapesSet'):
            elts = pmc.sets('rigShapesSet', query=True)
        fromSelection=False
    else:
        fromSelection=True
    
    if elts:
        for elt in elts:
            if fromSelection:
                atoms = various.getAtoms(elt.getShape(), flat=False)
                for i in range(len(atoms)):
                    try:
                        pmc.move(atoms[i], pmc.PyNode(elt.name()+'_storedShp.cv'+str(i)).get(), absolute=True)
                    except:
                        vp.vPrint('No %s in rigShapesSet set' % (elt.name()+'_storedShp'), 1)
            else:
                if pmc.objExists(elt.name().replace('_storedShp', '')):
                    obj = pmc.PyNode(elt.name().replace('_storedShp', '')).getShape()
                    atoms = various.getAtoms(obj, flat=False)
                    for i in range(len(atoms)):
                        try:
                            pmc.move(atoms[i], pmc.PyNode(elt+'.cv'+str(i)).get(), absolute=True)
                        except:
                            vp.vPrint('No data founded from %s in rigShapesSet set' % elt.name(), 1)
                else:
                    vp.vPrint('Shape %s doesn\'t exist' % elt.name().replace('_storedShp', ''), 1)
コード例 #13
0
ファイル: aw_locators.py プロジェクト: AndresMWeber/aw
 def locInst_locSel(self):
     '''
     Function: Takes a locator and instances it's target (set as an extra attr)
     Then sets the location of the instance.
     If the instance already exists it uses that
     Returns: None
     '''
     locs = pm.ls(sl=True)
     grp_name = "_".join(locs[0].getParent().split('_')[:-2])+"_INST_GRP"
     print grp_name
     print pm.objExists(grp_name)
     if pm.objExists(grp_name): pm.PyNode(grp_name)
     else: grp=pm.group(em=True, n=grp_name)
     
     for loc in locs:
         #if the target isn't an instance create it
         targetExists = pm.ls(loc.target.get().split('_')[:-1][0]!='GEO', r=True, type='transform')[0]
         instanceExists = pm.ls(loc.target.get().split('_')[:-1][0]!='INST', r=True, type='transform')[0]
         if not instanceExists and targetExists:
             matchObj = pm.ls(loc.target.get(), r=True, type='transform')[0]
             instance = pm.instance(matchObj, n=('_'.join(matchObj.split('_')[:-1])+'_INST'))[0]
             #set the target to the new instance since it was created
             loc.target.set(instance)
         
         elif pm.objExists(loc.target.get()) and pm.objExists('_'.join(target.split('_')[:-1])+'_INST'):
             pm.error('Neither a GEO nor an INST object exists with this name')
         #otherwise initialize the instance variable    
         else: instance = pm.PyNode('_'.join(arg.split('_')[:-1])+'_INST')
         loc.t.connect( instance.t )
         loc.r.connect( instance.r )
         loc.s.connect( instance.s )
         instance.setParent(grp)
コード例 #14
0
ファイル: libWeights.py プロジェクト: mds-dev/mds_repository
    def _create_deformers_(self):
        # Setup missing geo shapes dictionary
        missing_shapes = {}
        # Build in the order of blendshapes
        for blendshape in libXml.list_persist(self.import_data["Order"]):
            # Check if the blendshapes exists. If so create one.
            shapes = libXml.list_persist(self.import_data["Data"][blendshape])
            if not pm.objExists(blendshape):
                # Read info for each blendshape
                # select select the shapes.
                pm.select(cl=1)
                for shape in shapes:
                    # Check the shape exists
                    if pm.objExists(shape):
                        # Add to the selection
                        pm.select(shape, add=1)
                    else:
                        # If not then then add to error list dictionary
                        if missing_shapes.has_key(blendshape):
                            missing_shapes[blendshape].append(shape)
                        else:
                            missing_shapes[blendshape] = [shape]
                # Select the target geo and create blendshape
                pm.select(self.target, add=1)
                pm.blendShape(name=blendshape)

        if len(missing_shapes):
            print "#######The following blends had missing shapes#######"
            for key in missing_shapes.keys():
                print key.upper()
                libUtilities.print_list(missing_shapes[key])
コード例 #15
0
ファイル: hierarchy.py プロジェクト: loichuss/maya
def createHierarchy():
    """hierarchy construction"""
    
    gp = {}
    
    # create groups
    grps = [['TEMPLATES'], ['BDD'], ['PERSO'], ['SKINSKEL'], ['ADDITIVERIG'], ['ANIMATION'], ['TODELETE'], ['SETUP','PERSO|'], ['SCALEOFFSET','PERSO|SETUP|'], ['NOXFORM','PERSO|SETUP|']]
    for grp in grps:
        
        # create the absolute path
        tmpName = '|'
        for i in reversed(range(len(grp))):
            tmpName += grp[i]
        
        # check if the object exist
        if pmc.objExists(tmpName):
            gp[grp[0]] = pmc.PyNode(tmpName)
        else:
            gp[grp[0]] = pmc.createNode('transform', name=grp[0], skipSelect=True)
            if len(grp)==2:
                gp[grp[0]].setParent(grp[1])
                clean.__lockHideTransform__(gp[grp[0]], channel=['v'])
    
    
    # uncheck inherits transform
    gp['BDD'].inheritsTransform.set(False)
    gp['NOXFORM'].inheritsTransform.set(False)
    
    
    # create scale offset attribut
    if gp['SCALEOFFSET'].hasAttr('scaleOffset')==False:
        pmc.addAttr(gp['SCALEOFFSET'], longName='scaleOffset', attributeType='float', defaultValue=1.0, keyable=True )
    
    # connect the scale offset attribut into the scale
    clean.__lockHideTransform__(gp['SCALEOFFSET'], channel=['s'], lock=False)
    if len(gp['SCALEOFFSET'].sx.inputs(plugs=True))==0:
        gp['SCALEOFFSET'].scaleOffset >> gp['SCALEOFFSET'].sx
    if len(gp['SCALEOFFSET'].sy.inputs(plugs=True))==0:
        gp['SCALEOFFSET'].scaleOffset >> gp['SCALEOFFSET'].sy
    if len(gp['SCALEOFFSET'].sz.inputs(plugs=True))==0:
        gp['SCALEOFFSET'].scaleOffset >> gp['SCALEOFFSET'].sz
    
    
    # hide and lock attribut
    for key in gp.keys():
        clean.__lockHideTransform__(gp[key], channel=['t', 'r', 's'])
    
    
    # create set
    pmc.select(clear=True)
    sets = ['CONTROLS']
    for set in sets:
        if pmc.objExists(set)==False:
            gp[set] = pmc.sets(name=set)
        else:
            gp[set] = pmc.nodetypes.ObjectSet('CONTROLS')
    
    return gp
コード例 #16
0
ファイル: JR_camera_shake.py プロジェクト: jricker/JR_Maya
 def cameraHasNoiseApplied(self):
     if self.control:
         if pc.objExists('%s.Seed_T'%self.control) and pc.objExists('%s.Seed_R'%self.control): #check any 2 noise attributes
             noise_status = True
         else:
             noise_status = False
     else:
         noise_status = False
     return noise_status
コード例 #17
0
 def test_import_remove_namespace(self):
     ref = self.sphereRef1
     nsSphere = 'sphere1:pSphere1'
     noNsSphere = 'pSphere1'
     self.assertTrue(pm.PyNode(nsSphere).isReferenced())
     self.assertFalse(pm.objExists(noNsSphere))
     ref.importContents(removeNamespace=True)
     self.assertFalse(pm.objExists(nsSphere))
     self.assertFalse(pm.PyNode(noNsSphere).isReferenced())
コード例 #18
0
def assign_killz():
	sel=pm.ls(sl=True)
	#load shaders 
	if not pm.objExists("HELMET"):
		cmds.file("/mpc/mayors1/playstationKillzone4_5402105/pantry/bodies/vsa_infantry_shaders.ma",i=True,type='mayaAscii', ignoreVersion=True, rpr="vsa_infantry_shaders", options='v=0',loadReferenceDepth='all')
	if not pm.objExists("PLASTIC_LIGHT"):
		cmds.file("/mpc/mayors1/playstationKillzone4_5402105/pantry/bodies/hgh_infantry_shaders.ma",i=True,type='mayaAscii', ignoreVersion=True, rpr="hgh_infantry_shaders", options='v=0',loadReferenceDepth='all')
	assignments_keys=[chkObjNs('*vsa_security_trooper_helmet*'),
	                  chkObjNs('*vsa_security_trooper_glasses'),
	                  chkObjNs('*vsa_security_trooper_visor'),
	                  chkObjNs('*VSA_Infantry_Body_L*'),
	                  chkObjNs('*VSA_Infantry_Markers_L*'),
	                  chkObjNs('*VSA_Infantry_Marker_Lights_L*'),
	                  chkObjNs('*head*l*'),
	                  chkObjNs('*head_anthony_trooper_l*'),
	                  chkObjNs('*heads_GEO*'),
	                  chkObjNs('HGH_specOps_class_bodies_GRP'),
	                  chkObjNs('HGH_support_class_bodies_GRP'),
	                  chkObjNs('HGH_specOps_*_GRP'),
	                  chkObjNs('HGH_support_*_GRP'),
	                  chkObjNs('first_layer'),
	                  chkObjNs('second_layer'),
	                  chkObjNs('edges'),
	                  chkObjNs('*eyes_glowing*'),
	                  chkObjNs('*screen_back_L*'),
	                  chkObjNs('*single_led_back*'),
	                  chkObjNs('*Light_L*'),
	                  chkObjNs('*round_gridlights*')]
	assignments={chkObjNs('*vsa_security_trooper_helmet*'):'HELMET',
		 chkObjNs('*vsa_security_trooper_glasses'):'VISOR',
		 chkObjNs('*vsa_security_trooper_visor'):'VISOR',
		 chkObjNs('*VSA_Infantry_Body_L*'):'BODY',
		 chkObjNs('*VSA_Infantry_Markers_L*'):'lambert1',
		 chkObjNs('*VSA_Infantry_Marker_Lights_L*'):'lambert1',
		 chkObjNs('*head*l*'):'FACE',
		 chkObjNs('*head_anthony_trooper_l*'):'FACE',
		 chkObjNs('*heads_GEO*'):'FACE',
		 chkObjNs('HGH_specOps_class_bodies_GRP'):'HGH_SpecOp_BODY',
		 chkObjNs('HGH_support_class_bodies_GRP'):'HGH_Engineer_BODY',
		 chkObjNs('HGH_specOps_*_GRP'):'HGH_SpecOp_BODY',
		 chkObjNs('HGH_support_*_GRP'):'HGH_Engineer_BODY',
		 chkObjNs('first_layer'):'HGH_Engineer_BODY',
		 chkObjNs('second_layer'):'HGH_Engineer_BODY',
		 chkObjNs('edges'):'HGH_Engineer_BODY',
		 chkObjNs('*eyes_glowing*'):'PLASTIC_LIGHT',
		 chkObjNs('*screen_back_L*'):'PLASTIC_LIGHT',
		 chkObjNs('*single_led_back*'):'PLASTIC_LIGHT',
		 chkObjNs('*Light_L*'):'PLASTIC_LIGHT',
		 chkObjNs('*round_gridlights*'):'PLASTIC_LIGHT'}
	print assignments
	for obj in assignments_keys:
		if not obj == "":
			print 'Assigning shader %s to object %s' % ( assignments[obj], obj)
			objs = pm.ls(obj)
			print objs
			pm.select(objs,r=True)
			pm.hyperShade(obj, a=assignments[obj])
コード例 #19
0
ファイル: aw_transform.py プロジェクト: creuter23/tools
 def _targetMatch(self, *args):
     args=pm.ls(sl=True)
     for arg in args:
         if pm.objExists(arg+'.target'):
             tgt= pm.PyNode(arg.target.get())
         elif pm.objExists(nami.replaceSuffix(arg+'GEO')): tgt = pm.PyNode(arg.target.get())
         else:
             print 'Couldn\'t find target for object: %s ...skipping' % arg
             break
         posi.matchPos(arg, [tgt], 1)
コード例 #20
0
ファイル: lib_mpc.py プロジェクト: AndresMWeber/aw
def rig_makeBlockGeo(geometry, mpcStyle=False):
	'''Uses the MPC block geo script to create automaded block geo out of one selected object which is properly constrained.
	Args:
		geometry (pm.PyNode): poly mesh to be broken apart
		mpcStyle (boolean): replaces the suffix based on JNT and GEO
	Returns (list[pm.PyNode]): List of proxies that were generated
	Example Usage:
		rig_makeBlockGeo()
	'''
	#convert the list to a mel list as a string to pass
	command = 'rig_makeBlockGeo ({{"{MESHES}"}},"");'.format(MESHES=geometry)
	print command
	proxies = mel.eval(command)
	
	if len(proxies):
		#Time to sort them and order them + constrain them
		if not pm.objExists('proxy_GRP'):
			prx_grp = pm.group(em=True, n='proxy_GRP')
		else:
			prx_grp = pm.PyNode('proxy_GRP')
		
	if pm.objExists('model_GRP'):
		prx_grp.setParent('model_GRP')
		if pm.objExists('globalCon_GRP'):
			pm.scaleConstraint('globalCon_GRP', prx_grp, mo=True)
	final={}
	
	proxy_grp = geometry.replace('GEO','PROXY_GRP')
	if not pm.objExists(proxy_grp):
		proxy_grp=pm.group(em=True,n=proxy_grp)
	else:
		proxy_grp=pm.PyNode(proxy_grp)
	proxy_grp.setParent(prx_grp)
	
	for proxy in proxies:
		if mpcStyle:
			proxy=pm.PyNode(proxy)
			pm.polySoftEdge(proxy, a=0, ch=0)
			jnt = proxy.name().replace('_GEO','')
			print proxy.name().replace('_GEO','')
			print proxy.name().replace('GEO','JNT')
			if pm.objExists(proxy.replace('GEO','JNT')):
				jnt = proxy.replace('GEO','JNT')
			pm.parentConstraint(jnt, proxy, mo=True)
			proxy.setParent(proxy_grp)
			proxy.rename(geometry+'_'+proxy.replace('GEO','PROXY'))
			print 'adding joint'
			final[proxy]=jnt
		else:
			proxy=pm.PyNode(proxy)
			pm.polySoftEdge(proxy, a=0, ch=0)
			proxy.rename(proxy.replace('GEO','PROXY'))
			final[proxy]=proxy.replace('_PROXY', '')
	return final
コード例 #21
0
ファイル: aw_transform.py プロジェクト: creuter23/tools
    def _freezeWorldTransform(self, args):
        '''This function matches the transform based on world coordinates
        :param name: The name to use.
        '''
        #NEED TO ADD FOR RELATIVE TO PARENT FREEZING
        #if pm.radioCollection( self.hierSel_rc, q=1, selected=True ) == 2:
        #    args = self.get_objectHierarchy_transform(args[0], 'up')
            
        #if pm.radioCollection( self.hierSel_rc, q=1, selected=True ) == 3:
        args = self._get_objectHierarchy_transform(args[0], 'down')
        top=pm.ls(sl=True)[0]
        args.insert(0,top)
        for arg in args:
            #parent a locator -> parent of arg
            loc = (arg+"_LOC")
            if (not pm.objExists(loc)):
                loc = pm.spaceLocator(p=(0,0,0), n=arg+"_LOC")
                arg_parent = pm.listRelatives(arg, p=True)
                if arg_parent==[]:
                    pm.parent( loc, arg )
                else:
                    print loc, arg, arg_parent[0]
                    pm.parent( loc, arg_parent[0])
            arg_pos = pm.xform(arg, query=True, r=True, t=True)
            arg_rot = pm.xform(arg, query=True, r=True, ro=True)
            arg_scl = pm.xform(arg, query=True, r=True, s=True)
            pm.xform(loc, a=True, ro=arg_rot, s=arg_scl, t=arg_pos)
            #remove the locator from the parent in order to get the world coordinates/scale
            pm.parent(loc, w=True)
            #store the transform of the locator then delete it
            ot_data = pm.xform(loc,q=True,r=True,t=True) + pm.xform(loc,q=True,r=True,ro=True) + pm.xform(loc,q=True,r=True,s=True) 
            pm.delete(loc)
            #detect if the object has a origTrans attr
            if (not pm.objExists(arg+'.origTrans')):
                #if not create it
                pm.addAttr(arg, ln='origTrans', dt="string")
            else:
                #if it does throw a prompt asking if you'd like to add onto the previous transform freeze
                prompt_result = pm.confirmDialog (title='Orig Trans Detected!',
                                              message='This object was already frozen,\nUpdate of new position for original transform?',
                                              button=["Update", "Reset and Freeze"],
                                              defaultButton="Update", dismissString="Reset and Freeze")
                print "Need to modify ot_data in this situation...not sure how."
            #record the transform data to a string variable on the arg
            pm.setAttr (arg+'.origTrans', ' '.join(map(str,ot_data)))
	
	def _freezeLocalTransform( self ):
		args = pm.ls(sl=True)
		for arg in args:
			arg.t.get()
			arg.r.get()
			arg.s.get()
		' '.join(map(str,ot_data))
コード例 #22
0
 def checkNeck(ogoat, ygoat, troll):
     ogoat = 'Main_Neck_jnt1_OldGoat'
     ygoat = 'Main_Neck_jnt1_YoungGoat'
     troll = 'Troll_neck_jnt'
     if pm.objExists(ogoat):
         return True
     elif pm.objExists(troll):
         return True
     elif pm.objExists(ygoat):
         return True
     else:
         return False
コード例 #23
0
	def setExpression(self):
		if pm.objExists('olp_intervalsPerOrbits_expression'):
			pm.delete('olp_intervalsPerOrbits_expression')
		if pm.objExists('olp_orbits_expression'):
			pm.delete('olp_orbits_expression')
		
		interv_int = self.interv_int.value()
		orbit_int = self.orbit_int.value()

		intervExpression = pm.expression(o=rigInterv, n='olp_intervalsPerOrbits_expression', s='rx = frame * (360/{0}.000);'.format(interv_int))
		if_block = 'rz = (frame/{0}) * ((360/{1}.000)/2.000);'.format(interv_int, orbit_int)
		orbitExpression = pm.expression(o=rigOrbit, n='olp_orbits_expression', s='if (frame%{0} == 0) {1}'.format(interv_int, if_block))
コード例 #24
0
def check_file( file, skeleton = 0 ):    
    contents = open( file, 'r')
    missing_objects = []
    for line in contents.read().splitlines():
        split = line.split('/')
        if len(split)>1 and line[0] is not '#':
            if split[0] is not ' ' and split[2] is not ' ':
                if skeleton and not pm.objExists( split[0] ):
                    missing_objects.append( split[0] )
                elif not skeleton and not pm.objExists( split[-1] ):
                    missing_objects.append( split[-1] )
    contents.close()
    
    return missing_objects
コード例 #25
0
ファイル: KX_ClothTool.py プロジェクト: TianD/TianD_KX_TOOL
def qClothCmd(*args, **kwargs):
    '''
    create qCloth
    
    step 1: Select an anim geo
    step 2: Duplicate a cloth geo and a output geo from the anim geo
    step 3: Do blendshape both anim geo and cloth geo with output geo
    step 4: Create QCloth on cloth geo
    '''
    
    try:
        pm.loadPlugin("qualoth-2014-x64.mll")
    except:
        pass
    
    sel = pm.ls(sl=1)
    
    outputGrpName = 'output_Grp'
    
    clothGrpName = 'cloth_Grp'
    
    if pm.objExists(outputGrpName):
        outputGrp = pm.PyNode(outputGrpName)
    else :
        outputGrp = pm.createNode('transform', name = outputGrpName)
    
    outputGrp.v.set(0)
    
    if pm.objExists(clothGrpName):
        clothGrp = pm.PyNode(clothGrpName)
    else :
        clothGrp = pm.createNode('transform', name = clothGrpName)
        
    outputGeos = [pm.duplicate(i, name = i.name().replace("_anim", "_output"))[0] for i in sel]
    
    [outputGeo.setParent(outputGrp) for outputGeo in outputGeos]
    
    [i.v.set(0) for i in sel]
    
    clothShape = []
    for i in sel:
        pm.select(i)
        clothShape.append(pm.mel.qlCreateCloth())
    
    clothGeos = [pm.PyNode(i).outputMesh.outputs(p=0)[0] for i in clothShape]
    
    [clothGeo.setParent(clothGrp) for clothGeo in clothGeos]
    
    blendNodes = [pm.blendShape(sel[i], clothGeos[i], outputGeos[i], w = [(0,0), (1,1)]) for i in range(len(sel))]
コード例 #26
0
ファイル: aw_dynChain.py プロジェクト: AndresMWeber/aw
def rig_connectDynCtrl(dynObj, dynCtrl):
	'''Takes a dynamic pm.PyNode connects it to the dynCtrl pm.PyNode.spaceLocator
	Args:
		dynObj (pm.PyNode): the dynamic object to be attached
		dynCtrl (pm.PyNode): the dynamic control to drive
	Returns: (pm.PyNode) - controlled object
	'''
	if pm.objectType(dynObj.getShape()) == 'follicle':
		dynCtrl.pointLock.connect(dynObj.pointLock)
	else:
		for attr in ['simulationMethod','collide','selfCollide','drag','damp','friction','iterations',
					 'stiffness','startFrame','turbulenceStrength','turbulenceFrequency','turbulenceSpeed']:
			if pm.objExists(dynObj.name()+'.'+attr) and pm.objExists(dynCtrl.name()+'.'+attr):
				dynCtrl.attr(attr).connect(dynObj.attr(attr))
	return dynObj
コード例 #27
0
ファイル: lib_attr.py プロジェクト: AndresMWeber/aw
def attr_insertMultiplierOffset(target, source, attrNameA, attrNameB, type='double', min=None, max=None, k=True, cb=False, dv=0):
	'''if the source control's named attribute is not equal(or other operation listed) to compare value, then use it other wise use the other
	Args:
		targetAttr (pm.PyNode):
		sourceCtrl (pm.PyNode):
		attrName (string):
		type (string):
		min (float):
		max (float):
		k (boolean):
		cb (boolean):
		dv (float):
	Returns:
		pm.nt.Condition: condition node that we're using now to connect to that attribute
		attr_insertMultiplier(pm.PyNode('pSphere1.translateZ'), pm.PyNode('pSphere2'), 'multiplyTZ', min=0)
	'''
	mudl = pm.shadingNode('multDoubleLinear', n='%s_%s_to_%s_MUDL'%(source.name(), attrNameA, target.name().replace('.','_')),asUtility=True)
	if not pm.objExists(source.name()+'.'+attrNameA):
		source.addAttr(attrNameA, at=type, dv=dv)
		source.attr(attrNameA).set(k=k)
		if cb:
			source.attr(attrNameA).set(cb=cb)
		source.attr(attrNameA).setMin(min)
		source.attr(attrNameA).setMax(max)
	if not pm.objExists(source.name()+'.'+attrNameB):
		source.addAttr(attrNameB, at=type, dv=dv)
		source.attr(attrNameB).set(k=k)
		if cb:
			source.attr(attrNameB).set(cb=cb)
		source.attr(attrNameB).setMin(min)
		source.attr(attrNameB).setMax(max)
	
	sourceCtrlAttrA = source.attr(attrNameA)
	sourceCtrlAttrA.connect( mudl.input1 )
	
	targetAttrBConnect=False
	if source.attr(attrNameB).isConnected():
		connections = source.attr(attrNameB).listConnections(p=True)
		if len(connections)>1:
			pm.error('not sure what\'s going on but this attribute is connected to more than 1 thing somehow...sorry')
		targetAttrBConnect = connections[0]
	if targetAttrBConnect:
		targetAttrBConnect.connect( mudl.input2 )
	else:
		source.attr(attrNameB).connect( mudl.input2 )
	mudl.output.connect( target.attr(attrNameA),f=True )
	
	return mudl
コード例 #28
0
    def update(self):
        if self.nodeName is None or not pm.objExists(self.nodeName) \
            or self.networkCol is None or not pm.layout(self.networkCol, exists=True):
            return

        nodeAttr = pm.Attribute(self.nodeAttr('aiCustomAOVs'))
        self.updateAOVFrame(nodeAttr)
コード例 #29
0
def setup_control_global_attrs(control, module, prefix=""):
    """ Responsible for setting up global attributes on the control
    Args:
        control (str, pm.nt.Transform): can be anything really, just as long as it exists
        module (pm.nt.Transform): module group to parent controls into
    Returns: None
    """
    for attr in ['global_radius']:
        if not pm.objExists('%s.%s'%(control.name(), attr)):
            control.addAttr('global_radius', at='double', dv=0, k=True)
    attrs = ['tx','ty','tz','rx','ry','rz','sx','sy','sz', 'visibility']
    for attr in attrs:
        control.attr(attr).lock()
        control.attr(attr).setKeyable(False)
    
    # Setup subgroup connections to main control
    """
    for subgroup in ['skeleton','model','parts','controls']:
        attr_name = '%s_vis'%subgroup
        if not pm.objExists('%s.%s'%(control.name(), attr_name)):
            control.addAttr(attr_name,
                            at='long',
                            k=True,
                            dv=1, min=0, max=1)
            control.attr(attr_name).connect(module['top_group'].attr(attr_name))
    """
    to_parent = control.getParent() or control
    to_parent.setParent(module['controls'])
コード例 #30
0
def create(selection=[], options={}):
    # Check if correct
    elements = {}
    print(options)
    for i in selection:
        if type(i) == pc.system.FileReference:
            placer = i.namespace+':PLACER_CTL'
            print("Refed!", i)
            # Collect data
            if pc.objExists(placer):
                if str(i.path) not in elements:
                    elements[str(i.path)]={}
                elements[str(i.path)][i.namespace] = getPlacerValues(placer)
        else:
            print('Not supported',i , type(i), pc.system.FileReference)
    # Format json dict
    comp_path = os.path.join(os.path.abspath(os.getenv('PROJECT')),
                            'assets',
                            'compound',
                            options['compoundname']+'.cpa',
                            )
    # Write out to file
    with open(comp_path, 'w') as al:
        json.dump(elements, al, sort_keys=True, indent=4)
    return(True)
コード例 #31
0
    def __init__(self, prefix='new', baseObj=None):
        """
        :param prefix: str, prefix to name new objects
        :param baseObj: instance of base.module.Base class
        :return: None
        """

        self.topGrp = pm.group(n=prefix + 'Module_GRP', em=1)

        self.controlsGrp = pm.group(n=prefix + 'Controls_GRP',
                                    em=1,
                                    p=self.topGrp)
        self.secControlsGrp = pm.group(n=prefix + 'secondaryControls_GRP',
                                       em=1,
                                       p=self.topGrp)
        self.jointsGrp = pm.group(n=prefix + 'Joints_GRP', em=1, p=self.topGrp)
        self.partsGrp = pm.group(n=prefix + 'Parts_GRP', em=1, p=self.topGrp)
        self.partsNoTransGrp = pm.group(n=prefix + 'PartsNoTrans_GRP',
                                        em=1,
                                        p=self.topGrp)

        pm.hide(self.partsGrp, self.partsNoTransGrp)

        pm.setAttr(self.partsNoTransGrp + '.it', 0, l=1)

        if (pm.objExists('display_CTRL')):
            displayCtrl = pm.ls('display_CTRL')[0]

            levelGrp = [self.controlsGrp, self.secControlsGrp]
            pm.addAttr(displayCtrl,
                       ln=prefix,
                       at='enum',
                       enumName='none:block:all',
                       k=1,
                       dv=1)
            pm.setAttr(displayCtrl + '.' + prefix, cb=1)
            common.setDrivenKey(displayCtrl + '.' + prefix, [0, 1, 2],
                                levelGrp[0] + '.v', [0, 1, 1])
            common.setDrivenKey(displayCtrl + '.' + prefix, [0, 1, 2],
                                levelGrp[1] + '.v', [0, 0, 1])

        # parent module
        if baseObj:
            pm.parent(self.topGrp, baseObj.modulesGrp)
コード例 #32
0
def getInfoFromSelection(geo=None, pos=None):

    if not geo:
        lssl = pm.selected()
        geo = lssl[0]
    else:
        if pm.objExists(geo):
            geo = pm.PyNode(geo)
    if geo.type() == "mesh":
        #mesh = geo
        geo = mesh.getParent()

    if not pos:
        pos = [0, 0, 0]
        if lssl.__len__() > 1:
            inf = lssl[1]

    #print geo, pos
    return geo, inf
コード例 #33
0
def mainGroup(nodes=None):
    '''
    Returns the main group containing the rig.
    '''
    
    if nodes:
        for n in nodes:
            if simpleName(n) == 'main':
                return n
    
    if objExists('|main'):
        return PyNode('|main')
    else:
        # A pymel bug is sometimes returning duplicate nodes
        main = list(set([ obj for obj in ls( 'main', r=True) if not obj.getParent() ]))
        if len(main) == 1:
            return main[0]
        
        return None
コード例 #34
0
ファイル: RenderLayer.py プロジェクト: vfxsnake/AssemblingTK
def RenderLayerFx():

    if not pm.objExists('Fx_RL'):
        rs = renderSetup.instance()
        # Extract Name from Transform
        GetName = 'Fx'

        # Extract Name LigtRig
        SelectionLights = pm.listRelatives(type='transform')
        for selection in SelectionLights:
            if selection.endswith('LIGHTRIG'):
                pass
        # Create and append the render layer
        RsRenderLayer = rs.createRenderLayer(GetName + '_' + 'RL')
        ColectionEnvironment = RsRenderLayer.createCollection('Env' + '_' +
                                                              GetName + '_' +
                                                              'COL')
        ColectionLightRig = RsRenderLayer.createCollection('LightRig' + '_' +
                                                           GetName + '_' +
                                                           'COL')
        ColectionGeoMesh = RsRenderLayer.createCollection('Characters' + '_' +
                                                          GetName + '_' +
                                                          'COL')
        ColectionFx = RsRenderLayer.createCollection('Fx' + '_' + GetName +
                                                     '_' + 'COL')

        ##Append Colection
        # ColectionGeoMesh.getSelector().staticSelection.add(cmds.ls(Selection, long =True))
        # ColectionLightRig.getSelector().setPattern(GetName + '_' + 'LIGHTRIG*')

        ##Switch Create RenderLayer
        rs.switchToLayer(RsRenderLayer)

        ##Build Message Done
        pm.inViewMessage(amg='<hl>Fx_RL_Done!!</hl>.',
                         pos='midCenter',
                         fade=True)

    else:
        pm.select('Fx_RL')
        pm.inViewMessage(amg='<hl>Fx_RL_Exist!!</hl>.',
                         pos='midCenter',
                         fade=True)
コード例 #35
0
    def check(self):
        """@brief Check if all the meshes in the scene are referenced.
        """
        nonReferencedMesh = list()

        for mesh in pm.ls(type="mesh"):
            if not pm.objExists(mesh.name() + ".grid_noCheck"):
                if not mesh.isReferenced():
                    nonReferencedMesh.append(mesh)

        if not nonReferencedMesh:
            self.status = "OK"
        else:
            self.status = self.errorMode
            self.errorNodes = nonReferencedMesh
            for mesh in nonReferencedMesh:
                self.addError("%s is not referenced" % mesh.name())
            self.errorMessage = "%s non referenced mesh(es)" % (
                len(nonReferencedMesh))
コード例 #36
0
 def setup_bank(self):
     """Using the existing bank controls create an attribute driven setup"""
     if not pm.objExists('%s.bankInOut' % self.ctrl_rotation):
         self.ctrl_rotation.srt.addAttr('bankInOut',
                                        at='float',
                                        dv=0,
                                        k=True,
                                        min=-25.0,
                                        max=25.0)
     cnd_in = pm.createNode('condition', n='%s_bankIn_dg' % self.name)
     cnd_out = pm.createNode('condition', n='%s_bankOut_dg' % self.name)
     self.ctrl_rotation.srt.bankInOut.connect(cnd_in.firstTerm)
     self.ctrl_rotation.srt.bankInOut.connect(cnd_in.colorIfTrueR)
     cnd_in.outColorR.connect(self.ctrl_bank_in.buffers[0].rz)
     cnd_in.operation.set(2)
     self.ctrl_rotation.srt.bankInOut.connect(cnd_out.firstTerm)
     self.ctrl_rotation.srt.bankInOut.connect(cnd_out.colorIfTrueR)
     cnd_out.outColorR.connect(self.ctrl_bank_out.buffers[0].rz)
     cnd_out.operation.set(4)
コード例 #37
0
ファイル: baseio.py プロジェクト: jonntd/Public
    def tag_nodes(self):
        """Tag the nodes by reading the currentIO."""
        selection = pm.ls(sl=True)
        for s in selection:
            nodetype = pm.nodeType(s)
            if nodetype == 'transform':
                child = pm.listRelatives(s, c=True)
                if child:
                    s = child[0]
                    nodetype = pm.nodeType(s)
                # end if override nodetype with child shape
            # end if selection is a transform

            if (nodetype not in self.valid_nodetype()):
                msg = 'Type of selection "%s" not valid with %s' % (s, self)
                return logging.error(msg)
            # end if invalid nodetype selected
            if not pm.objExists('%s.%s' % (s, self)):
                s.addAttr(self, at='bool', dv=1)
コード例 #38
0
ファイル: autoren.py プロジェクト: bafly/myScripts
def doRename(template, lssl=None):
    if not lssl:
        lssl = pm.selected()
    sz = len(lssl)
    print "Renaming by template: {}".format(template)
    ls_padding = [x for x in template.split("_") if x.startswith("#")]
    padding = 1
    if not ls_padding:
        ls_padding = [x for x in template.split("_") if x.endswith("#")]
        if not ls_padding:
            print " Index paddings not found, use: ## if one of the field"
            return
    padding = ls_padding[0].count("#")
    print "Given padding: ", padding
    # check if padding can store selection size
    cur_pad = len(repr(sz))
    # if padding is greater than one and number of item is exceeds
    #   padding will conform that items count
    if padding > 1 and cur_pad > padding:
        print " Extending currentPadding to: ", cur_pad
        padding = cur_pad
    idx_part = "1"
    pad_stt = template.find("#")
    pad_cnt = template.count("#")
    repl = template[pad_stt:pad_stt + pad_cnt]
    for i, sel in enumerate(lssl):
        setCurrentName(sel)
        idx = int(idx_part)
        idx_part = findNextIndex(template, idx)
        # idx_part = "{}".format(idx).zfill(padding)
        # new_name = template.replace(ls_padding[0], idx_part)
        print "repl: " + repl
        new_name = template.replace(repl, idx_part)
        if sel.nodeName() == new_name:
            continue
        print "newn: " + new_name
        print "Renaming: {} to: {}".format(sel, new_name)
        if pm.objExists(new_name):
            print " ! Already exists {}".format(new_name)
            new_name += "#"
            print "   adding number at the end {}".format(new_name)
        sel.rename(new_name)
        sel.isRenamed.set(1)
コード例 #39
0
    def findDeformer(self, deformerType='wrap'):
        """
        Find the blendShape from a string
        @param _tranformToCheck: Needs to be a String!!
        """
        result = []
        if not (pm.objExists(self.transform)):
            return result

        validList = mel.eval('findRelatedDeformer("' + str(self.transform) +
                             '")')

        if validList is None:
            return result

        for elem in validList:
            if pm.nodeType(elem) == deformerType:
                result.append(elem)
        return result
コード例 #40
0
def create_shadow_shader_mentalray():
    if not pm.objExists('shadow_SG_hs_mentalray'):
        shadow_shader = pm.shadingNode('useBackground',
                                       asShader=1,
                                       name='shadow_shader_hs_mentalray')
        shadow_sg = pm.sets(renderable=1,
                            noSurfaceShader=1,
                            empty=1,
                            name='shadow_SG_hs_mentalray')
        shadow_shader.specularColor.set(0, 0, 0)
        shadow_shader.reflectivity.set(0)
        shadow_shader.reflectionLimit.set(0)
        shadow_shader.outColor >> shadow_sg.surfaceShader
        return [shadow_shader, shadow_sg]
    else:
        return [
            pm.PyNode('shadow_shader_hs_mentalray'),
            pm.PyNode('shadow_SG_hs_mentalray')
        ]
コード例 #41
0
    def create_local_spaces(self):
        spaces_names = []
        space_locs = []
        for space in self.model.space_list:
            name = str(space).replace("_OUTPUT", "")
            if "local_ctrl" in name:
                name = "world"
            spaces_names.append(name)

            if pmc.objExists("{0}_{1}_SPACELOC".format(self.model.module_name,
                                                       name)):
                pmc.delete("{0}_{1}_SPACELOC".format(self.model.module_name,
                                                     name))
            space_loc = pmc.spaceLocator(p=(0, 0, 0),
                                         n="{0}_{1}_SPACELOC".format(
                                             self.model.module_name, name))
            space_locs.append(space_loc)

        spaces_names.append("local")

        fk_ctrls = self.created_spine_ctrl

        fk_ctrls[0].addAttr("space",
                            attributeType="enum",
                            enumName=spaces_names,
                            hidden=0,
                            keyable=1)

        for i, space in enumerate(self.model.space_list):
            space_locs[i].setAttr(
                "translate",
                pmc.xform(self.created_spine_jnts[0], q=1, ws=1,
                          translation=1))
            pmc.parent(space_locs[i], space)

            fk_space_const = pmc.parentConstraint(space_locs[i],
                                                  fk_ctrls[0].getParent(),
                                                  maintainOffset=1)

            rig_lib.connect_condition_to_constraint(
                "{0}.{1}W{2}".format(fk_space_const, space_locs[i],
                                     i), fk_ctrls[0].space, i,
                "{0}_{1}_COND".format(fk_ctrls[0], spaces_names[i]))
コード例 #42
0
def interface(ui_object, attr_name, spaces):

    attr_name = '{}'.format(attr_name)
    if len(spaces) != 1:
        enum_names = ":".join(spaces)
    else:
        enum_names = spaces

    _logger.debug(ui_object)
    _logger.debug(attr_name)

    string_ui = "{}.{}".format(ui_object.name(), attr_name)

    if pmc.objExists(string_ui):
        current_enums = ui_object.attr(attr_name).getEnums()
        match_result = set(spaces) & set(current_enums)

        if len(match_result) == 0:
            recompile = []
            for i in range(0, len(current_enums)):
                recompile.append(current_enums[i])
            enum_names = ":".join(recompile + spaces)

        pmc.addAttr(string_ui,
                    e=True,
                    enumName=enum_names,
                    r=True,
                    w=True,
                    k=True,
                    dv=0)

    else:
        _logger.debug(enum_names)
        pmc.addAttr(ui_object,
                    longName=attr_name,
                    attributeType='enum',
                    enumName=enum_names,
                    r=True,
                    w=True,
                    k=True,
                    dv=0)

    return ui_object.attr(attr_name)
コード例 #43
0
def show():        #check modifyed
    if not sceneName():
        PopupError('Save scene before continue')
        return
    if cmds.file(q=True, modified=True) and not objExists(submitter_variables.root_group_name):
        if confirmDialog( title='Continue ?',
                          message='Scene have unsaved changes\n\nContinue without saving?',
                          button=['Yes','No'],
                          defaultButton='Yes',
                          cancelButton='No',
                          dismissString='No' ) == 'No':
            return
    def showUI():
        from . import submitter_window
        reload(submitter_window)
        w = submitter_window.SubmitterWindowClass()
        w.show()
    load_ai()
    QTimer.singleShot(1000, showUI)
コード例 #44
0
    def execute(self):
        self.prebuild()

        for obj in self.selection:
            if pmc.objExists("{0}_ctrl_OFS".format(obj)):
                pmc.delete("{0}_ctrl_OFS".format(obj))

            pmc.select(cl=1)

            ctrl_shape = pmc.circle(c=(0, 0, 0),
                                    nr=self.orientation,
                                    sw=360,
                                    r=self.model.size,
                                    d=3,
                                    s=8,
                                    n="{0}_CTRLShape".format(obj),
                                    ch=0)[0]
            ctrl = rig_lib.create_jnttype_ctrl("{0}_CTRL".format(obj),
                                               ctrl_shape,
                                               drawstyle=2,
                                               rotateorder=self.rotate_order)

            pmc.select(cl=1)

            ctrl_ofs = pmc.joint(p=(0, 0, 0), n="{0}_ctrl_OFS".format(obj))
            ctrl_ofs.setAttr("rotateOrder", self.rotate_order)
            ctrl_ofs.setAttr("drawStyle", 2)
            pmc.parent(ctrl, ctrl_ofs)

            if pmc.objectType(obj) == "joint" or pmc.xform(
                    obj, q=1, rotatePivot=1) == [0, 0, 0]:
                pmc.xform(ctrl_ofs,
                          ws=1,
                          matrix=pmc.xform(obj, q=1, ws=1, matrix=1))
            else:
                pmc.xform(ctrl_ofs,
                          ws=1,
                          translation=pmc.xform(obj, q=1, ws=1, rotatePivot=1))
                pmc.xform(ctrl_ofs,
                          ws=1,
                          rotation=pmc.xform(obj, q=1, ws=1, rotation=1))

        pmc.select(self.selection)
コード例 #45
0
ファイル: rope.py プロジェクト: Aiacos/DevPyLib
def rp_Twist():
    """..............................................................................................//"""

    ncj = int(pm.intField('NCJ', q=1, v=1))
    # > control joints
    # > selection list
    s = pm.ls(sl=1)
    rp_check(s)
    cj = pm.ls((s[0] + "_ctj_*"), typ="joint")
    # > twist and roll
    if pm.checkBoxGrp('MRL', q=1, v1=1):
        if pm.getAttr(s[0] + "_tw_hl.dtce") == 1:
            pm.setAttr((s[0] + "_tw_hl.dtce"), 0)
            pm.disconnectAttr((cj[0] + ".wm[0]"), (s[0] + "_tw_hl.dwum"))
            pm.disconnectAttr((cj[(ncj - 1)] + ".wm[0]"),
                              (s[0] + "_tw_hl.dwue"))

        rl = str(pm.createNode('multiplyDivide', n=(s[0] + "_roll")))
        pm.connectAttr((cj[0] + ".rx"), (rl + ".i1x"), f=1)
        pm.setAttr((rl + ".i2x"), (-1))
        pm.connectAttr((cj[0] + ".rx"), (s[0] + "_tw_hl" + ".rol"), f=1)
        tw = str(pm.createNode('plusMinusAverage', n=(s[0] + "_twist")))
        pm.connectAttr((rl + ".ox"), (tw + ".i1[0]"), f=1)
        pm.connectAttr((cj[(ncj - 1)] + ".rx"), (tw + ".i1[1]"), f=1)
        pm.connectAttr((tw + ".o1"), (s[0] + "_tw_hl" + ".twi"), f=1)

    # > advanced twist
    elif pm.objExists(s[0] + "_twist"):
        pm.delete((s[0] + "_twist"), (s[0] + "_roll"))
        pm.disconnectAttr((cj[0] + ".rx"), (s[0] + "_tw_hl" + ".rol"))

    pm.setAttr((s[0] + "_tw_hl.dtce"), 1)
    pm.setAttr((s[0] + "_tw_hl.dwut"), 4)
    pm.setAttr((s[0] + "_tw_hl.dwua"), 0)
    pm.connectAttr((cj[0] + ".wm[0]"), (s[0] + "_tw_hl.dwum"))
    pm.connectAttr((cj[(ncj - 1)] + ".wm[0]"), (s[0] + "_tw_hl.dwue"))
    pm.setAttr((s[0] + "_tw_hl.dwuy"), 1)
    pm.setAttr((s[0] + "_tw_hl.dwvy"), 1)
    pm.setAttr((s[0] + "_tw_hl.dwuz"), 0)
    pm.setAttr((s[0] + "_tw_hl.dwvz"), 0)
    pm.setAttr((s[0] + "_tw_hl" + ".rol"), 0)
    pm.setAttr((s[0] + "_tw_hl" + ".twi"), 0)
    pm.select(s[0])
コード例 #46
0
def rad_load_associations():
    someFailures = False
    targetFile = ""
    files = cmds.fileDialog2(dialogStyle=2,
                             fileFilter="*.radpw",
                             fileMode=1,
                             caption="Load Pickwalk Configuration",
                             okCaption="Load")
    if files:
        if len(files) > 0:
            targetFile = files[0]
    if not targetFile:
        return
    allNodes = cmds.ls(recursive=True)
    with open(targetFile) as f:
        for line in f:
            if not line.startswith("This"):
                infoArray = line.split()
                # node-name dir dir dir dir
                nodeName = infoArray[0]
                if pm.objExists(nodeName):
                    infoIndex = 1
                    for direction in DIRECTIONS:
                        dirNode = infoArray[infoIndex]
                        infoIndex += 1
                        if dirNode != "null":
                            try:
                                if not pm.attributeQuery(
                                        dir_to_attr(direction),
                                        node=nodeName,
                                        exists=True):
                                    pm.addAttr(nodeName,
                                               longName=dir_to_attr(direction),
                                               attributeType="message")
                                make_pick_walk(nodeName, dirNode, direction)
                            except:
                                print "Error during load of " + nodeName + " -> " + direction + " -> " + dirNode
                                someFailures = True
    if someFailures:
        pm.warning(
            "Some relationships failed to load (possibly due to different set of nodes)"
        )
コード例 #47
0
    def unhideAllPieces(self, namespaceString):

        #check if namespace is root
        if (namespaceString == 'root'): namespaceString = ''

        #check if namespace is root
        if not (namespaceString):
            if (self.verbose):
                print('Please select namespace different from root')
            return None

        #grpList
        grpList = ['innerHull_grp', 'outerHull_grp', 'intermediary_grp']

        #Iterate grpLIst and unhide pieces
        for groupName in grpList:

            try:

                #Check if topGrp exists
                if not (pm.objExists(namespaceString + ':' + groupName)):
                    if (self.verbose):
                        print('Object ' + namespaceString + ':' + groupName +
                              ' does not exists. Continuing')
                    continue

                #get piecesTopGrp
                piecesTopGrp = pm.PyNode(namespaceString + ':' + groupName)

                #get piece_grp and unhide it
                for pieceGrp in piecesTopGrp.getChildren():
                    pieceGrp.visibility.set(True)

                #success msg
                if (self.verbose):
                    print('Succesfully unhid all pieces in ' +
                          piecesTopGrp.name() + '. Continuing...')

            except:
                if (self.verbose):
                    print('Error unhiding pieces in ' + namespaceString + ':' +
                          groupName + '. Continuing...')
コード例 #48
0
def arnoldspshmaker(path, meshName, texSets, fileType, autocbvalue, mattype):
    pm.arnoldFlushCache(textures=True)
    udimvial = [
        "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009",
        "1011", "1012", "1013", "1014", "1015", "1016", "1017", "1018", "1019"
    ]
    udimlists = list(set(texSets) & set(udimvial))
    if udimlists == []:
        for texSet in texSets:
            if pm.objExists(texSet) == True:
                shader = pm.listConnections(texSet + ".aiSurfaceShader", d=0)
                if shader == []:
                    shader = pm.listConnections(texSet + ".surfaceShader", d=0)
                pm.hyperShade(o=shader[0])
                mesh = pm.ls(sl=1, r=1)
                if mattype.find("ARNOLD4(aistandard)") != -1:
                    Aishaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
                elif mattype.find("Arnold4(AlSurface)") != -1:
                    Alshaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
            else:
                mesh = []
                if mattype.find("ARNOLD4(aistandard)") != -1:
                    Aishaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
                elif mattype.find("Arnold4(AlSurface)") != -1:
                    Alshaderfunc(path, meshName, texSet, "." + fileType,
                                 autocbvalue, mesh)
    else:
        sel = pm.ls(sl=1, type="transform")
        if sel != []:
            mesh = [a for a in sel if pm.nodeType(a.getShape()) == "mesh"]
            if mesh != []:
                if mattype.find("ARNOLD4(aistandard)") != -1:
                    Aishaderfunc(path, meshName, texSets[0], "." + fileType,
                                 autocbvalue, mesh)
                elif mattype.find("Arnold4(AlSurface)") != -1:
                    Alshaderfunc(path, meshName, texSets[0], "." + fileType,
                                 autocbvalue, mesh)
            else:
                pm.warning("请选择模型!!")
コード例 #49
0
def resolution_init():
    """
    Sets the resolution on first launch.

    Extracting a "width" and "height" custom attributes,
    on the parent entity of the task.

    Adds a "ftrackResolutionSet" attribute to the defaultResolution node,
    which indicates whether to set the resolution on startup.
    """

    defaultResolution = pm.PyNode("defaultResolution")
    task = ftrack.Task(os.environ["FTRACK_TASKID"])

    # Adding/Checking ftrack resolution attribute
    resolution_set = False
    if hasattr(defaultResolution, "ftrackResolutionSet"):
        attr = pm.Attribute("defaultResolution.ftrackResolutionSet")
        resolution_set = attr.get()
    else:
        pm.addAttr(
            defaultResolution,
            longName="ftrackResolutionSet",
            defaultValue=True,
            attributeType="bool"
        )

    if not resolution_set:
        width = task.getParent().get("width")
        defaultResolution.width.set(width)
        pm.warning("Changed resolution width to: {0}".format(width))
        height = task.getParent().get("height")
        defaultResolution.height.set(height)
        pm.warning("Changed resolution height to: {0}".format(height))

        # Vray specific resolution
        if pm.objExists("vraySettings"):
            vray_settings = pm.PyNode("vraySettings")
            vray_settings.width.set(width)
            pm.warning("Changed vray resolution width to: {0}".format(width))
            vray_settings.height.set(height)
            pm.warning("Changed vray resolution height to: {0}".format(height))
コード例 #50
0
ファイル: Ppl_assetT.py プロジェクト: octvision/oct
 def cmd_txsnm_chk_bt(self):  #check 贴图命名
     u"""
     >>check 贴图命名 :  项目缩写为 前缀, 使用 数字 0-9 字母a-zA-Z 下划线 _  点.
                        贴图文件命名及路径中 回避 中文
                        贴图文件命名及路径中 不能有  空格 - () 等 特殊字符
     """
     chk_labels = {
         'noExists': u'贴图不存在',
         'iffyName': u'贴图命名 应由 (字母/数字/_/.) 组成',
         'seqIffyName': u'序列贴图序号存在异常 正常为 ***.0001.jpg',
         'prefIffyName': u'贴图前缀与当前任务不匹配'
     }
     res = self.chk_txf_name()
     if not res: return
     olnps = [
         ea for ea in pm.lsUI(panels=True) if ea.type() == 'ToutlinerEditor'
     ]
     if olnps:
         mc.outlinerEditor(olnps[0].name(), showSetMembers=True, e=True)
     res_str = u'>>>请检查列出的file节点 贴图命名 所描述的错误{}'.format(os.linesep)
     ck_cnt = 0
     res_total_sets = None
     if pm.objExists('Check_Error_information_Sets'):
         res_total_sets = pm.PyNode('Check_Error_information_Sets')
         [
             pm.delete(ea_sets)
             for ea_sets in res_total_sets.listConnections()
         ]
     res_total_sets = pm.sets(name='Check_Error_information_Sets', em=True)
     for ea_ck_lb in chk_labels:
         if res[ea_ck_lb]:
             res_sets = pm.sets(name="CheckRes_{}".format(ea_ck_lb))
             res_total_sets.add(res_sets.name())
             res_str += u'\t{}{}'.format(chk_labels[ea_ck_lb], os.linesep)
             for ea_fn in res[ea_ck_lb]:
                 res_sets.add(ea_fn.name())
                 res_str += u"\t\t>>>File Node >> {:<32}\t>>>Texture File>>  {:<120}\t 异常部分: {}{}".format(
                     ea_fn.name(), res[ea_ck_lb][ea_fn].keys()[0],
                     res[ea_ck_lb][ea_fn].values()[0], os.linesep)
             ck_cnt += 1
     if ck_cnt: print res_str
     else: print(u">>>没有贴图节点被check")
コード例 #51
0
def NoseBuild():
	noseLocHier = pm.listRelatives("NoseSetup",c=True)
	NosejntGrp = pm.group(n="NoseJnt_Grp")
	for i in range(len(noseLocHier)):
		name = noseLocHier[i].split("Loc")
		jnt = pm.joint(n=name[0]+"Jnt"+name[1])
		pm.delete(pm.parentConstraint(noseLocHier[i],jnt))
		pm.parent(jnt,jntGrp)
		pm.select(cl=True)
		
	### Nose Ctrl Created on Joints ###
	noseJntGrpHier = pm.listRelatives(NosejntGrp,c=True)
	pm.select(cl=True)
	noseCtrlGrp = pm.group(n="NoseCtrl_Grp")
	for i in range(len(noseJntGrpHier)):
		pm.select(cl=True)
		jntCtrlName = noseJntGrpHier[i].split("Jnt")
		offsetJnt = pm.joint(n="FKOffset"+jntCtrlName[0]+jntCtrlName[1])
		pm.setAttr(offsetJnt+".drawStyle",2)
		pm.select(cl=True)
		extraGrp = pm.group(n="FKExtra"+jntCtrlName[0]+jntCtrlName[1])
		pm.parent(extraGrp,offsetJnt)
		pm.select(cl=True)
		ctrl = pm.circle(n="FK"+jntCtrlName[0]+jntCtrlName[1]+"_CTRL",r=.2,ch=False)
		fkxJnt = pm.joint(n="FKX"+jntCtrlName[0]+jntCtrlName[1])
		pm.setAttr(fkxJnt+".drawStyle",2)
		pm.parent(ctrl[0],extraGrp)
		pm.parent(offsetJnt,noseCtrlGrp)
		pm.delete(pm.parentConstraint(noseJntGrpHier[i],offsetJnt))
		pm.parentConstraint(fkxJnt,noseJntGrpHier[i])
	
	pm.parent(["FKOffsetSneer_L","FKOffsetSneer_R"],"FKXMuzzle")
	pm.select(cl=True)
	noseGrp = pm.group(n="NoseGrp")
	pm.parent([NosejntGrp,noseCtrlGrp],noseGrp)
	pm.delete("NoseSetup")
	
	if not pm.objExists("FacialGroup"):
		pm.group(n="FacialGroup")
	pm.parent(noseGrp,"FacialGroup")
	
	print ("Sneer Build"),
コード例 #52
0
    def buildSet(self):
        selDelete = pm.ls('*_vehicleDelete')
        deleteETC = pm.delete(selDelete)
        dmtList = [
            'frontWheel_R_distance_MULT', 'frontWheel_L_distance_MULT',
            'backWheel_R_distance_MULT', 'backWheel_L_distance_MULT'
        ]
        dmtCtlList = [
            'frontWheel_R_CTL', 'frontWheel_L_CTL', 'backWheel_R_CTL',
            'backWheel_L_CTL'
        ]
        for i in range(len(dmtList)):
            diameter = pm.getAttr(dmtList[i] + '.outputX')
            pm.setAttr(dmtCtlList[i] + '.diameter', diameter)

        pm.parentConstraint('body_M_pivTarget_GRP',
                            'body_M_control_conGRP',
                            mo=1)
        parList = [
            'sky_M_CTL', 'body_M_CTL', 'frontDoor_L_CTL', 'backDoor_L_CTL',
            'frontDoor_R_CTL', 'backDoor_R_CTL', 'frontWheel_R_tgetJNT',
            'backWheel_R_tgetJNT', 'frontWheel_L_tgetJNT',
            'backWheel_L_tgetJNT'
        ]
        chiList = [
            'root_M_skinJNT', 'body_M_skinJNT', 'frontDoor_L_skinJNT',
            'backDoor_L_skinJNT', 'frontDoor_R_skinJNT', 'backDoor_R_skinJNT',
            'frontWheel_R_skinJNT', 'backWheel_R_skinJNT',
            'frontWheel_L_skinJNT', 'backWheel_L_skinJNT'
        ]
        for i in range(len(parList)):
            if pm.objExists(chiList[i]):
                pm.parentConstraint(parList[i], chiList[i], mo=1)
                pm.scaleConstraint(parList[i], chiList[i], mo=1)
            else:
                delName = chiList[i].split('_skinJNT')[0]
                pm.delete(delName + '*')

        pm.setAttr('main_M_CTL_GRP.visibility', 1)
        pm.setAttr('poser_GRP.visibility', 0)
        selDeleteEnd = pm.ls('*_endVehicleDelete')
        deleteETCEnd = pm.delete(selDeleteEnd)
コード例 #53
0
    def file_control(self, scene_object, **kwargs):
        scale = kwargs.pop('scale', 1.0)
        name = kwargs.pop('name', None)
        control_type = kwargs.pop('control_type', 'Move')

        scene_object = dataValidators.as_pymel_nodes(scene_object)
        MoversTypeDic = {
            "move": {"filename": "ControlMover.mb", "object": "MoverControl"},
            "v": {"filename": "ControlV.mb", "object": "VControl"},
            "head": {"filename": "ControlHead.mb", "object": "HeadControl"},
            "circleDeform": {"filename": "ControlCircularDeform.mb", "object": "CircularDeform"}
        }
        path = os.path.dirname(RMRigTools.__file__)
        RMPYPATH = os.path.split(path)
        FinalPath = os.path.join(RMPYPATH[0], "RMPY\AutoRig\RigShapes", MoversTypeDic[control_type]["filename"])
        if os.path.isfile(FinalPath):
            pm.importFile(FinalPath, i=True, type="mayaBinary", ignoreVersion=True, mergeNamespacesOnClash=False,
                                    rpr="ControlMover", pr=False)
        else:
            print "archivo no encontrado %s , %s, %s "% (path, RMPYPATH, FinalPath)
            return None

        control = pm.ls(MoversTypeDic[control_type]["object"])[0]

        if pm.objExists(control):
            if name:
                control = pm.rename(control, name)

            pm.setAttr(control + ".scale", scale, scale, scale)

            pm.makeIdentity(control, apply=True, t=1, r=1, s=1)

            self.name_convention.rename_name_in_format(control, objectType='control')

            transform.align(scene_object, control)

            reset_group = self.rigTools.RMCreateGroupOnObj(control)
            self.scale_controls(reset_group)
            return reset_group, control
        else:
            print "Error importing Shape File"
            return None
コード例 #54
0
    def on_delete_btn(self, *args):
        # Delete image plane handler

        confirm = pm.confirmDialog(title='Delete',
                                   message='Deleting image plane %s ?' %
                                   (self.currentImgPlane),
                                   button=['Yes', 'No'],
                                   defaultButton='Yes',
                                   cancelButton='No',
                                   dismissString='No')

        if confirm == 'Yes':
            print('ipm: deleting %s' % self.currentImgPlane)
            if pm.objExists('%s_mover' % self.currentImgPlane[0]):
                pm.delete('%s_mover' % self.currentImgPlane[0])
                pm.delete('%s_moveroffset' % self.currentImgPlane[0])

            pm.delete(pm.listRelatives(self.currentImgPlane, p=1))
            self.imp_option_list()
            self.create()
コード例 #55
0
    def run(self, nodes=None):
        current_selection = nodes or pm.selected()
        nodes_to_select = list()

        for node in current_selection:

            side = crab.config.get_side(node.name())
            opp = crab.config.MIDDLE

            if side == crab.config.RIGHT:
                opp = crab.config.LEFT

            elif side == crab.config.LEFT:
                opp = crab.config.RIGHT

            opp_name = node.name().replace(side, opp)
            if pm.objExists(opp_name):
                nodes_to_select.append(opp_name)

        pm.select(nodes_to_select)
コード例 #56
0
    def assignMaterial(self, node, shader='surfaceShader'):
        _logger.debug('Creating shader %s'%node)
        pm.delete(self.name + '_templateShader')
        if pm.objExists(self.name + '_templateShader') == False:
            shaderNode = pm.shadingNode(shader, asShader=True, name=self.name + '_templateShader')
            pm.sets(renderable=True, noSurfaceShader=True, empty=True, name=shaderNode + 'SG')


            _logger.debug(Template.COLOR_PRESETS[self.color])
            pm.setAttr(shaderNode + '.outColor',
                       Template.COLOR_PRESETS[self.color][0],
                       Template.COLOR_PRESETS[self.color][1],
                       Template.COLOR_PRESETS[self.color][2], type='double3')
            pm.setAttr(shaderNode + '.outTransparency', [.5, .5, .5] )
            pm.connectAttr(shaderNode + '.outColor', shaderNode + 'SG.surfaceShader')
        else:
            shaderNode = pm.PyNode(self.name + '_templateShader')

        _logger.debug('Assigning color schader %s'% shaderNode )
        pm.sets(shaderNode + 'SG', edit=True, forceElement=node)
コード例 #57
0
def add_a_keyable_attribute(myObj,
                            oDataType,
                            oParamName,
                            oMin=None,
                            oMax=None,
                            oDefault=0.0):
    """adds an attribute that shows up in the channel box; returns the newly created attribute"""
    oFullName = '.'.join([str(myObj), oParamName])
    if pm.objExists(oFullName):
        return pm.PyNode(oFullName)
    else:
        myObj.addAttr(oParamName, at=oDataType, keyable=True, dv=oDefault)
        myAttr = pm.PyNode(myObj + '.' + oParamName)
        if oMin != None:
            myAttr.setMin(oMin)
        if oMax != None:
            myAttr.setMax(oMax)
        pm.setAttr(myAttr, e=True, channelBox=True)
        pm.setAttr(myAttr, e=True, keyable=True)
        return myAttr
コード例 #58
0
def parent_by_name(obj):
    name = obj.nodeName()
    parents = name.split('___')
    first_parent = parents[0]

    obj_path = '|'
    if obj.getParent():
        obj_path = obj.getParent().longName()

    first_parent_path = obj_path + '|' + first_parent
    if pm.objExists(first_parent_path):
        pm.parent(obj, first_parent_path)
        pm.rename(obj, '___'.join(parents[1:]))
    else:
        pm.group(n=first_parent)
        pm.rename(obj, '___'.join(parents[1:]))
        pm.select(obj)

    if '___' in obj.nodeName():
        parent_by_name(obj)
コード例 #59
0
ファイル: ka_animation.py プロジェクト: 3dkris/ka_maya
def storeAllControls(allControls=None):
    if not allControls:
        allControls = pymel.ls(selection=True)

    if pymel.objExists(CONTROLS_SET_NAME):

        result = cmds.confirmDialog(title='Overwrite existing controls set?',
                                    message='Overwrite existing controls set?',
                                    button=['OK', 'Cancel'],
                                    defaultButton='Cancel',
                                    cancelButton='Cancel',
                                    dismissString='Cancel')
        if result == 'OK':
            pymel.delete(CONTROLS_SET_NAME)
        else:
            return None

    controlSet = pymel.sets(allControls)
    controlSet.rename(CONTROLS_SET_NAME)
    controlSet.addAttr(CURRENT_ANIMATION_FRAME_SET_ATTR_NAME, at='message')
コード例 #60
0
ファイル: rigUnreal.py プロジェクト: sbourgoing/omtk_unreal
    def pre_build(self):
        """
        Pre build routine before the rig is build

        :return:
        """
        super(RigUnreal, self).pre_build(create_master_grp=True,
                                         create_layer_jnt=True)

        #
        # Create scalar joint to flip export from maya to unreal
        #

        # Build the scene root
        if pymel.objExists(self.nomenclature.scalar_root_name):
            self.scene_root = pymel.PyNode(self.nomenclature.scalar_root_name)
        else:
            self.scene_root = pymel.joint(
                name=self.nomenclature.scalar_root_name)
            self.scene_root.attr("jointOrientX").set(-90)