示例#1
0
文件: lattice.py 项目: Bumpybox/Tapp
def latticeRemove():

    #undo enable
    cmds.undoInfo(openChunk=True)

    #getting nodes
    sel = cmds.ls(selection=True)
    if not sel:
        cmds.warning('No nodes selected!')
        return

    lat = sel[-1]
    objs = sel[0:-1]

    if cmds.nodeType(cmds.listRelatives(lat, shapes=True)[0]) != 'lattice':
        cmds.warning('Last selected is NOT a lattice!')
        return

    #removing from lattice
    for obj in objs:
        try:
            cmds.lattice(lat, e=True, remove=True, geometry=obj)

            #disconnecting shapes
            shapes = cmds.listRelatives(obj, shapes=True)
            for shp in shapes:
                source = cmds.listConnections(shp + '.inMesh', source=True)
                if cmds.nodeType(source) == 'ffd':
                    attr = cmds.listConnections(shp + '.inMesh', plugs=True)[0]
                    cmds.disconnectAttr(attr, shp + '.inMesh')
        except:
            pass

    cmds.undoInfo(closeChunk=True)
示例#2
0
    def filterSelection(self):
        """
            from a raw list of items, returns 1 dict containing:
            {[meshes], [cameras], [locators], [lights]}
        """
        # get current selection
        cmds.select(hi = True)
        selection = [str(item) for item in cmds.ls(sl = True)]

        # fill the items dict from the raw selection
        items = {}
        # meshes
        items['meshes'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \
                    for node in selection if cmds.nodeType(node) == "mesh"]
        # cameras
        items['cameras'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \
                    for node in selection if cmds.nodeType(node) == "camera"]
        # locators
        items['locators'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \
                    for node in selection if cmds.nodeType(node) == "locator"]
        # lights
        items['lights'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \
                    for node in selection if 'Light' in cmds.nodeType(node)]

        return items
示例#3
0
def getCurrentCamera():
    '''
    Returns the camera that you're currently looking through.
    If the current highlighted panel isn't a modelPanel, 
    '''
    
    panel = mc.getPanel(withFocus=True)
    
    if mc.getPanel(typeOf=panel) != 'modelPanel':
        #just get the first visible model panel we find, hopefully the correct one.
        for p in mc.getPanel(visiblePanels=True):
            if mc.getPanel(typeOf=p) == 'modelPanel':
                panel = p
                mc.setFocus(panel)
                break
    
    if mc.getPanel(typeOf=panel) != 'modelPanel':
        OpenMaya.MGlobal.displayWarning('Please highlight a camera viewport.')
        return False
    
    camShape = mc.modelEditor(panel, query=True, camera=True)

    if not camShape:
        return False
    
    if mc.nodeType(camShape) == 'transform':
        return camShape
    elif mc.nodeType(camShape) == 'camera':
        return mc.listRelatives(camShape, parent=True)[0]
def SundayRenderToolsChangeTextureResolution(object, level):
    sel = cmds.ls(selection = True)
    if object == 'selected':
        if len(sel) == 0:
            SundayDialogPy.SundayDialogConfirm('ERROR                       ', 'Nothing selected.', 'OK')
        else:
            cmds.hyperShade('', shaderNetworksSelectMaterialNodes = True)
            selShader = cmds.ls(selection = True)
            for curSelShader in selShader:
                notes = cmds.hyperShade(listUpstreamNodes = curSelShader)
                for note in notes:
                    if cmds.nodeType(note) == 'file' or cmds.nodeType(note) == 'psdFileTex':
                        cmds.select(note)
                        SundayRenderToolsChangeTextureResolutionSet(level, note)
                        continue
                
            
    elif object == 'global':
        notes = cmds.ls(type = 'file')
        for note in notes:
            cmds.select(note)
            SundayRenderToolsChangeTextureResolutionSet(level, note)
        
    
    
    try:
        cmds.select(sel)
    except:
        pass
示例#5
0
def copy_user_attr(selparentshapes, seltargetshapes, copyUV=True):
    listattrvalue = {}
    listdatatype = {}
    userattr = cmds.listAttr(selparentshapes, ud=True)
    if copyUV and cmds.nodeType(seltargetshapes) == 'mesh' and cmds.nodeType(selparentshapes) == 'mesh':
            cmds.transferAttributes(selparentshapes, seltargetshapes, transferUVs=1, transferColors=2, searchMethod=3, sampleSpace=5, flipUVs=False)
    if userattr:
        for attr in userattr:
            nodetype = cmds.nodeType(selparentshapes)
            checkrendershape = cmds.getAttr(selparentshapes + '.intermediateObject')
            if checkrendershape != 1 or nodetype != 'mesh':
                key = attr
                value = cmds.getAttr("%s.%s" % (selparentshapes, key))
                data = cmds.getAttr("%s.%s" % (selparentshapes, key), typ=True)
                listattrvalue[key] = value
                listdatatype[key] = data
    checkrendershape = cmds.getAttr(seltargetshapes + '.intermediateObject')
    if checkrendershape != 1:
        for key in listattrvalue:
            if not cmds.attributeQuery(key, node=seltargetshapes, ex=True):
                if listdatatype[key] == 'string':
                    cmds.addAttr(seltargetshapes, longName=key, dataType=listdatatype[key])
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                else:
                    cmds.addAttr(seltargetshapes, longName=key)
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
            else:
                cmds.warning('Attribute ' + key + ' already on ' + seltargetshapes)
                if cmds.getAttr("%s.%s" % (seltargetshapes, key), se=True):
                    if listdatatype[key] == 'string':
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                    else:
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
def stabilizer (task):
	camera	= Camera()
	point	= cmds.ls (selection = True)

	if task == 'end':
		# turn off stab
		expression		= str (cmds.expression ('stabilizator_expression', string = True, query = True))
		camera.shape	= expression[2:expression.find('#')]
		cmds.delete ('stabilizator_expression')
		camera.reset_camera ()
		cmds.button ('button_stabilizer',
					edit				= True,
					label				= 'stabilize',
					backgroundColor		= (0, 0.5, 0),
					command				= 'fstab.stabilizer("start")')

	else:
		# start stab
		if cmds.objExists ('stabilizator_expression'):
			# stabilizator exists
			expression		= str (cmds.expression ('stabilizator_expression', string = True, query = True))
			camera.shape	= expression[2:expression.find('#')]
			cmds.delete ('stabilizator_expression')
			cmds.select (camera.shape, replace = True)
			cmds.warning (('>>> STAB WAS TURNED ON. CHECK: ' + camera.shape + ' <<< FOR NONZERO OFFSET VALUES ::..'))
		
		else:
			if cmds.nodeType (point) != 'mesh' and cmds.nodeType (point) != 'transform' and len (point) == 0:
				# wrong selection
				cmds.warning ('..:: SELECT SOMETHING TO STABILIZE ::..')
			else:
				point = point[0]
				
				if point != camera.transform and point != camera.shape and camera.transform != 'empty':
					# stabilize
					cmds.setAttr( camera.shape + '.displayResolution', 0)
					cmds.setAttr( camera.shape + '.displayFilmGate', 0)
				
					expression = '//%s#' % camera.shape
					expression += '\npython "import maya.cmds as cmds";'
					expression += '\npython "fov_h = cmds.camera (\'%s\', query = True, horizontalFieldOfView = True)";' % camera.shape
					expression += '\npython "fov_v = cmds.camera (\'%s\', query = True, verticalFieldOfView = True)";' % camera.shape
					expression += '\npython "aperture_h = cmds.camera (\'%s\', query = True, horizontalFilmAperture = True)";' % camera.shape
					expression += '\npython "aperture_v = cmds.camera (\'%s\', query = True, verticalFilmAperture = True)";' % camera.shape
					expression += '\n$pos=`python "fstab.get_normalized_screen_position(\'%s\',\'%s\',fov_h, fov_v,aperture_h,aperture_v)"`;' % (point, camera.transform)
					expression += '\nsetAttr "%s.horizontalFilmOffset" ($pos[2]);' % camera.shape
					expression += '\nsetAttr "%s.verticalFilmOffset" ($pos[3]);' % camera.shape

					# create expression
					cmds.expression		(name = 'stabilizator_expression', string = expression)
		
					# update GUI
					cmds.button			('button_stabilizer',
										edit			= True,
										label			="deStabilize",
										backgroundColor	= (1, 0, 0),
										command			= 'fstab.stabilizer("end")')
					
				else:
					cmds.warning ('..:: CLICK IN THE PANE WITH THE CAMERA ::..')
def get_scene_texture_connections():
	conns =[]
	
	for mat in cmds.ls(mat=True):
		if cmds.nodeType(mat) == 'lambert':
			dif_conn = cmds.listConnections('%s.color' % mat)
			nrm_conn = cmds.listConnections('%s.normalCamera' % mat)
			if dif_conn:
				conns.append(dif_conn[0])
			if nrm_conn:
				for itm in cmds.listConnections(nrm_conn):
					if cmds.nodeType(itm) == 'file':
						conns.append(itm)
						break
				
		if cmds.nodeType(mat) == 'blinn' or cmds.nodeType(mat) == 'phong':
			dif_conn = cmds.listConnections('%s.color' % mat)
			nrm_conn = cmds.listConnections('%s.normalCamera' % mat)
			spc_conn = cmds.listConnections('%s.specularColor' % mat)
			if dif_conn:
				conns.append(dif_conn[0])
				
			if nrm_conn:
				#conns.append(nrm_conn[0])
				for itm in cmds.listConnections(nrm_conn):
					if cmds.nodeType(itm) == 'file':
						conns.append(itm)
						break
						
			if spc_conn:
				conns.append(spc_conn[0])
	return conns	
示例#8
0
def BindSkeletons(source, dest, method='connect'):
    '''
    From 2 given root joints search through each hierarchy for child joints, match
    them based on node name, then connect their trans/rots directly, or 
    parentConstrain them. Again cmds for speed
    '''
    sourceJoints = cmds.listRelatives(source, ad=True, f=True, type='joint')
    destJoints = cmds.listRelatives(dest, ad=True, f=True, type='joint')
 
    if cmds.nodeType(source) == 'joint':
        sourceJoints.append(source)
    if cmds.nodeType(dest) == 'joint':
        destJoints.append(dest)
        
    attrs = ['rotateX', 'rotateY', 'rotateZ', 'translateX', 'translateY', 'translateZ']   
     
    for sJnt, dJnt in MatchGivenHierarchys(sourceJoints, destJoints):
        if method == 'connect':
            for attr in attrs:
                try:
                    cmds.connectAttr('%s.%s' % (sJnt, attr), '%s.%s' % (dJnt, attr), f=True)
                except:
                    pass
        elif method == 'constrain':
            try:
                cmds.parentConstraint(sJnt, dJnt, mo=True)    
            except:
                pass
示例#9
0
 def __check_scene(self):
     #--- this method checks the scene
     #--- check if something is selected
     sel = cmds.ls(selection = True)
     if sel:
         #--- check if selection is a mesh
         transform = None
         for i in sel:
             if cmds.nodeType(i) == 'transform':
                 transform = i
         if cmds.listRelatives(transform, allDescendents = True, type = 'mesh'):
             mesh = cmds.listRelatives(transform,
                                       allDescendents = True,
                                       type = 'mesh')[0]
             if cmds.nodeType(mesh) == 'mesh':
                 #--- store the mesh
                 self.mesh = transform
                 #--- get current frame
                 self.currentFrame = cmds.currentTime(query = True)
                 #--- get timestamp
                 ts = str(time.time())
                 self.time_stamp = str(ts.split('.')[0] + ts.split('.')[1])
             else:
                 raise Exception('The selected object is not a mesh!')
         else:
             raise Exception('The selected object is not a mesh!')
     else:
         raise Exception('You have to select a mesh, dude!')
示例#10
0
def switchProxy( rfn, to="" ):
    if cmds.nodeType( rfn ) == "reference":
        pm = cmds.listConnections( rfn, type="proxyManager" )
    else:
        print "%s has not any connected proxy references." % rfn
        return None
    if pm:
        pm = pm[0]
        if to == "":
            references = cmds.listConnections( "%s.proxyList" % pm, type="reference", source=False, destination=True )
            active = cmds.listConnections( "%s.activeProxy" % pm, source=False, destination=True, plugs=True )
            if active:
                for i in range( 0, len( references )):
                    connections = cmds.listConnections( "%s.proxyMsg" % references[i], type="proxyManager", source=True, destination=False, plugs=True )
                    if connections and active[0] in connections:
                        return loadReference( references[i-1] )
                        break 
            else:
                return loadReference( references[0] )
        else:
            if cmds.objExists( to ) and cmds.nodeType( to ) == "reference":
                tm = cmds.listConnections( to, type="proxyManager" )
                if tm and pm == tm[0]:
                    return loadReference( to )
                else:
                    print "%s is not proxy reference for current reference." % to
                    return None
            else:
                print "%s is not proxy reference." % to
                return None
示例#11
0
def copyWeight( first, second ):
    
    hists = cmds.listHistory( first, pdo=1 )
    
    skinNode = None
    for hist in hists:
        
        if cmds.nodeType( hist ) == 'skinCluster':
            skinNode = hist
            
    if not skinNode: return None
    
    targetSkinNode = None
    targetHists = cmds.listHistory( second, pdo=1 )
    if targetHists:
        for hist in targetHists:
            if cmds.nodeType( hist ) == 'skinCluster':
                targetSkinNode = hist

    if not targetSkinNode:
        bindObjs = cmds.listConnections( skinNode+'.matrix', s=1, d=0, type='joint' )
        bindObjs.append( second )
        print bindObjs
        cmds.skinCluster( bindObjs, tsb=1 )
    
    cmds.copySkinWeights( first, second, noMirror=True, surfaceAssociation='closestPoint', influenceAssociation ='oneToOne' )
示例#12
0
def ucGetBasePoints():
    
    sels = cmds.ls( sl=1 )
    
    model.fnMeshList = []
    model.fnCrvList = []
    model.meshPoints = []
    model.crvPoints = []
    
    for target in sels:
        targetShapes = cmds.listRelatives( target, s=1 )
        
        for shape in targetShapes:
            if cmds.nodeType( shape ) == 'mesh':
                fnMesh = om.MFnMesh( functions.getMObject( shape ) )
                points = om.MPointArray()
                fnMesh.getPoints( points )
                model.fnMeshList.append( fnMesh )
                model.meshPoints.append( points )
            
            elif cmds.nodeType( shape ) == 'nurbsCurve':
                fnCurve = om.MFnNurbsCurve( functions.getMObject( shape ) )
                points = om.MPointArray()
                fnCurve.getCVs( points )
                model.fnCrvList.append( fnCurve )
                model.crvPoints.append( points )
def getObjMaterials():
    global remapAndLuminaceNodes
    index = 0
    shadingType = ["blinn", "phong", "RedshiftArchitectural", "aiStandard"]
    displacementShading = ["RedshiftDisplacement", "displacementShader"]
    duplicateMaterials = list()
    selObjsList = cmds.ls(sl=1, tr=1)
    if not selObjsList:
        assert "No object is selected!"
    for obj in selObjsList:
        duplicateNodes = list()
        cmds.select(obj, r=1)
        cmds.hyperShade(smn=1)
        selObjsDuplicateMaterials = cmds.duplicate(un=1)
        for item in selObjsDuplicateMaterials:
            dupliMater = cmds.rename(item, "%s_duplicate" % (item))
            duplicateNodes.append(dupliMater)
        remapAndLuminaceNodes.append(duplicateNodes[1])
        remapAndLuminaceNodes.append(duplicateNodes[2])
        remapAndLuminaceNodes.extend(duplicateNodes)
        for item in duplicateNodes:
            if cmds.nodeType(item) == "shadingEngine":
                duplicateShading = item
            if cmds.nodeType(item) in shadingType:
                duplicateMaterials.append(item)
            #     duplicateMaterials.append(item)
            #     remapAndLuminaceNodes.remove(item)
            # if cmds.nodeType(item) == displacementShading:
            #     if index >= 1: continue
            #     cmds.connectAttr('%s.displacement'%item, '%s.displacementShader'%duplicateShading, f = 1)
            #     index += 1
            # remapAndLuminaceNodes.remove(item)
        cmds.sets(obj, e=1, fe=duplicateShading)
    cmds.select(selObjsList, r=1)
    return list(set(duplicateMaterials))
def linkFileToSpecular(src, dst):
    cmds.shadingNode('remapHsv', n = '%s_remapHsc'%dst, au = 1)
    cmds.shadingNode('solidFractal', n = '%s_solidFractal'%dst, at = 1)
    cmds.shadingNode('place3dTexture', n = '%s_place3dTexture'%dst, at = 1)
    cmds.shadingNode('multiplyDivide', n = '%s_multiplyDivide'%dst, au = 1)
    cmds.shadingNode('ramp', n = '%s_ramp'%dst, at = 1)
    cmds.setAttr('%s.saturation[1].saturation_Position'%('%s_remapHsc'%dst), 1)
    cmds.setAttr('%s.saturation[1].saturation_FloatValue'%('%s_remapHsc'%dst), 0)
    cmds.setAttr('%s.value[0].value_FloatValue'%('%s_remapHsc'%dst), 0)
    cmds.setAttr('%s.value[0].value_Position'%('%s_remapHsc'%dst), 0.025)
    cmds.setAttr('%s.value[1].value_FloatValue'%('%s_remapHsc'%dst), 1)
    cmds.setAttr('%s.value[1].value_Position'%('%s_remapHsc'%dst), 0.075)
    cmds.connectAttr('%s.worldInverseMatrix[0]'%('%s_place3dTexture'%dst), '%s.placementMatrix'%('%s_solidFractal'%dst), f = 1)
    cmds.connectAttr('%s.outColor'%src, '%s.color'%('%s_remapHsc'%dst), f = 1)
    cmds.connectAttr('%s.outColor'%('%s_remapHsc'%dst), '%s.input1'%('%s_multiplyDivide'%dst), f = 1)
    cmds.connectAttr('%s.outColor'%('%s_solidFractal'%dst), '%s.input2'%('%s_multiplyDivide'%dst), f = 1)
    cmds.connectAttr('%s.output'%('%s_multiplyDivide'%dst), '%s.colorGain'%('%s_ramp'%dst), f = 1)
    if cmds.nodeType(dst) == 'RedshiftArchitectural':
        # cmds.disconnectAttr('%s.outColor'%(src), '%s.diffuse'%dst)
        cmds.connectAttr('%s.outColor'%('%s_ramp'%dst), '%s.refl_color'%dst, f = 1)
    elif cmds.nodeType(dst) == 'aiStandard':
        # cmds.disconnectAttr('%s.outColor'%(src), '%s.color'%dst)
        cmds.connectAttr('%s.outColor'%('%s_ramp'%dst), '%s.KsColor'%dst, f = 1)
        # cmds.connectAttr('%s.outColor'%('%s_ramp'%dst), '%s.color'%dst, f = 1)
    else:
        # cmds.disconnectAttr('%s.outColor'%(src), '%s.color'%dst)
        cmds.connectAttr('%s.outColor'%('%s_ramp'%dst), '%s.reflectedColor'%dst, f = 1)
        # cmds.connectAttr('%s.outColor'%('%s_ramp'%dst), '%s.color'%dst, f = 1)
    linkTopRemapNodeToAll('%s_ramp'%dst)
    getRemapAndMutilplyNodes(dst)
示例#15
0
def cacheFluidsToCTemp():
	if cmds.objExists(CONST.FOAM_FLUID_SHAPENODE) and cmds.objExists(CONST.WAKE_FLUID_SHAPENODE):
		## Get default non-cached wake and foam
		fluidsToCache = []
		for cache in [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE]:
			fluidConnection = cmds.listConnections(cache, type = 'cacheFile') or cmds.listConnections(cache, type = 'cacheBlend')
			if fluidConnection:
				if cmds.nodeType(fluidConnection[0]) == 'cacheFile' or cmds.nodeType(fluidConnection[0]) == 'cacheBlend':
					cmds.confirmDialog(title = 'CACHE FLUIDS', message = 'Cache already exist for "%s". You should cleanup your caches if you want to re-cache a newer one!' % cache, button = 'OK')
				else:
					fluidsToCache.append(cache)
			else:
				fluidsToCache.append(cache)

		## Cache em fluids at one go to save time
		if fluidsToCache:
			cachePath = _getPathFromSceneName()
			if cachePath:
				if os.path.exists(cachePath):
					_cacheWake(cachepath = cachePath, fluids = fluidsToCache)

					## Set time to min
					[cmds.currentTime( cmds.playbackOptions(q = True, min = True) ) for x in range(2)]
	else:
		cmds.confirmDialog(title = 'CACHE FLUIDS', message = 'Both "%s" and "%s" fluids don\'t exist in your scene!' % (CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE), button = 'OK')
def linkFileToSpecular(src, dst):
    cmds.shadingNode("remapHsv", n="%s_remapHsc" % dst, au=1)
    cmds.shadingNode("solidFractal", n="%s_solidFractal" % dst, at=1)
    cmds.shadingNode("place3dTexture", n="%s_place3dTexture" % dst, at=1)
    cmds.shadingNode("multiplyDivide", n="%s_multiplyDivide" % dst, au=1)
    cmds.shadingNode("ramp", n="%s_ramp" % dst, at=1)
    cmds.setAttr("%s.saturation[1].saturation_Position" % ("%s_remapHsc" % dst), 1)
    cmds.setAttr("%s.saturation[1].saturation_FloatValue" % ("%s_remapHsc" % dst), 0)
    cmds.setAttr("%s.value[0].value_FloatValue" % ("%s_remapHsc" % dst), 0)
    cmds.setAttr("%s.value[0].value_Position" % ("%s_remapHsc" % dst), 0.025)
    cmds.setAttr("%s.value[1].value_FloatValue" % ("%s_remapHsc" % dst), 1)
    cmds.setAttr("%s.value[1].value_Position" % ("%s_remapHsc" % dst), 0.075)
    cmds.connectAttr(
        "%s.worldInverseMatrix[0]" % ("%s_place3dTexture" % dst), "%s.placementMatrix" % ("%s_solidFractal" % dst), f=1
    )
    cmds.connectAttr("%s.outColor" % src, "%s.color" % ("%s_remapHsc" % dst), f=1)
    cmds.connectAttr("%s.outColor" % ("%s_remapHsc" % dst), "%s.input1" % ("%s_multiplyDivide" % dst), f=1)
    cmds.connectAttr("%s.outColor" % ("%s_solidFractal" % dst), "%s.input2" % ("%s_multiplyDivide" % dst), f=1)
    cmds.connectAttr("%s.output" % ("%s_multiplyDivide" % dst), "%s.colorGain" % ("%s_ramp" % dst), f=1)
    if cmds.nodeType(dst) == "RedshiftArchitectural":
        # cmds.disconnectAttr('%s.outColor'%(src), '%s.diffuse'%dst)
        cmds.connectAttr("%s.outColor" % ("%s_ramp" % dst), "%s.refl_color" % dst, f=1)
    elif cmds.nodeType(dst) == "aiStandard":
        # cmds.disconnectAttr('%s.outColor'%(src), '%s.color'%dst)
        cmds.connectAttr("%s.outColor" % ("%s_ramp" % dst), "%s.KsColor" % dst, f=1)
        # cmds.connectAttr('%s.outColor'%('%s_ramp'%dst), '%s.color'%dst, f = 1)
    else:
        # cmds.disconnectAttr('%s.outColor'%(src), '%s.color'%dst)
        cmds.connectAttr("%s.outColor" % ("%s_ramp" % dst), "%s.reflectedColor" % dst, f=1)
        # cmds.connectAttr('%s.outColor'%('%s_ramp'%dst), '%s.color'%dst, f = 1)
    linkTopRemapNodeToAll("%s_ramp" % dst)
示例#17
0
 def get_translation(self):
     #--- this method gets the translation values
     #--- check the checkboxes
     self.get_checkbox_info()        
     #--- get the selection
     sel = cmds.ls(selection=True)
     #--- get the proper information
     names = list()
     position = list()
     print 'TRANSLATION:'
     for i in sel:
         if cmds.nodeType(i) == 'mesh' or cmds.nodeType(i) == 'nurbsCurve' or cmds.nodeType(i) == 'nurbs':
             self.get_component_position(i)
             return
         elif cmds.nodeType(i) != 'transform':
             raise Exception('Selection has to be a transform node or a mesh!')
         pos = cmds.xform(i, query=True, translation=True, worldSpace=self.world)
         if self.list:
             if self.selection:
                 names.append(i)
             position.append(pos)
         else:
             if self.selection:
                 print i, pos
             else:
                 print pos
     if self.list:
         if self.selection:
             print names
         print position
示例#18
0
def createMaterialSelect():
       
    selNodes = cmds.ls(selection=True) # get selection
    
    mtlSelectToCreate = [] # clean out array
    
    for node in selNodes:
        if cmds.nodeType(node) == 'VRayBlendMtl': #make sure it's a vray blend mat
            mat = (cmds.listConnections('%s.base_material' % (node))[0])
            print mat, node
            if mat != None and mat not in mtlSelectToCreate:
                mtlSelectToCreate.append(mat)
            for n in range(0,9):
                mat = (cmds.listConnections('%s.coat_material_%d' % (node,n))) # go thru each coat and add if it's there
                if mat != None and mat not in mtlSelectToCreate:
                    mtlSelectToCreate.append(mat[0])
        if cmds.nodeType(node) == 'VRayMtl':
            if node not in mtlSelectToCreate:
                mtlSelectToCreate.append(node) 
                
    for curMat in mtlSelectToCreate:
        matSelName = 'mtl_%s' % (curMat) # create a reasonable name
        if not cmds.objExists(matSelName): # make sure it doesn't already exist
            renderElement = mel.eval('vrayAddRenderElement MaterialSelectElement;') # create render element
            renderElement = cmds.rename(renderElement,matSelName) # rename the old to new
            cmds.connectAttr (curMat + '.outColor', renderElement + '.vray_mtl_mtlselect') # connect up the shader to the render element
            cmds.setAttr (renderElement + '.vray_explicit_name_mtlselect', matSelName, type = 'string') # make sure the name that gets shoved in the exr is named the same
def positionReorderDoIt(*args):
	meshes = []
	sourceMeshText = cmds.textField( 'sourceMeshTextField', query=True, text=True )

	if sourceMeshText == '':
		cmds.error('source mesh textfield is empty')

	if cmds.objExists(sourceMeshText) == False:
		cmds.error('the source mesh ( '+sourceMeshText+' ) does not exist')

	if cmds.nodeType(sourceMeshText) != 'mesh':
		shapes = cmds.listRelatives( sourceMeshText, shapes=True )

		if shapes is None or len(shapes) < 1 or cmds.nodeType(shapes[0]) != 'mesh':
			cmds.error('source ( '+sourceMeshText+' ) is not a mesh')

	meshes.append( sourceMeshText )

	destinationMeshText = cmds.textField( 'destinationMeshTextField', query=True, text=True )
	
	if destinationMeshText == '':
		cmds.error('destination mesh textfield is empty')

	if cmds.objExists(destinationMeshText) == False:
		cmds.error('the destination mesh ( '+destinationMeshText+' ) does not exist')

	if cmds.nodeType(destinationMeshText) != 'mesh':
		shapes = cmds.listRelatives( destinationMeshText, shapes=True )

		if shapes is None or len(shapes) < 1 or cmds.nodeType(shapes[0]) != 'mesh':
			cmds.error('destination ( '+destinationMeshText+' ) is not a mesh')

	meshes.append( destinationMeshText )

	positionReorder( meshes=meshes )
示例#20
0
def mirrorConnect( target ):
    
    import sgBFunction_attribute
    
    if cmds.nodeType( target ) in [ 'transform', 'joint' ]:
        mirrorTarget = mirrorTransform( target )
    else:
        mirrorTarget = mirrorNode( target )
    
    srcCons = cmds.listConnections( target, s=1, d=0, p=1, c=1 )
    
    outCons = srcCons[1::2]
    inCons  = srcCons[::2]
    
    for i in range( len( outCons ) ):
        outputNode, outputAttr = outCons[i].split( '.' )
        inputAttr = inCons[i].split( '.' )[-1]
        
        if cmds.nodeType( outputNode ) in [ 'transform', 'joint' ]:
            mirrorOutputNode = mirrorTransform( outputNode )
        else:
            mirrorOutputNode = mirrorNode( outputNode )
        
        if not cmds.attributeQuery( outputAttr, node=mirrorOutputNode, ex=1 ):
            sgBFunction_attribute.copyAttribute( outputNode+'.'+outputAttr, mirrorOutputNode )
        if not cmds.attributeQuery( inputAttr, node=mirrorTarget, ex=1 ):
            sgBFunction_attribute.copyAttribute( target+'.'+inputAttr, mirrorTarget )

        if not cmds.isConnected( mirrorOutputNode+'.'+outputAttr, mirrorTarget+'.'+inputAttr ):
            cmds.connectAttr( mirrorOutputNode+'.'+outputAttr, mirrorTarget+'.'+inputAttr )
    
    return mirrorTarget
def getObjMaterials():
    global remapAndLuminaceNodes
    shadingType = ["blinn", "phong", "RedshiftArchitectural", "aiStandard"]
    displacementShading = ["RedshiftDisplacement", "displacementShader"]
    duplicateMaterials = list()
    selObjsList = cmds.ls(sl=1, tr=1)
    if not selObjsList:
        assert "No object is selected!"
    for obj in selObjsList:
        duplicateNodes = list()
        cmds.select(obj, r=1)
        cmds.hyperShade(smn=1)
        selObjsDuplicateMaterials = cmds.duplicate(un=1)
        for item in selObjsDuplicateMaterials:
            dupliMater = cmds.rename(item, "%s_duplicate" % (item))
            duplicateNodes.append(dupliMater)
        for item in duplicateNodes:
            if cmds.nodeType(item) in shadingType:
                duplicateShading = cmds.sets(r=1, nss=1, em=1, n="%s_SG" % item)
                cmds.connectAttr("%s.outColor" % item, "%s.surfaceShader" % duplicateShading, f=1)
                duplicateMaterials.append(item)
            elif cmds.nodeType(item) == "RedshiftDisplacement":
                conInfo = cmds.connectionInfo("%s.displacementShader" % duplicateShading, sfd=1)
                if not conInfo:
                    cmds.connectAttr("%s.out" % item, "%s.displacementShader" % duplicateShading, f=1)
            elif cmds.nodeType(item) == "displacementShader":
                conInfo = cmds.connectionInfo("%s.displacementShader" % duplicateShading, sfd=1)
                if not conInfo:
                    cmds.connectAttr("%s.displacement" % item, "%s.displacementShader" % duplicateShading, f=1)
        cmds.sets(obj, e=1, fe=duplicateShading)
    cmds.select(selObjsList, r=1)
    return list(set(duplicateMaterials))
示例#22
0
 def on_actionLoadSourceControl_triggered(self, clicked=None):
     if clicked == None:return
     selectOBJ = mc.ls(sl=True)
     
     if len(selectOBJ) == 0:return
     self.sourceControlFLD.setText(selectOBJ[0])
     
     KeyableAttr = mc.listAttr(selectOBJ[0], k=True)
     
     del self.sourceAtrLst[:]
     del self.targentAtrLst[:]
     # loop  Attributes..
     for Attr in KeyableAttr:
         SDKeys = mc.connectionInfo('%s.%s'%(selectOBJ[0], Attr), dfs=True)
         # loop driven Attributes..
         for key in SDKeys:
             if mc.nodeType(key) == 'unitConversion':
                 keyNode = mc.connectionInfo('%s.output'%key.split('.')[0], dfs=True)[0].split('.')[0]
             
             elif mc.nodeType(key) not in ('animCurve','animCurveTA', 'animCurveTL', 'animCurveTT','animCurveTU','animCurveUA','animCurveUL','animCurveUT','animCurveUU'):
                 continue
             else:
                 keyNode = key.split('.')[0]
             DriverValues     =  mc.keyframe(keyNode, q=True, fc=True)
             DrivenValues     =  mc.keyframe(keyNode, q=True, vc=True)
             DriverAttribute =  mc.connectionInfo('%s.output'%keyNode, dfs=True)[0]
             
             # if more than one Drivers, from add  node get the attribute..
             if  DriverAttribute.endswith(']'):
                 DriverAttribute = mc.connectionInfo('%s.output'%(DriverAttribute.split('.')[0]), dfs=True)[0]
              
             self.sourceAtrLst.append(['%s.%s'%(selectOBJ[0], Attr), DriverAttribute, DriverValues, DrivenValues])
     
     self.on_actionInputSearchReplace_triggered()
def stabilizer ():
	global _camera_
	_point = cmds.ls (selection = True)
	
	if cmds.objExists ('stabilizator_expression') == False and len(_point) > 0:
		_camera_	= Camera()
		_point		= _point[0]

		if (cmds.nodeType (_point) == 'mesh' or cmds.nodeType (_point) == 'transform') and _camera_.transform != 'empty':
			_expression	=	r'''
$pos=`python "fmmu.get_normalized_screen_position(\"'''	+	_point	+	r'''\")"`;
setAttr "'''	+	_camera_.shape	+	r'''.horizontalFilmOffset" $pos[2];
setAttr "'''	+	_camera_.shape	+	r'''.verticalFilmOffset" $pos[3];'''

			print "=================================="
			print _expression
			cmds.expression		(name = 'stabilizator_expression', string = _expression)
			cmds.frameLayout	('adjustCam_frml', edit = True, visible = True)
			cmds.symbolButton	('button_stabilizer', edit = True, image = 'ford_matchMoveUtilities__deStabilize.xpm', annotation = 'deStabilizer')
			cmds.floatField		('field_overscan', edit = True, value = _camera_.overscan)

	else:
		if cmds.objExists ('stabilizator_expression') == True:
			cmds.delete ('stabilizator_expression')
		
		cmds.symbolButton	('button_stabilizer', edit = True, image = 'ford_matchMoveUtilities__stabilize.xpm', annotation = 'deStabilizer')
		cmds.frameLayout	('adjustCam_frml', edit = True, collapse = True, visible = False)
		
		try:
			_camera_.reset_camera()
		except:
			pass
示例#24
0
 def check_name_match(self, parents=None, targets=None, topology=None):
     target_events_list = {}
     for parent in parents:
         parent_name = parent.split('|')[-1].split(':')[-1]
         copy_event_parent = False
         target_match = []
         for target in targets:
             copy_event_target = False
             target_name = target.split('|')[-1].split(':')[-1]
             if parent_name == target_name:
                 if cmds.nodeType(parent) == cmds.nodeType(target) == 'mesh':
                     tp = [parent]
                     tt = [target]
                     topocheck = self.check_topology_match(parents=tp, targets=tt, globout=False)
                     if parent in topocheck and target in topocheck[parent]:
                         target_match.append(target)
                         self.found_matches[parent] = target_match
                         copy_event_target = True
                 else:
                     target_match.append(target)
                     self.found_matches[parent] = target_match
                     copy_event_target = True
             if not copy_event_target and target_events_list.get(target) != True:
                 target_events_list[target] = False
             if copy_event_target:
                 target_events_list[target] = True
                 copy_event_parent = True
         if not copy_event_parent:
             self.non_found_parent.append(parent)
     for target in target_events_list:
         if not target_events_list[target]:
             self.non_found_target.append(target)
     self.non_found_target = list(set(self.non_found_target))
     self.non_found_parent = list(set(self.non_found_parent))
     return self.found_matches, self.non_found_parent, self.non_found_target
示例#25
0
    def nameChangedCB(self, node, prevName, client):
        ''' Callback when a node is renamed '''

        if prevName == "" or not prevName or prevName.startswith("_"):
            return
        handle = MObjectHandle( node )
        if not handle.isValid():
            return
        mobject = handle.object()

        nodeFn = MFnDependencyNode ( mobject )
        if nodeFn.hasUniqueName():
            nodeName = nodeFn.name()
            if cmds.getClassification(cmds.nodeType(nodeName), satisfies="shader"):

                if cmds.nodeType(nodeName) == "displacementShader":
                    items = self.displacementList.findItems(prevName, QtCore.Qt.MatchExactly)
                    for item in items:
                        item.setText(nodeName)

                    # renaming shaders in caches
                    for cache in self.ABCViewerNode.values():
                        cache.renameDisplacement(prevName, nodeName)
                    self.checkShaders()
                else:
                    items = self.shadersList.findItems(prevName, QtCore.Qt.MatchExactly)
                    for item in items:
                        item.setText(nodeName)

            if cmds.nodeType(nodeName) == "shadingEngine":
                    # renaming shaders in caches
                    for cache in self.ABCViewerNode.values():
                        cache.renameShader(prevName, nodeName)

                    self.checkShaders()
示例#26
0
def setCharacterInput(_HIK, _HIK_source, **kwargs):
    if not ( cmds.nodeType(_HIK) == 'HIKCharacterNode' and cmds.nodeType(_HIK_source) == 'HIKCharacterNode' ):
        print u'HIKCharacterNode를 입력하세요.'
        return

    # sourceHide
    _sourceHide = False
    if kwargs.get('sourceHide') or kwargs.get('sh'):
        _input = ''

        # 해당 키워드에 해당하는 키값을 받아오고
        if   kwargs.get('sourceHide'): 
            _input = kwargs.get('sourceHide')
        elif kwargs.get('sh'): 
            _input = kwargs.get('sh')

        # 맞으면.. 아래 실행
        _sourceHide = _input

    # 연결
    mel.eval( 'mayaHIKsetCharacterInput( "%s", "%s" );'%(_HIK, _HIK_source) )
    mel.eval( '$gHIKCurrentCharacter = "%s";'%_HIK)
    mel.eval( 'hikUpdateCurrentCharacterFromScene();')

    if _sourceHide:
        # 소스 루트 알아옴.
        _root = getRootParent(_HIK_source)
        cmds.setAttr(_root+'.v',0)
示例#27
0
def	splitJoint	():
	_newBoneNum	= cmds.intSlider	('boneNum',	query	= 1,	value	= 1)
	_bone		= cmds.ls	(selection	= 1,	long	= 1)
	_childJoint	= cmds.listRelatives	(children	= 1)

	if (len (_bone)	> 0) and (type(_childJoint) is not NoneType) \
	and (cmds.nodeType(_bone[0]) == 'joint') and (cmds.nodeType(_childJoint) == 'joint'):
		
		_childTranslateX	=	cmds.getAttr	(	_childJoint[0]	+	'.translateX'	)
		_childTranslateY	=	cmds.getAttr	(	_childJoint[0]	+	'.translateY'	)
		_childTranslateZ	=	cmds.getAttr	(	_childJoint[0]	+	'.translateZ'	)

		_newX				=	_childTranslateX	/	(	_newBoneNum	+	1.0	)
		_newY				=	_childTranslateY	/	(	_newBoneNum	+	1.0	)
		_newZ				=	_childTranslateZ	/	(	_newBoneNum	+	1.0	)

		for	_k	in	range	(	_newBoneNum):
			_bone	=	cmds.insertJoint	(	_bone	)
			cmds.toggle	(localAxis		=1)
			cmds.xform	(_bone	+	'.scalePivot',	_bone	+	'.rotatePivot',
						relative	=	1,	objectSpace	=	1,	translation	=	(	_newX,	_newY,	_newZ	)	)

		for	_k	in	range	(	_newBoneNum	):	cmds.pickWalk	(	direction	=	'up'	)
	
	else:	raiseWarning	(	'select a bone! You can do it!'	)
示例#28
0
 def deleteLocalControler(self, target ):
     
     if not cmds.objExists( target ): return None
     
     transNode = cmds.listConnections( target, type='retargetTransNode' )
     orientNode = cmds.listConnections( target, type='retargetOrientNode' )
     
     if cmds.nodeType( target ) == 'editMatrixByCurve' :
         cmds.delete( target )
     else:
         targetP = fnc.getP( target )
         targetPShape = cmds.listRelatives( targetP, s=1 )[0]
         
         if cmds.nodeType( targetPShape ) == 'retargetLocator':
             cmds.delete( targetP )
         else:
             cmds.delete( target )
     
     if transNode:  
         length = fnc.getLastIndex( transNode[0]+'.localData' )+1
         for i in range( length ):
             if not cmds.listConnections( transNode[0]+'.localData[%d].localMatrix' % i ):
                 mel.eval( 'removeMultiInstance %s[%d]' %( transNode[0]+'.localData', i ) )
     if orientNode :
         length = fnc.getLastIndex( orientNode[0]+'.localData' )+1
         for i in range( length ):
             if not cmds.listConnections( orientNode[0]+'.localData[%d].localMatrix' % i ):
                 mel.eval( 'removeMultiInstance %s[%d]' %( orientNode[0]+'.localData', i ) )
def findLambert(each):
    """
    This will find a lambert to 4 levels deep of connects for a suuplied node. Usually a File node for us
    """
    getConns = findConnections(each)
    if getConns:##make sure it's a valid list of connections to look through
        for eachConn in getConns:
            #print 'Looking For Lambert: %s \tnodeType: %s' % (eachConn, cmds.nodeType(eachConn))
            if cmds.nodeType(eachConn) == 'lambert':
                return eachConn
            else:            
                getConn2 = findConnections(eachConn)
                if getConn2:##make sure it's a valid list of connections to look through
                    for eachConn2 in getConn2:
                        #print 'Looking For Lambert LvL2: %s \tnodeType: %s' % (eachConn2, cmds.nodeType(getConn2))
                        if cmds.nodeType(eachConn2) == 'lambert':
                            return eachConn2
                        else:
                            getConn3 = findConnections(eachConn2)
                            if getConn3:##make sure it's a valid list of connections to look through
                                for eachConn3 in getConn3:
                                    #print 'Looking For Lambert LvL3: %s \tnodeType: %s' % (eachConn3, cmds.nodeType(eachConn3))
                                    if cmds.nodeType(eachConn3) == 'lambert':
                                        return eachConn3
                                    else:
                                        getConn4 = findConnections(eachConn3)                                        
                                        if getConn4:##make sure it's a valid list of connections to look through
                                            for eachConn4 in getConn4:
                                                #print 'Looking For Lambert LvL4: %s \tnodeType: %s' % (eachConn4, cmds.nodeType(eachConn4))
                                                if cmds.nodeType(eachConn4) == 'lambert':
                                                    return eachConn4
                                                else:
                                                    pass
    else:
        return False
示例#30
0
def deleteExpression(con='', attr=''):
    '''
    #
    '''
    # find exp
    cnn = cmds.listConnections(con + '.' + attr, s=True, d=False)
    if cnn:
        if cmds.nodeType(cnn[0]) == 'unitConversion':
            cnn_uc = cmds.listConnections(cnn, s=True, d=False, type='expression')
            if cnn_uc:
                if cmds.nodeType(cnn_uc[0]) == 'expression':
                    exp = cnn_uc[0]
        elif cmds.nodeType(cnn[0]) == 'expression':
            exp = cnn[0]
        # delete exp
        if exp:
            st1 = cmds.expression(exp, q=True, s=True)
            st2 = 'frame'
            if st2 in st1:
                cmds.delete(exp)
                print 'deleted___  ', con, '  ___  ', exp
            else:
                print '    nope     '
        else:
            print 'no expression  ', attr
示例#31
0
def create_wrap(driver,
                driven,
                weightThreshold=0,
                limitWrapInfluence=0,
                maxDistance=1,
                wrapInflType=2,
                exclusiveBind=1,
                autoWeightThreshold=1,
                renderInfl=0,
                falloffMode="surface"):

    cmds.optionVar(fv=["weightThreshold", weightThreshold])
    cmds.optionVar(iv=["limitWrapInfluence", limitWrapInfluence])
    cmds.optionVar(iv=["maxDistance", maxDistance])
    cmds.optionVar(iv=["wrapInflType", wrapInflType])
    cmds.optionVar(iv=["exclusiveBind", exclusiveBind])
    cmds.optionVar(iv=["autoWeightThreshold", autoWeightThreshold])
    cmds.optionVar(iv=["renderInfl", renderInfl])
    print("falloffMode", falloffMode)
    cmds.optionVar(sv=["falloffMode", falloffMode])

    cmds.select(cl=True)
    cmds.select(driven)
    cmds.select(driver, add=True)

    mel.eval("CreateWrap;")

    if isinstance(driven, list):
        driven_node = driven[0]
    else:
        driven_node = driven
    driven_type = cmds.nodeType(driven_node)

    if driven_type == "transform":
        driven_node = cmds.listRelatives(driven_node, shapes=True)[0]
    return cmds.listConnections(driven_node, type="wrap")[0]
示例#32
0
	def saveSelectedForm( self ):				
		selection = mc.ls(sl=True)
		
		if ( len(selection) == 1 ) and ( mc.nodeType( selection[0] ) == 'nurbsCurve' ):
			pass
		else:
			mc.error('You must select one curveShape')
			
		result = mc.promptDialog( title= 'Save Curve Form ', message='Enter name of the form:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel' )	
	
		if( result == 'OK' ):
			formName = mc.promptDialog(query=True, text=True)
		else:
			return 0
	
		curveShapeName = selection[0]				
		curveCoords    = getCurveCoords( curveShapeName )
		curveDegree    = mc.getAttr( curveShapeName +'.degree' )	
		
		self.saveForm( formName , curveCoords , curveDegree )
		
		print('=== Curve Form Saved ===')
	
		return 1
示例#33
0
def change_node_path(nodes, src, dst):
    """ change file nodes path

    """
    _file_nodes = nodes
    #if _file_nodes:
    for _file_node_attr in _file_nodes:
        _file_node = _file_node_attr.split(".")[0]
        _type = cmds.nodeType(_file_node)
        _ori_file_texture_path = _get_file_full_name(_file_node_attr)
        _file_texture_path = _ori_file_texture_path

        # _extend_file = _file_texture_path.split(src)[-1]
        _extend_file = os.path.basename(_file_texture_path)
        while _extend_file.startswith("/"):
            _extend_file = _extend_file[1:]
        _new_file_text_path = "%s/%s"%( dst, _extend_file )
        # 锁定节点色彩空间,防止替换贴图时色彩空间设置丢失
        # print(_new_file_text_path)
        if _type == "file" and not cmds.getAttr("{}.ignoreColorSpaceFileRules".format(_file_node)):
            cmds.setAttr("{}.ignoreColorSpaceFileRules".format(_file_node), 1)
        print("{} change node texture path start".format(_file_node_attr))
        while True:
            cmds.setAttr(_file_node_attr, _new_file_text_path, type = 'string')
            print("original convert_path {}".format(convert_path(_get_file_full_name(_file_node_attr))))
            print("new convert_path {}".format(convert_path(_new_file_text_path)))
            if convert_path(_get_file_full_name(_file_node_attr)) == convert_path(_new_file_text_path):
                break
        print("change node texture path over")
        # 取消色彩空间锁定(Raw除外)
        if _type == "file":
            _colorSpace = cmds.getAttr('%s.colorSpace'%_file_node)
            if _colorSpace == 'Raw':
                cmds.setAttr("{}.ignoreColorSpaceFileRules".format(_file_node), 1)
            else:
                cmds.setAttr("{}.ignoreColorSpaceFileRules".format(_file_node), 0)
示例#34
0
 def buttonFn(self):
     
     transform = cmds.ls(sl = True)
     
     if not transform == []:
     
         shape = cmds.listRelatives(transform[0],type = 'shape')[0]
         nodeType = cmds.nodeType(shape)
         
         deformerName = ''
         
         if nodeType == 'clusterHandle':
             
             connection = cmds.connectionInfo('%s.worldMatrix[0]'%transform[0], dfs = True)[0]
             deformerName = connection.split('.')[0]
             
         elif nodeType == 'nurbsCurve':
 
             connection = cmds.connectionInfo('%s.worldSpace[0]'%shape, dfs = True)[0]
             deformerName = connection.split('.')[0]
             
         if not deformerName == '':
             
             self.field.setText(deformerName)
示例#35
0
def getSpecifieTypeChildrens(_father, _exludedTypes):

    childrensNoShape = []

    childrens = mc.listRelatives(_father, c=True)

    #wrongTypes = { 'nurbsCurve' , 'mesh' , 'nurbsSurface' }

    for children in childrens:

        type = mc.nodeType(children)

        passChildren = 0

        for exludedType in _exludedTypes:
            if (type == exludedType):
                passChildren = 1

        if (passChildren == 1):
            continue

        childrensNoShape.append(children)

    return childrensNoShape
 def Add_Loc_Pick_Fun(self):
     if len(cmds.ls(sl=True)) > 0 :
         Selection = cmds.ls(sl=True,l=1)[0] 
         SelectionShape = cmds.listRelatives(Selection)[0]
         SelectionType = cmds.nodeType( SelectionShape )
         if SelectionType == "locator":
             self.Add_Loc_LE.setText(Selection)
             try :
                 self.Add_Loc_Get.clicked.disconnect()
             except:
                 pass
             self.Add_Loc_Get.clicked.connect(partial(self.Select_OBJ_Fun,Selection))
         else:
             cmds.warning(u"请选择Locator进行获取")
             cmds.headsUpMessage(u"请选择Locator进行获取")
     else :
         self.Add_Loc_LE.setText("")
     
     if self.Add_Loc_LE.text() != "":
         self.Add_Loc_Label.setVisible(False)
         self.Add_Loc_Get.setVisible(True)
     else:
         self.Add_Loc_Label.setVisible(True)
         self.Add_Loc_Get.setVisible(False)
示例#37
0
    def on_btn_blendShape_clicked(self, clicked=None):
        if clicked == None: return

        sel = mc.ls(sl=True)
        if len(sel) < 1:
            return

        if not mc.nodeType(sel[0]) == 'blendShape':
            return

        self.btn_blendShape.setText(sel[0])
        #--------------------------------
        self.__blendShape = sel[0]
        self.__AttributeDT = mayaTool.getBlendShapeInfo(sel[0])
        self.__AttributeDT2 = dict(
            zip(self.__AttributeDT.values(), self.__AttributeDT.keys()))
        self.__IGTAttributeDT = mayaTool.getBlendShapeInputGeomTarget(sel[0])
        mesh = mc.blendShape(str(self.btn_blendShape.text()), q=True, g=True)
        self.__baseModel = mc.listRelatives(mesh, p=True, path=True)[0]
        #--------------------------------
        self.__AttributeModel.clear()

        for i, attr in enumerate(mayaTool.getBlendShapeAttributes(sel[0])):
            self.__AttributeModel.insertRow(i, attr)
示例#38
0
def get_object_primary_visibility(node):
    """

    :param node: the name of a transform node as a string
    :return: a bool for the node primary visibility value
    """

    override = "primaryVisibility"

    if cmds.nodeType(node) == "mesh":
        shape_node = node
    else:
        shape_node = get_object_shape_node(node)

    if shape_node is False:
        return False

    if not cmds.attributeQuery(override, node=shape_node, exists=True):
        return False

    if cmds.getAttr("%s.%s" % (shape_node, override)) is False:
        return False

    object_sets = cmds.listSets(object=node) or False

    if not object_sets:
        return True

    for object_set in object_sets:
        if not cmds.attributeQuery(override, node=object_set, exists=True):
            continue

        if cmds.getAttr("%s.%s" % (object_set, override)) is False:
            return False

    return True
示例#39
0
def isMesh(mesh):
    """Check if the specified object is a polygon mesh or transform parent of a mesh

    Args:
        mesh: Object to query
    Returns:
        True/False
    """
    # Check Object Exists
    if not cmds.objExists(mesh): return False

    # Check Shape
    if 'transform' in cmds.nodeType(mesh, i=True):
        meshShape = cmds.ls(cmds.listRelatives(mesh, s=True, ni=True, pa=True)
                            or [],
                            type='mesh')
        if not meshShape: return False
        mesh = meshShape[0]

    # Check Mesh
    if cmds.objectType(mesh) != 'mesh': return False

    # Return Result
    return True
示例#40
0
def getIndicesFromSelected():

    sels = cmds.ls(cmds.polyListComponentConversion(cmds.ls(sl=1), toVertex=1),
                   fl=1)

    strIndices = ''
    targetMesh = ''
    for sel in sels:
        mesh, vtx = sel.split('.')
        strIndex = sel.split('[')[-1].replace(']', '')
        strIndices += strIndex + ","

        if cmds.nodeType(mesh) == 'transform':
            shapes = cmds.listRelatives(mesh, s=1)
            if not shapes: return None
            mesh = shapes[0]

        if not targetMesh:
            targetMesh = mesh
        else:
            if mesh != targetMesh:
                return None

    return targetMesh, strIndices[:-1]
示例#41
0
    def Add_Crv_Pick_Fun(self):
        if len(cmds.ls(sl=True)) > 0:
            Selection = cmds.ls(sl=True, l=1)[0]
            SelectionShape = cmds.listRelatives(Selection)[0]
            SelectionType = cmds.nodeType(SelectionShape)
            # if SelectionType == "nurbsCurve":
            #     self.Add_Crv_LE.setText(Selection)
            #     try :
            #         self.Add_Crv_Get.clicked.disconnect()
            #     except:
            #         pass
            #     self.Add_Crv_Get.clicked.connect(partial(self.Select_OBJ_Fun,cmds.ls(Selection))
            # else:
            #     cmds.warning(u"请选择NurbsCurve进行获取")
            #     cmds.headsUpMessage(u"请选择NurbsCurve进行获取")
        else:
            self.Add_Crv_LE.setText("")

        if self.Add_Crv_LE.text() != "":
            self.Add_Crv_Label.setVisible(False)
            self.Add_Crv_Get.setVisible(True)
        else:
            self.Add_Crv_Label.setVisible(True)
            self.Add_Crv_Get.setVisible(False)
示例#42
0
def rename(mObj, newName, side=None, startNum=1, skipSuff=False):
    """ Rename object with suffix to avoid conflicts.
        [Args]:
        mObj (mObj) - The mObj for the node to rename
        newName (string) - The new name for the node
        startNum (int) - The number to start on
        [Returns]:
        r (string) - renamed object name
    """
    if side:
        newName = '{}_{}'.format(side, newName)
    lN, sN = apiFn.getPath(mObj, returnString=True)
    try:
        cmds.rename(lN, 'TMPNAME_OOGIEOOGIE_POOP')
    except:
        return False
    lN, sN = apiFn.getPath(mObj, returnString=True)
    suffix = getSuffixForObjType(lN)
    if cmds.nodeType(lN) == 'aiImage':
        fileName = cmds.getAttr('{}.filename'.format(lN))
        fileName = fileName.rsplit('/', 1)[-1]
        if not newName[-1] == '_':
            newName += '_'
        newName = '{}{}'.format(newName, fileName.rsplit('.')[0])
    if newName.endswith(suffix) or skipSuff:
        nameNoDigits = newName
        while nameNoDigits[-1].isdigit():
            nameNoDigits = nameNoDigits[:-1]
        if '_{}'.format(newName.rsplit(
                '_', 1)[-1]) in suffixDictionary.suffix.values():
            newName = newName.rsplit('_', 1)[0]
        else:
            suffix = ''
    newName = hashToNumber(newName, suffix, startNum)
    r = cmds.rename(lN, newName)
    return r
示例#43
0
    def Add_Crv_Pick_Fun(self):
        if len(cmds.ls(sl=True)) > 0:
            Selection = cmds.ls(sl=True,l=1)[0] 
            SelectionShape = cmds.listRelatives(Selection,pa=1)[0]
            SelectionType = cmds.nodeType( SelectionShape )
            if SelectionType == "nurbsCurve":
                self.Add_Crv_LE.setText(Selection)
                try :
                    self.Add_Crv_Get.clicked.disconnect()
                except:
                    pass
                self.Add_Crv_Get.clicked.connect(partial(self.Select_OBJ_Fun,Selection))

                # Note 自动识别MotionPath
                try:
                    MotionPath = cmds.listConnections(SelectionShape)[0]
                    cmds.select(MotionPath)
                    self.Add_Motion_Path_Pick_Fun()
                except:
                    

            else:
                cmds.warning(u"请选择NurbsCurve进行获取")
                cmds.headsUpMessage(u"请选择NurbsCurve进行获取")
        else :
            self.Add_Crv_LE.setText("")
        
        if self.Add_Crv_LE.text() != "":
            self.Current_Item.Attr["Add_Crv_LE"] = self.Add_Crv_LE.text()
            self.Add_Crv_Label.setVisible(False)
            self.Add_Crv_Get.setVisible(True)
        else:
            self.Add_Crv_Label.setVisible(True)
            self.Add_Crv_Get.setVisible(False)

        self.MainWindow.Save_Json_Fun()
示例#44
0
def transfereAnim(objSource, destination):
    '''
	this proc connect the anim node of the source to the destination. This is not a copy of none!
	'''
    # get information

    upStreamNodes = mc.listConnections(objSource, s=True, d=False)

    animCurveNodes = []
    attrToConnect = []

    for node in upStreamNodes:
        if ('animCurve' in mc.nodeType(node)):
            animCurveNodes.append(node)

            plugDest = mc.listConnections(node, d=True, s=False, p=True)
            attrDest = plugDest[0].split('.')[1]
            attrToConnect.append(attrDest)

    # connect to dest

    for i in range(0, len(animCurveNodes)):
        mc.connectAttr((animCurveNodes[i] + '.output'),
                       (destination + '.' + attrToConnect[i]))
示例#45
0
    def loadBaseMesh(self, *args):

        sels = cmds.ls(sl=1)

        if not sels: cmds.error("Select mesh")

        selShapes = cmds.listRelatives(sels[-1], s=1)

        if not selShapes: cmds.error("Select mesh")

        meshShape = ''

        for shape in selShapes:
            if not cmds.getAttr(shape + '.io'):
                if cmds.nodeType(shape) == 'mesh':
                    meshShape = shape
                    break

        if not meshShape:
            cmds.error("Selected Object has no mesh")

        cmds.textField(self._baseMesh, e=1, tx=meshShape)

        self.saveData()
示例#46
0
def cntjoint(axis='x'):

    radius = 1.0
    dirX = dirY = dirZ = centerX = centerY = centerZ = 0
    if axis == "x":
        dirZ = 1
    if axis == "y":
        dirZ = 1
    if axis == "z":
        dirX = 1

    sel = mc.ls(sl=1)

    if len(sel) == 0 and mc.nodeType(sel[0]) != 'joint':
        print 'Select a joint before creating the control'

    rel = mc.listRelatives(sel[0], c=1, type='joint')

    if rel:
        radius = mc.getAttr((str(rel[0]) + '.t' + axis)) / 2.0

    if axis == 'x':
        centerX = radius
    if axis == 'y':
        centerY = radius
    if axis == 'z':
        centerZ = radius

    cnt = mc.circle(n=sel[0].split('__')[0] + '__CNT',
                    c=[centerX, centerY, centerZ],
                    nr=[dirX, dirY, dirZ],
                    r=radius)

    rel = mc.listRelatives(cnt[0], c=1, s=1)
    mc.parent(rel[0], sel[0], s=1, r=1)
    mc.delete(cnt[0])
def checkForPlusMinusAverage(switchNode, switchAtt):
    """A function to loop through the output connections and check for a plusMinusAverage Node. Currently this script will return only the first found PMA if more than one is connected"""
    switchPMA = None
    switchCon = cmds.listConnections(switchNode + "." + switchAtt,
                                     destination=True)
    switchPMAList = []

    if switchCon != None:  # listConnections returns "None" if there are no connection so we have to play it safe and check
        for con in switchCon:
            if cmds.nodeType(con) == "plusMinusAverage":
                if len(
                        con.split("pma")
                ) > 1:  #If this name splits then it is probably one of our generated plusMinusAverage Nodes
                    if len(
                            con.split("switch")
                    ) > 1:  # If this name splits too then it is almost definitely one of our generated plusMinusAverage Nodes
                        switchPMAList.append(con)
    if len(switchPMAList) >= 1:
        switchPMA = switchPMAList[0]
        if len(switchPMAList) > 1:
            cmds.warning(
                "More than one \"plusMinusAverage\" has been found, connecting to the first one found in the destination connection list"
            )
    return switchPMA
示例#48
0
文件: __init__.py 项目: octvision/oct
def delSmoothNode():
    obj = checkSel()
    allNode = []
    del allNode[:]

    if obj == None:
        allNode = mc.ls(type='polySmoothFace')
    else:
        for eachShape in obj:
            try:
                smoothNode = mc.listConnections(eachShape + '.inMesh',d=True)
            except RuntimeError:
                om.MGlobal.displayWarning(u'%s节点没有inMesh属性,跳过操作...\n' % eachShape)
            else:
                if mc.nodeType(smoothNode[0]) == 'polySmoothFace':
                    allNode.append(smoothNode[0])

    if len(allNode) > 0:
        mc.delete(allNode)

    _msg1 = u'一共删除了' + str(len(allNode)) + u'个Poly Smooth节点'
    _msg2 = u''
    mc.text('msg1',e=True,l=_msg1)
    mc.text('msg2',e=True,l=_msg2)
示例#49
0
def get_joint_data(node):
    """Get the serializable data of a node.

    :param node: Joint or transform name.
    :return: Data dictionary.
    """
    node_type = cmds.nodeType(node)
    shapes = cmds.listRelatives(node, children=True, shapes=True)
    if node_type not in ["joint", "transform"] or (shapes and node_type == "transform"):
        # Skip nodes that are not joints or transforms or if there are shapes below.
        return None

    parent = cmds.listRelatives(node, parent=True)
    parent = parent[0] if parent else None
    joint_data = {"nodeType": node_type, "name": node, "parent": parent}
    for attr in ATTRIBUTES:
        attribute = "{}.{}".format(node, attr)
        if not cmds.objExists(attribute):
            continue
        value = cmds.getAttr(attribute)
        if isinstance(value, list):
            value = list(value[0])
        joint_data[attr] = value
    return joint_data
示例#50
0
def edo_renameBlendShapeMeshByFrameInbetween(frameName):
    #frameName=ctrlName+'_up'
    if not cmds.objExists('GRP_wrongNameBlendShapes'):
        cmds.createNode('transform', n='GRP_wrongNameBlendShapes')
    childs = cmds.listRelatives(frameName, s=0, c=1, pa=1, type='transform')
    if childs == None:
        return False
    newnames = []
    for c in childs:
        #c=childs[0]
        if c.split('_')[-1] == 'connectCurve':
            print 'pass connectCurve'
            continue
        if cmds.nodeType(c) == 'transform':
            tc = c.split('|')[-1]
            objname = tc.split('__')[1]
            if not cmds.objExists(objname + '_'):
                cmds.parent(c, 'GRP_wrongNameBlendShapes')
                continue
            newname = edo_removeLastStr(c, '__') + frameName
            nn = newname.split('|')[len(newname.split('|')) - 1]
            newname = cmds.rename(c, nn)
            newnames.append(newname)
    return newnames
示例#51
0
    def utils_dictionaryToMayaObjInfo(self, obj, dictionary):
        #INIT
        dictValues = {}
        if not (mc.objExists(obj)) and not (mc.nodeType(obj) == 'transform'):
            return 0
        #DELETE
        objAttrs = mc.listAttr(obj)

        if (mc.objExists(obj + '.' + self.utilsClasseInfoAttr)):
            mc.deleteAttr(obj + '.' + self.utilsClasseInfoAttr)

        #WRITE
        dictKeys = dictionary.keys()
        dictStr = '{'
        for i in range(0, len(dictKeys)):

            value = dictionary[dictKeys[i]]

            if (type(value) == types.InstanceType):
                value = str(value)
            if (type(value) == types.StringType) or (type(value)
                                                     == types.UnicodeType):
                value = ('\'' + value + '\'')

            dictStr += '\'' + dictKeys[i] + '\':' + str(value)
            if not (len(dictKeys) - 1 <= i):
                dictStr += ','

        dictStr += '}'

        mc.addAttr(obj, longName=self.utilsClasseInfoAttr, dataType='string')
        mc.setAttr(obj + '.' + self.utilsClasseInfoAttr,
                   dictStr,
                   type='string')

        return 1
示例#52
0
def getDefaultValue(node):
    
    type = cmds.nodeType(node)
    
    if "animCurve" in type: 
        target  = getTarget("", [node], "")        
        object  = target[0][0]
        attr    = target[1][0]
    else:
        object, attr = node.split(".")
    
    if not object: return 0
    
    isScale = isAnimCurveScale(node)
    if isScale: 
        value = 1
        return value
    
    
    value               = cmds.attributeQuery(attr, node=object, listDefault=True)
    if len(value) > 0:  value = value[0]
    else:               value = 0
        
    return value
    def import_particles(self):
        # load houdini assets
        asset_name = os.path.split(self.asset_path)[-1].split('.')[0]
        asset = cmds.houdiniAsset(loadAsset=[self.asset_path, "Object/{}".format(asset_name)])

        # create shader
        surface_name = '{}_particles'.format(asset)
        # create surface shader
        surface_name = core.createArnoldNode('aiStandardSurface', name=surface_name)
        # assign shader
        cmds.sets(asset, edit=True, forceElement='{}SG'.format(surface_name))

        # particle color
        if self.import_color:
            color_name = '{}_rgbPP'.format(surface_name)
            # import particle color
            color_name = core.createArnoldNode('aiUserDataColor', name=color_name)
            cmds.setAttr('{}.colorAttrName'.format(color_name), 'rgbPP', type='string')
            if self.color_channel == 'baseColor':
                cmds.connectAttr('{}.outColor'.format(color_name), '{}.baseColor'.format(surface_name))
            elif self.color_channel == 'emitColor':
                cmds.connectAttr('{}.outColor'.format(color_name), '{}.emissionColor'.format(surface_name))
                cmds.setAttr('{}.emission'.format(surface_name), 1)

        # particle opacity
        if self.import_opacity:
            opacity_name = '{}_opacityPP'.format(surface_name)
            # disable opaque
            children = cmds.listRelatives(asset, allDescendents=True)
            for child in children:
                if cmds.nodeType(child) == 'nParticle':
                    cmds.setAttr('{}.aiOpaque'.format(child), 0)
            # import opacity
            opacity_name = core.createArnoldNode('aiUserDataFloat', name=opacity_name)
            cmds.setAttr('{}.attribute'.format(opacity_name), 'opacityPP', type='string')
            cmds.connectAttr('{}.outTransparency'.format(opacity_name), '{}.opacity'.format(surface_name))
示例#54
0
    def buildRigPart(self, *args):
        # Find the layouts namespace
        sel = cmds.ls(sl=True)
        selcontainer = cmds.container(q=True, fc=sel[0])
        if cmds.nodeType(sel[0]) == 'dagContainer':
            selcontainer = sel[0]
        lytnamespace = selcontainer.partition(':')[0]

        # Delete history on the surface
        cmds.delete(lytnamespace + ':FACE_Surface', ch=True)
        cmds.setAttr(lytnamespace + ':FACE_SurfaceShape.overrideEnabled', 0)

        # Remove DELETE nodes
        cmds.select(lytnamespace + ":DELETE*")
        dnodes = cmds.ls(sl=True)
        cmds.delete(dnodes)

        # Turn off minor control drawing override
        cmds.setAttr(lytnamespace + ':FACE_Minor_CTRL.overrideEnabled', 0)

        # Find and rename remaning nodes.
        containednodes = cmds.namespaceInfo(lytnamespace, lod=True)

        for n in containednodes:
            newname = n.replace('FACE', lytnamespace)
            try:
                cmds.rename(n, newname)
            except:
                pass

        cmds.namespace(mv=[lytnamespace, ':'], force=True)
        cmds.namespace(set=':')
        try:
            cmds.namespace(lytnamespace, rm=True, force=True)
        except:
            pass
示例#55
0
    def jointsOnCVs(name, curve):

        if not cmds.nodeType(curve) == 'shape':

            curve = cmds.listRelatives(curve, type='shape')[0]

        mobject = GenAPI.getMObject(curve)
        iterCVs = om.MItCurveCV(mobject)

        while not iterCVs.isDone():

            index = iterCVs.index()
            nameIndex = index + 1
            pos = iterCVs.position()
            joint = cmds.joint(n='%s_0%i_Jnt' % (name, nameIndex),
                               p=(pos[0], pos[1], pos[2]))

            try:
                cmds.parent(joint, w=True)

            except RuntimeError:
                pass

            iterCVs.next()
示例#56
0
def check_nurbsCurve_with_key(log=None):
    if not log:
        import logging
        log = logging.getLogger()
        
    # get control curve, control curve is nurbs curve
    for x in cmds.ls(type='nurbsCurve'):
        # get parent transform node
        trans = cmds.listRelatives(x,parent=True)
        if trans:
            # get transform's input connection
            connections = trans[0].connections(d=1)
            if connections:
                for c in connections :
                    # is animCurve node or not
                    if cmds.nodeType( c ) == 'animCurve':
                        # get animCurve's input connection
                        con_anim = c.connections(d=1)
                        if not con_anim:
                            # animCurve has no input connection
                            # so animCurve is key animation and not set driven key animation curve
                            log.warning('The transform node has animation key:%s' % trans[0])
                        else:
                            log.debug('The transform node has set driven animation key:%s' % trans[0])
示例#57
0
def openReference(rfn):
    """
    Open current reference node in new maya window.
    """
    rfn = type(rfn) is list and rfn or [rfn]
    for i in range(0, len(rfn)):
        if cmds.nodeType(rfn[i]) == "reference":
            node = rfn
        elif os.path.isfile(rfn):
            node = cmds.referenceQuery(rfn[i], rfn=True)
        else:
            print "%s is not reference" % rfn[i]
            return None
        maya = sys.executable
        filename = cmds.referenceQuery(node, filename=True)
        expression = re.compile(
            "^(/Server-3d/Project)|(/mnt/server-3d)|(P:)|(/home/.*/Project)|(D:/Work/Project)|(//Server-3d/Project)",
            re.IGNORECASE)
        filename = expression.sub("//Server-3d/Project", filename)
        if filename:
            filename = filename.split("{")[0]
            m_command = "python(\"import chekProject; chekProject.setMayaProject({0}); import melnik_setup; melnik_setup.updateScene();import maya.cmds as cmds; cmds.file({0}, force=True, open=True )\")".format(
                "'%s'" % filename)
            subprocess.Popen([maya, "-command", m_command])
示例#58
0
def getSelectedMeshes():
    """
    Get all selected meshes, the current selection will be looped and checked
    if any of the selected transforms contain a mesh node. If this is the case
    the transform will be added to the selection list.

    :return: Parents nodes of all selected meshes
    :rtype: list
    """
    # get selection
    selection = cmds.ls(sl=True, l=True)
    extendedSelection = []

    # extend selection
    for sel in selection:
        extendedSelection.extend(
            cmds.listRelatives(sel, s=True, ni=True, f=True))

    # return parent of meshes
    return list(
        set([
            cmds.listRelatives(m, p=True, f=True)[0] for m in extendedSelection
            if cmds.nodeType(m) == "mesh"
        ]))
示例#59
0
def follicle(shape, u=0, v=0, name=""):
    """Attach follicle to "shape" at specified "u" and "v" values"""

    type = cmds.nodeType(shape)
    assert type in ("mesh", "nurbsSurface"), (
        "follicle() works on polygonal meshes and nurbs")

    src, dst = {
        "mesh": (".outMesh", ".inputMesh"),
        "nurbsSurface": (".local", ".inputSurface")
    }[type]

    follicle = cmds.createNode("follicle", name=name + "Shape")
    transform = cmds.listRelatives(follicle, parent=True)[0]

    cmds.setAttr(follicle + ".parameterU", u)
    cmds.setAttr(follicle + ".parameterV", v)

    cmds.connectAttr(follicle + ".outTranslate", transform + ".translate")
    cmds.connectAttr(follicle + ".outRotate", transform + ".rotate")
    cmds.connectAttr(shape + ".worldMatrix[0]", follicle + ".inputWorldMatrix")
    cmds.connectAttr(shape + src, follicle + dst, force=True)

    return transform
示例#60
0
    def assignShader(self):
        if not cmds.objExists(str(self.shaderToAssign)):
            if self.shaderToAssign.endswith("SG") and cmds.objExists(
                    str(self.shaderToAssign)[:-2]):
                self.interface.createSG(str(self.shaderToAssign)[:-2])
            else:
                return

        if not cmds.nodeType(self.shaderToAssign) == "shadingEngine":
            self.interface.createSG(str(self.shaderToAssign))

        path = self.getPath()

        self.cache.assignShader(path, self.shaderToAssign)

        selectedItems = self.interface.hierarchyWidget.selectedItems()
        if len(selectedItems) > 1:
            for item in selectedItems:
                if item is not self:
                    item.cache.assignShader(item.getPath(),
                                            self.shaderToAssign)

        self.interface.checkShaders(self.interface.getLayer(), item=self)
        self.interface.hierarchyWidget.resizeColumnToContents(1)