def FTV_getFluidElements( fluid ):
	'''this function consider the type of parameter fluid to not be exactly known but output anyway the fluid Transform and the fluid Shape'''

	if fluid is None:
		raise FTV_msCommandException('Please select a Fluid')

	fldTrs = None
	fldShp = None

	if pm.nodeType(fluid)== 'transform':
		childs = pm.listRelatives(fluid, s=True)
		if len(childs)>0 and pm.nodeType(childs[0]) == 'fluidShape' :
			fldTrs = fluid
			fldShp = childs[0]
		else :
			raise FTV_msCommandException('selection is invalid, you must select a fluid')
	elif pm.nodeType(fluid)== 'fluidShape':
		par = pm.listRelatives(fluid, p=True)
		if len(par)>0 and pm.nodeType(par[0]) == 'transform' :
			fldTrs = par[0]
			fldShp = fluid
		else :
			raise FTV_msCommandException('selection is invalid, you must select a fluid')
	else :
		raise FTV_msCommandException('selection is invalid, you must select a fluid')
	return (fldTrs,fldShp)
예제 #2
0
	def createManipCtrlCenter(self):
		
		pm.select(cl = True)
		
		#createTextCurves
		nurbsText = self.prefix + '_Ctrl'
		textCurvesReturnList = pm.textCurves(f = 'arial' , t = nurbsText, ch = True )
		
		textTopGrp = textCurvesReturnList[0]
		makeTextCurvesNode = textCurvesReturnList[1]
		
		pm.select(cl = True)
		
		#get future history of makeTextCurvesNode
		textHistoryList = pm.listHistory(makeTextCurvesNode, future = True, af = True)
		
		#get list of transforms and NurbsCurve nodes connected to makeTextCurvesNode
		textTransformList = []
		textNurbsCurveList = []
		for node in textHistoryList:
			if(pm.nodeType(node) == 'transform'): textTransformList.append(node)
			if(pm.nodeType(node) == 'nurbsCurve'): textNurbsCurveList.append(node)
			
		pm.select(cl = True)
		
		#delete makeTextCurvesNode
		pm.delete(makeTextCurvesNode)
		pm.select(cl = True)
		
		#iterate through transformList, move pivot to ws (0,0,0) and freeze all
		for transformNode in textTransformList:
			pm.xform(transformNode, ws = True, piv = (0,0,0))
			pm.makeIdentity(transformNode, a = True)
			
			
		#create manipCtrlGrp
		self.manip_CtrlCenter = pm.group(n = self.prefix + '_manip_ctrl_center')
		pm.select(cl = True)
		
		#iterate through nurbsCurve list and parent shapes under manip ctrlCenter
		for nurbsCurveShape in textNurbsCurveList:
			pm.parent(nurbsCurveShape, self.manip_CtrlCenter, r = True, s = True)
			
		pm.select(cl = True)
		
		#create manip_ctrlCenter grp and translate correctly
		self.manip_CtrlCenter_grp = pm.group(n = self.prefix + '_manip_ctrl_center_grp')
		pm.select(cl = True)
		pm.parent(self.manip_CtrlCenter, self.manip_CtrlCenter_grp)
		pm.select(cl = True)
		
		self.manip_CtrlCenter_grp.translate.set(self.jointPositionList[-1][0], self.jointPositionList[-1][1] + 2, self.jointPositionList[-1][2])
		
		
		#delete remaining text transform nodes
		pm.delete(textTopGrp)
		pm.select(cl = True)
예제 #3
0
def isObjType(*args):
    tmpList = [ o.getParent() for o in sel if not(pm.nodeType(o) == 'mesh' or pm.nodeType(o) == 'nurbsSurface') ]
    
    tmpStr = ''
    for s in tmpList:
        tmpStr = tmpStr + s + ','
            
    if( len(tmpList) > 0 ):
        pm.confirmDialog(t="Error", message= tmpStr + " are not mesh or nurbsSurface", icon='critical')
        return 0
    
    return 1
예제 #4
0
def export():
    '''
    Export a nuke file out with all the selected object from maya. 
    Takes care of all exporting
    need: shape and transform
    because might need some attributes from them
    '''
    objList = []
    for node in pm.ls(sl=True):
        print '[%s]%s' % (pm.nodeType(node) , node)
        if pm.nodeType(node) == 'transform':
            obj = mObject(node)
            objList.append(obj)
    writeNukeFile(objList)
 def findCameraInSelection(self):
     selection = pm.ls(sl=True)
     assert len(selection)>0, "Nothing is selected. Select a camera"
     assert len(selection)<2, "Multiple objects selected. Select camera only"
     
     if pm.nodeType(selection[0])=='transform':
         camShapeLst = pm.listRelatives(selection[0], type='camera')
         assert len(camShapeLst)>0, "No camera selected"
         return (selection[0], camShapeLst[0])
     
     elif pm.nodeType(selection[0])=='camera':
         parentTransform = pm.listRelatives(selection[0], parent=True)
         return (parentTransform,selection[0])
     
     raise StandardError("No camera is selected")
예제 #6
0
 def __init__(self, node, **kwargs):
     self.setup(kwargs)
     self.transform = node
     self.shape = self.transform.getShape()
     self.type = pm.nodeType(self.shape)
     
     self.setAttributes()
예제 #7
0
 def create_preset(self):
     '''
     # creates the file for the preset
     ******
     # file pattern
     # data = ['preset name', 'light type', 'description',
                         xform_attrs[], shape_attrs[]] 
     ******
     '''
     sel = pm.ls(selection= True)[0]
     sel_shape = sel.getShape()
     node_type = pm.nodeType(sel_shape)
     
     if 'Light' not in node_type:
         return
     
     data = []
     
     data.append('%s' % (self.field.getText()))
     
     data.append('%s' % (node_type))
     
     data.append('%s' % (self.scroll.getText()))
     
     sel_data = []
     
     sel_shape_data = []
     
     sel_attrs = pm.listAttr(sel)
     sel_shape_attrs = pm.listAttr(sel_shape)
     
     for attr in sel_attrs:
         try :
             value = pm.getAttr('%s.%s' % (sel, attr))
             temp_data = (attr , value)
             sel_data.append(temp_data)
         
         except:
             pass
         
     for attr in sel_shape_attrs:
         try:
             value = pm.getAttr('%s.%s' % (sel_shape, attr))
             temp_data = (attr , value)
             sel_shape_data.append(temp_data)
         
         except:
             pass
         
         
     data.append(sel_data)
     data.append(sel_shape_data)
     
     name ='%s.light'  % (self.field.getText())
     full_path = os.path.join(self.path, name)
     f = open(full_path, 'w')
     pickle_data = pickle.dump(data, f)
     f.close()
     
     preset_ui() # this will list will update the preset section
예제 #8
0
    def check(self):
        """
        Initial checks to prevent from some problems.
        This is not a guarantee for the procedure to run smoothly,
        but a big hint that it will.
        """

        #selected_node
        selected_node = self.get_selected_node()

        #check selected node exists
        if not (selected_node):

            #log
            self.logger.debug('Selected node is None.')
            return False

        
        #check if node is transform
        if not (pm.nodeType(selected_node) == 'transform'):

            #log
            self.logger.debug('Selected node {0} is not of type transform'.format(selected_node.name()))
            return False


        #return
        return True
예제 #9
0
파일: utils.py 프로젝트: bohdon/boTools
def printSelection(longNames=True):
    """Print the selection in an organized, numbered list"""
    selList = pm.selected()
    print '\n//{0} Nodes Selected'.format(len(selList))
    nameMethod = None
    if longNames:
        nameMethod = 'longName'
    else:
        nameMethod = 'name'
    
    maxLen = 0
    for obj in selList:
        if hasattr(obj, nameMethod):
            name = getattr(obj, nameMethod)()
        else:
            name = obj.name()
        if len(name) > maxLen:
            maxLen = len(name)
    
    for i in range(len(selList)):
        obj = selList[i]
        typ = pm.nodeType(obj)
        if hasattr(obj, nameMethod):
            name = getattr(obj, nameMethod)()
        else:
            name = obj.name()
        print '{index:03}. {name:<{maxLen}} - {type}'.format(index=i, name=name, type=typ, maxLen=maxLen)
def addMaterialinGraph(*args):
    
    sel_shapes = pm.ls( sl=True, dag=True, type='shape' )
    
    global panel_hyperShd
    for shape in sel_shapes:
        if( not( pm.nodeType(shape) == 'mesh' or pm.nodeType(shape) == 'nurbsSurface' ) ):
            pm.confirmDialog( t="Error", message= " selected objects are not mesh or nurbsSurface", icon='critical' )
            
        shdGrp = shape.outputs(type='shadingEngine')
        for sg in shdGrp:
            shader = pm.ls( sg.inputs(), materials=1 )
            pm.select(shader)
            mel.eval( "hyperShadePanelGraphCommand( \"%s\", \"addSelected\" )"  % str(panel_hyperShd) )
            
            pm.select(shape.getParent())
예제 #11
0
def FindDeformers ( shape=None , type=''):
	
	if shape==None:
		obj = pm.ls(sl=True)[0]
		shape = obj.getShape()
	
	if shape :
		# List Deformers
		history = pm.listHistory( shape, pruneDagObjects=True, interestLevel=2 ) 
		
		deformers = []
		
		for node in  history :
			nodeTypes = pm.nodeType( node, inherited=True )
		
			if 'geometryFilter' in nodeTypes:
				
				if type=='' and  nodeTypes[1] != 'tweak' :
					deformers.append(node)
			
				elif nodeTypes[1] == type and nodeTypes[1] != 'tweak':
					deformers.append(node)
		
		return deformers
	else:
		pm.warning('No shape found.')
예제 #12
0
def getAnimCurve(node):
    '''
    If node or nodes parent is a transform node.
        returns a AnimCurve node.
    '''
    
    type = pm.nodeType(node)
    if type == 'transform':
        return getAnimCurveFromTransform(node)
    else:
        parent = node.getParent()
        if pm.nodeType(parent) == 'transform':
            return getAnimCurveFromTransform(parent)
        else:
            print node, 'is none of the requered nodeTypes...'
            return None
예제 #13
0
def create_ui(* args):
    '''
    # this creates the ui for the selected  light from the scrollField
    '''
    # dictionary for class
    # the script get the light type each type is a key
    # and based on that it will pick which class to instance
    
    light_classes = {'spotLight': lights.Light_spot,
            'directionalLight': lights.Light_directional,
              'ambientLight': lights.Light_ambient,
              'areaLight': lights.Light_area,
              'pointLight': lights.Light_point,
              'volumeLight': lights.Light_volume}
    
    selected = scroll_list.getSelectItem()
    global lights_dict
    global obj_ui_list
    # deleteting existing ui objects
    for obj in obj_ui_list:
        try:
            obj.delete()
            
        except:
            pass
    
    
    for sel in selected:
        pm.setParent(ui_row)
       # getting the node type
        obj_type = pm.nodeType('%s' % (lights_dict[u'%s' %(str(sel))]))
        # using the  ^^ dictionarry to instance the appropritate class
        light  = light_classes[obj_type](light= '%s' % (sel)).create()
        # appending that object to the global objects list
        obj_ui_list.append(light)
예제 #14
0
def get_light_details_list():
	"""Parse the scene for light nodes and return list with information"""

	#log_progress
	log_progress = False

	#scene_lights_list
	scene_lights_list = get_all_scene_lights()
	#empty
	if not(scene_lights_list):
		print('No light nodes in the scene.')
		return []

	#scene_light_details_list
	scene_light_details_list = []

	#iterate and add details
	for light_node in scene_lights_list:

		#light_details_dict
		light_details_dict = {}

		#light_shape_name
		light_details_dict['light_shape_name'] = light_node.name()
		#light_transform_name
		light_details_dict['light_transform_name'] = light_node.getParent().name()
		#light_type
		light_details_dict['light_type'] = pm.nodeType(light_node)

		
		#inclusive_matrix
		inclusive_matrix = get_inclusive_matrix(light_node.name())
		#list_matrix
		list_matrix = mmatrix_to_list(inclusive_matrix)
		#add to dict
		light_details_dict['matrix'] = list_matrix




		#iterate LIGHT_PARAMETERS_LIST and add values if existing
		LIGHT_PARAMETERS_LIST = VRAY_LIGHT_PARAMETERS_LIST + MAYA_LIGHT_PARAMETERS_LIST
		for attr in LIGHT_PARAMETERS_LIST:
			if(light_node.hasAttr(attr)):
				#attr_value
				attr_value = pm.getAttr(light_node.name() +'.' +attr)
				#append to dict
				light_details_dict[attr] = attr_value

		

		#append dict to list
		scene_light_details_list.append(light_details_dict)


	return scene_light_details_list
예제 #15
0
def get_camera_details_list():
	"""Parse the scene for camera nodes and return list with information"""

	#log_progress
	log_progress = False

	#scene_cameras_list
	scene_cameras_list = pm.ls(ca = True)
	#empty
	if not(scene_cameras_list):
		print('No camera nodes in the scene.')
		return []

	#camera_details_list
	camera_details_list = []

	#iterate and add details
	for camera_node in scene_cameras_list:

		#camera_details_dict
		camera_details_dict = {}

		#camera_shape_name
		camera_details_dict['camera_shape_name'] = camera_node.name()
		#camera_transform_name
		camera_details_dict['camera_transform_name'] = camera_node.getParent().name()
		#camera_type
		camera_details_dict['camera_type'] = pm.nodeType(camera_node)

		
		#inclusive_matrix
		inclusive_matrix = get_inclusive_matrix(camera_node.name())
		#list_matrix
		list_matrix = mmatrix_to_list(inclusive_matrix)
		#add to dict
		camera_details_dict['matrix'] = list_matrix




		#iterate LIGHT_PARAMETERS_LIST and add values if existing
		CAMERA_PARAMETERS_LIST = VRAY_CAMERA_PARAMETERS_LIST + MAYA_CAMERA_PARAMETERS_LIST
		for attr in CAMERA_PARAMETERS_LIST:
			if(camera_node.hasAttr(attr)):
				#attr_value
				attr_value = pm.getAttr(camera_node.name() +'.' +attr)
				#append to dict
				camera_details_dict[attr] = attr_value

		

		#append dict to list
		camera_details_list.append(camera_details_dict)


	return camera_details_list
예제 #16
0
 def filterForTextures(cls, textureList, *args, **kwargs):
   ''' filter a list for only file texture nodes '''
   newList = []
   if textureList:
     #
     for item in textureList:
       type = pm.nodeType(item)
       if type == 'file':
         newList.append(item)
   return newList
예제 #17
0
def getNodeType(name):
    nodeType = pm.nodeType(name)
    lights = ["directionalLight",
                "pointLight",
                "spotLight",
                "areaLight"]

    if nodeType in lights:
        nodeType = 'light'

    return nodeType
예제 #18
0
def listWorldChildren ():
    '''
    Return the transform node at the root of the hierarchy.
    
    Return :
    worldChildrenList = List
    '''
    worldChildrenList = list()
    for elem in pm.ls(assemblies=True) :
        if pm.nodeType(elem) == 'transform' :
            worldChildrenList.append(elem)
    return worldChildrenList
	def startupCheck(self):
		'''Perform check to see if all requirements to run the script are fullfilled'''
		
		
		#Check namespaces attrs.
		if not(self.namespaceShader):
			if(self.verbose):print('Empty namespaces for shader. Please provide correct parameter.')
			return False
			
		#Check namespaces attrs.
		if not(self.namespaceChrystal):
			if(self.verbose):print('Empty namespaces for chrystal. Please provide correct parameter.')
			return False
		
		
		
		
		#check selection
		selectionList = pm.ls(sl = True, fl  = True)
		
		#check selectionList 
		if not(selectionList):
			if(self.verbose):print('Nothing selected.')
			return False
			
		#check selectionList == 1
		if not(len(selectionList) == 1):
			if(self.verbose):print('SelectionList has wrong length, please only select Chrystal_top_grp')
			return False
			
		
		#check shadernames in scene
		for shaderName in self.shaderNamesList:
			#if shdername in scene
			if not(self.namespaceShader +':' +shaderName in pm.ls(fl = True, mat = True)):
				if(self.verbose):print(self.namespaceShader +':' +shaderName +' not in scene')
				return False
				
		
		#check if chrystalTopGrp is type transform
		if not(pm.nodeType(selectionList[0]) == 'transform'):
			if(self.verbose):print('Selected chrystal top grp is not of type transform')
			return False
			
		#Check subGroupNames
		for chrystalSubgroupName in self.chrystalSubgroupNamesList:
			if not(chrystalSubgroupName in [x.name().split('|')[-1] for x in selectionList[0].getChildren()]):
				if(self.verbose):print(chrystalSubgroupName +' not in selectionList')
				return False
		
		
		#If successful return True
		return True
	def getAnimCurveNodeList(self, object):
		
		pm.select(cl = True)
		
		#get all connections to object
		connectionsList = pm.listConnections(object)
		
		#Check if connectionsList is empty
		if not(connectionsList):
			if(self.verbose): print('Object hast no input coonections')
			return connectionsList
			
		#get animCurveList
		animCurveList = []
		
		#iterate through connectionList and append animcurve nodes
		for node in connectionsList:
			if(pm.nodeType(node) == 'animCurveTU' or pm.nodeType(node) == 'animCurveTL' or pm.nodeType(node) == 'animCurveTA'): animCurveList.append(node)
			
			
		return animCurveList
예제 #21
0
 def toNukeFormat(self, attr):
     '''
     Formats to a string which can be writen to nuke.
     '''
     d ={}
     name = attr.longName()
     string = '%s {' % (name)
     for curve in attr.connections():
         if  'animCurve' in pm.nodeType(curve):
             string +=  '{curve%s} ' % (self.getAnimDict(curve))
     string = '%s}\n' % (string.strip())
     d[name] = string
     return d
예제 #22
0
 def toNukeFormat(self, attr):
     '''
     Formats to a string which can be writen to nuke.
     '''
     name = attr.longName()
     string = '{'
     for curve in attr.connections():
         if 'animCurve' in pm.nodeType(curve):
             if 'FilmAperture' in name:
                 string +=  '{curve%s} ' % (self.getAnimDict(curve, 25.4))
             else:
                 string +=  '{curve%s} ' % (self.getAnimDict(curve))
     string = '%s}\n' % (string.strip())
     return string
def FTM_getFluidElements( fluid ):
	if fluid is None:
		raise FTM_msCommandException('Please select a Fluid')

	fldTrs = None
	fldShp = None
	if pm.nodeType(fluid)== 'transform':
		childs = pm.listRelatives(s=True)
		if len(childs)>0 and pm.nodeType(childs[0]) == 'fluidShape' :
			fldTrs = fluid
			fldShp = childs[0]
		else :
			raise FTM_msCommandException('selection is invalid, you must select a fluid')
	elif pm.nodeType(fluid)== 'fluidShape':
		par = pm.listRelatives(p=True)
		if len(par)>0 and pm.nodeType(par[0]) == 'transform' :
			fldTrs = par[0]
			fldShp = fluid
		else :
			raise FTM_msCommandException('selection is invalid, you must select a fluid')
	else :
		raise FTM_msCommandException('selection is invalid, you must select a fluid')
	return (fldTrs,fldShp)
예제 #24
0
    def duplicate(self, *args):
        '''
        # duplicates selected lights
        '''
        selected = pm.ls(sl=True)

        for sel in selected:
            sel_shape = sel.getShape()  # getting the shape node
            sel_type = pm.nodeType(sel_shape)  # getting the node type

            xform = self.xform.getValue()

            if 'Light' not in sel_type:
                print '# wrong object type ', sel
                continue
            # creating a new light based on the recieved node type
            new_light = pm.shadingNode('%s' % (sel_type), asLight=True)
            new_light = pm.rename(new_light, '%s_copy' % (sel))  # renaming
            new_shape = new_light.getShape()  # getting the shape
            # listing transform attrs
            input_attrs = pm.listAttr(sel)
            # listing shape attrs
            shape_attrs = pm.listAttr(sel_shape)

            if xform == 1:
                for attr in input_attrs:
                    try:
                        value = pm.getAttr('%s.%s' % (sel, attr))
                        pm.setAttr('%s.%s' % (new_light, attr), value)

                    except:
                        pass

            for attr in shape_attrs:
                try:
                    value = pm.getAttr('%s.%s' % (sel_shape, attr))
                    pm.setAttr('%s.%s' % (new_shape, attr), value)

                except:
                    pass

            pm.select(new_light)
            if self.override_intensity.getValue() == 1:
                #pm.setAttr('%s.intensity' % (new_light), self.int_slider.getValue())
                new_light.intensity.set(self.int_slider.getValue())

            if self.override_color.getValue() == 1:
                #pm.setAttr('%s.color' % (new_light), self.color_slider.getRgbValue())
                new_light.color.set(self.color_slider.getRgbValue())
예제 #25
0
 def duplicate(self, * args):
     '''
     # duplicates selected lights
     '''
     selected = pm.ls(sl= True)
                
     for sel in selected:
         sel_shape = sel.getShape() # getting the shape node
         sel_type = pm.nodeType(sel_shape) # getting the node type
         
         xform = self.xform.getValue()
         
         if 'Light' not in sel_type:
             print '# wrong object type ', sel
             continue
         # creating a new light based on the recieved node type
         new_light = pm.shadingNode('%s' % (sel_type), asLight= True)
         new_light = pm.rename(new_light, '%s_copy' % (sel)) # renaming
         new_shape = new_light.getShape() # getting the shape
         # listing transform attrs
         input_attrs = pm.listAttr(sel) 
         # listing shape attrs
         shape_attrs = pm.listAttr(sel_shape)
         
         if xform == 1:
             for attr in input_attrs:
                 try:
                     value = pm.getAttr('%s.%s' % (sel, attr))
                     pm.setAttr('%s.%s' % (new_light, attr), value)
                 
                 except:
                     pass
                 
         for attr in shape_attrs:
             try:
                 value = pm.getAttr('%s.%s' % (sel_shape, attr))
                 pm.setAttr('%s.%s' % (new_shape, attr), value)
             
             except:
                 pass
         
         pm.select(new_light)
         if self.override_intensity.getValue() == 1:
             #pm.setAttr('%s.intensity' % (new_light), self.int_slider.getValue())
             new_light.intensity.set(self.int_slider.getValue())
         
         if self.override_color.getValue() == 1:
             #pm.setAttr('%s.color' % (new_light), self.color_slider.getRgbValue())
             new_light.color.set(self.color_slider.getRgbValue())
예제 #26
0
def fix_shape_names():
    start = time.time()
    top_nodes = cmds.ls(assemblies=True)

    for node in top_nodes:
        children = pm.listRelatives(node, ad=True)

        for transform in children:
            if pm.nodeType(transform) == 'transform':
                shape = transform.getShape()
                if shape and shape != transform + 'Shape':
                    cmds.rename(str(shape), transform + 'Shape')

    end = time.time()
    print('!Info: The renaming took: {} seconds.'.format(end - start))
예제 #27
0
def transformation_info(sel_node):
    """ Gets the translate, rotate, scale and joint orient data (if joint) of the selected node.
    :param sel_node: The selected node.
    :return: transformation array which contains the all translate, rotate, scale and if node is a joint joint orient.
    """
    transformation = {}
    if pm.getAttr(sel_node + '.t'):
        transformation['t'] = pm.getAttr(sel_node + '.t')
    if pm.getAttr(sel_node + '.r'):
        transformation['r'] = pm.getAttr(sel_node + '.r')
    if pm.nodeType(str(sel_node)) == 'joint' and pm.getAttr(sel_node + '.jo'):
        transformation['jo'] = pm.getAttr(sel_node + '.jo')
    if pm.getAttr(sel_node + '.s'):
        transformation['s'] = pm.getAttr(sel_node + '.s')
    return transformation
예제 #28
0
def _aeLoader(modname, objname, nodename):
    mod = __import__(modname, globals(), locals(), [objname], -1)
    try:
        f = getattr(mod, objname)
        if inspect.isfunction(f):
            f(nodename)
        elif inspect.isclass(f):
            inst = f(pm.nodeType(nodename))
            inst._doSetup(nodename)
        else:
            print "AE object %s has invalid type %s" % (f, type(f))
    except Exception:
        print "failed to load python attribute editor template '%s.%s'" % (modname, objname)
        import traceback
        traceback.print_exc()
def run():
    if pm.nodeType(pm.ls(sl=True)[0]) == 'reference':
        result = pm.promptDialog(title='Rename Object',
                                 message='Enter Name:',
                                 button=['OK', 'Cancel'],
                                 defaultButton='OK',
                                 cancelButton='Cancel',
                                 dismissString='Cancel')

        if result == 'OK':
            name = pm.promptDialog(query=True, text=True)
            if name != '':
                pm.lockNode(pm.ls(sl=True)[0], l=False)
                pm.rename(pm.ls(sl=True)[0], name)
                pm.lockNode(pm.ls(sl=True)[0])
	def getVrayMeshlightLightLink(self, vrayMeshLight):
		'''Accept vrayMeshLight as Param and traverse the connections to return corresponding lightlink node'''
		
		pm.select(cl = True)
		
		#get list of all connections of type transform for vray meshlight
		lightConnectionsList = vrayMeshLight.listConnections(t='transform', et = True)
		pm.select(cl = True)
		
		#iterate over lightconnectionsList and check children, return if child is of type vrayLightLink
		for obj in lightConnectionsList:
			try:
				if(len(obj.getChildren()) == 1 and pm.nodeType(obj.getChildren()[0]) == 'VRayLightMeshLightLinking'):return obj.getChildren()[0]
			except:
				pass
예제 #31
0
def findBlendShape(_tranformToCheck):
    """
    Find the blendShape from a string
    @param _tranformToCheck: Needs to be a String!!
    """
    result = []
    if not (pm.objExists(_tranformToCheck)):
        return result
    validList = mel.eval('findRelatedDeformer("' + str(_tranformToCheck) + '")')
    if validList is None:
        return result
    for elem in validList:
        if pm.nodeType(elem) == 'blendShape':
            result.append(elem)
    return result
예제 #32
0
def getContainerOfNode(node):
    if isinstance(node, pymel.nodetypes.DagNode):
        parent = pymel.listRelatives(node, parent=True)
        if parent:
            while parent:
                if pymel.nodeType(node) == 'dagContainer':
                    return parent[0]

                else:
                    parent = pymel.listRelatives(parent, parent=True)
                    if not parent:
                        return None

    else:
        pass
예제 #33
0
def saveDeformers():
    saveFilePath = pm.fileDialog2(fileFilter='*.json')[0]
    if saveFilePath:
        saveFileDir = '/'.join(saveFilePath.split('/')[:-1]) + '/'
        dfms = [dfm for dfm in pm.ls() if pm.nodeType(dfm) in deformerTypes]
        deformerDict = {}

        for dfm in dfms:
            key = dfm.name()
            handle = getHandle(dfm)
            deformerDict[key] = {}
            deformerDict[key]['nlType'] = getNonlinearType(dfm)
            deformerDict[key]['mtx'] = pm.xform(handle, q=1, ws=1, m=1)
            parent = None
            if handle.getParent():
                parent = handle.getParent().name()
            deformerDict[key]['parent'] = parent
            deformerDict[key]['params'] = {}
            deformerDict[key]['geo'] = [
                geo for geo in pm.nonLinear(dfm, q=1, geometry=1)
            ]
            for geo in deformerDict[key]['geo']:
                fileName = '%s_%s_weights.xml' % (geo, key)
                toSkip = [node.name() for node in dfms if not node == dfm]
                pm.deformerWeights(fileName,
                                   export=1,
                                   sh=geo,
                                   skip=toSkip,
                                   path=saveFileDir)
            attrs = [
                a for a in pm.listAttr(dfm)
                if pm.Attribute('%s.%s' %
                                (key, a)).isKeyable() and not 'weight' in a
            ]
            for attr in attrs:
                deformerDict[key]['params'][attr] = pm.getAttr(
                    '%s.%s' % (dfm.name(), attr))
            deformerDict[key]['conns'] = {}
            for attr in attrs:
                if not pm.Attribute('%s.%s' % (key, attr)).isArray():
                    conn = pm.listConnections('%s.%s' % (key, attr),
                                              plugs=1,
                                              d=0)
                    if conn:
                        deformerDict[key]['conns'][attr] = conn[0].name()

        with open(saveFilePath, 'w') as outfile:
            json.dump(deformerDict, outfile)
	def connectToAlembicCache(self, namespace = ''):
		
		#get SelectionList
		selectionList = pm.ls(sl = True, fl = True, type = 'transform')
		pm.select(cl = True)
		
		#check if objects are selected
		if not(selectionList):
			if(self.verbose): print('No objects selected, please select at least one object.')
			return None
			
		#Check if namespace is valid
		if not(namespace in self.getNamespaces()):
			if(self.verbose): print('Picked namespace does not exists anymore. Please refresh namespace list')
			return None
		
		
		
		
		#Connect to alembic node
		
		
		#Iterate through selectionList and connect same object plus namespace to alembic cache node if possible
		for masterTrans in selectionList:
			
			#getShape
			masterShape = masterTrans.getShape()
			
			#check if masterShape inMesh Attr connected to Alembic
			if not(pm.nodeType(pm.listConnections(masterShape.inMesh, s = True)[0]) == 'AlembicNode'):
				if(self.verbose): print(masterTrans.name() +' inMesh Attribute not connected to Alembic node. Continuing...')
				continue
				
			#Check if namespace + masterTrans object exists
			if not(pm.objExists(namespace +':' +masterTrans.name().split(':')[-1])):
				if(self.verbose): print(namespace +':' +masterTrans.name().split(':')[-1] +' does not exist. Continuing...')
				continue
				
			
			#Connect Object to Alembic Node
			connectioSourceAttr = pm.listConnections(masterShape.inMesh, s = True, p = True)[0]
			connectionDestinationAttr = namespace +':'  +masterShape.name().split(':')[-1] +'.inMesh'
			pm.connectAttr(connectioSourceAttr, connectionDestinationAttr,f = True)
		
		
		
		#Success Msg
		if(self.verbose): print('Successfully connected PaintFx Hair Geo to Alembic Cache')
예제 #35
0
 def getTextureDimensions(self, *args, **kwargs):
   '''
     returns the dimensions of the currently displayed texture in the UV Editor
     If there is no texture loaded returns a default [1,1]
   
   '''
   textureDimensions = [1,1]
   numImages = pm.textureWindow(self.uvTextureView[0],q=True, ni=True)
   if numImages>0:
     currentTextureImage = pm.textureWindow(self.uvTextureView[0],q=True, imageNumber=True)
     imageList = pm.textureWindow(self.uvTextureView[0],q=True, imageNames=True)
     currentTextureString = imageList[currentTextureImage].split('|')
     currentTextureNode = currentTextureString[len(currentTextureString)-1].strip()
     if pm.nodeType(currentTextureNode)=='file':
       textureDimensions = pm.getAttr(currentTextureNode+'.outSize')        
   return textureDimensions
예제 #36
0
def getParentNodes(grp, nodeType='mesh', dataType=0, mainWindow=None):

    nodes = list()
    get_nodes = getNodes(grp, 'Transform', 0, mainWindow=mainWindow)
    dType = {0: 'node', 1: 'node.longName()'}

    for node in get_nodes:

        child = node.childAtIndex(0)

        if pm.nodeType(child) == nodeType:
            nodes.append(eval(dType[dataType]))
    if dataType != 0:
        nodes.sort(key=len, reverse=True)

    return nodes
def copyWeights(sourceMesh, destMesh):
    '''
    Select skinned mesh then non-skinned mesh and run: copyWeights(pmc.selected()[0], pmc.selected()[1])
    '''

    sourceSkin = [
        x for x in pmc.listHistory(sourceMesh)
        if pmc.nodeType(x) == "skinCluster"
    ][0]
    influences = pmc.skinCluster(sourceMesh, q=1, influence=1)
    pmc.select(influences)

    destSkin = pmc.skinCluster(influences, destMesh)
    pmc.copySkinWeights(ss=sourceSkin.name(),
                        ds=destSkin.name(),
                        noMirror=True)
예제 #38
0
def _aeLoader(modname, objname, nodename):
    mod = __import__(modname, globals(), locals(), [objname], -1)
    try:
        f = getattr(mod, objname)
        if inspect.isfunction(f):
            f(nodename)
        elif inspect.isclass(f):
            inst = f(pm.nodeType(nodename))
            inst._doSetup(nodename)
        else:
            print "AE object %s has invalid type %s" % (f, type(f))
    except Exception:
        print "failed to load python attribute editor template '%s.%s'" % (
            modname, objname)
        import traceback
        traceback.print_exc()
예제 #39
0
def saveCntrlsShape(objs, path):
    sel = [x for x in objs if '_cntrl' in x.name()]
    filename = path
    cntrlShapeDict = {}
    for obj in sel:
        tempDict = {}
        for shp in obj.getShapes():
            if pm.nodeType(shp) == 'nurbsCurve':
                pointList = []
                for i in range(len(shp.cv)):
                    pointList.append(pm.pointPosition(shp.cv[i], l=True))
                tempDict[shp.name()] = pointList
        cntrlShapeDict[obj.name()] = tempDict
    with open(filename, 'wb') as f:
        pickle.dump(cntrlShapeDict, f)
    print 'cntrl save ok'
예제 #40
0
def assign_material_to_selection():
    sel = pm.ls(sl=True, l=True)
    # Error checking for selection node type
    if len(sel) == 0:
        print "Nothing currently selected!"
    else:
        # Error checking for selection node type
        for s in sel:
            node_type = pm.nodeType(s)
            if node_type == 'transform' or 'mesh':
                shading_group = pm.listConnections(node_type, d=True, et=True, t='shadingEngine')
                if shading_group:
                    pm.sets(node_type, e=True, forceElement=shader)
                    print "Success"
            else:
                print "Not a mesh or transform type"
예제 #41
0
    def findBlendShape(self):
        """
        Find the blendShape from 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) == 'blendShape':
                result.append(elem)
        return result
예제 #42
0
    def write_info(self):

        self.info_field.setText('')

        node = self.connections_list.getSelectItem()[0]
        if self.check_box.getValue() == 1:
            pm.select(node)

        node_type = pm.nodeType(node)
        #print node_type

        if node_type == 'layeredTexture':
            result = self.get_layered_texture_attrs(
                self.connections_dict[node])
            for r in result:
                self.info_field.insertText('%s\n' % (r))

        if node_type == 'ramp':
            result = self.get_ramp_attrs(node)
            for r in result:
                self.info_field.insertText('%s\n' % (r))

        if node_type == 'noise':
            result = self.get_noise_attrs(node)
            for r in result:
                self.info_field.insertText('%s\n' % (r))

        if node_type != 'ramp' and node_type != 'noise':
            if self.attr_check_box.getValue() == 1:
                attrs = pm.listAttr('%s' % (node),
                                    write=True,
                                    settable=True,
                                    keyable=True)

            if self.attr_check_box.getValue() == 0:
                attrs = pm.listAttr('%s' % (node),
                                    write=True,
                                    settable=True,
                                    keyable=True,
                                    inUse=True)

            for attr in attrs:
                try:
                    value = pm.getAttr('%s.%s' % (node, attr))
                    self.info_field.insertText('%s: %s\n' % (attr, value))
                except:
                    pass
예제 #43
0
 def get_scene_nodes(self):
     """
     each node in list contains 3 sub-items: nodeName, type, longName
     """
     list_nodes_raw = pm.ls()
     list_nodes = []
     for node in list_nodes_raw:
         if 'dagNode' in pm.nodeType(str(node.longName()), inherited=True):
             is_dag = True
         else:
             is_dag = False
         list_nodes.append([
             str(node.nodeName()),
             str(node.type()),
             str(node.longName()), is_dag
         ])
     return list_nodes
예제 #44
0
def getCenter(nodes, getPivot=True, getScalePivot=False):
    '''
    선택된 컴포턴트나 트렌스폼노드들의 중심좌표를 리턴

    @param nodes: trnasform, or components 노드들
    @type nodes: list

    @param getPivot: (default True),  transform노드의 pivot을 기준으로 작동, 기본값을 True translate를 사용
    @type getPivot: bool

    @param getScalePivot: (default False), getPivot이 True일때 기본으로 rotatePivot을 사용하는데 scalePivot을 사용하고 싶을때 사용.
    @type getScalePivot: bool

    @return : 중심 좌표
    @rtype : pm.dt.Vector
    '''
    result = []
    if getPivot:
        for obj in nodes:
            if pm.nodeType(obj) == 'transform':
                xformResult = pm.xform(obj, q=True, ws=True, pivots=True)
                rtPiv, scPiv = xformResult[:3], xformResult[3:]

                if getScalePivot: res = scPiv
                else: res = rtPiv

            else:
                res = pm.xform(obj, q=True, ws=True, t=True)

            result.extend(res)
    else:
        result = pm.xform(nodes, q=True, ws=True, t=True)

    # 입력된 자료의 평균값 알아냄
    points = []
    for i in range(len(result) / 3):
        pnt = i * 3
        x, y, z = result[pnt], result[pnt + 1], result[pnt + 2]
        points.append(dt.Vector(x, y, z))

    arr = dt.Array(points)
    sum = dt.Vector(arr.sum(0))  # @ReservedAssignment
    avr = sum / len(points)

    # 결과 리턴
    return avr
예제 #45
0
    def overrideType(self, object):
        """
        Deprecated. Use produceOverrides() instead.

        Check the type of the object and return which override we can use.
        """
        om.MGlobal.displayWarning("%s: Walter.overrideType is deprecated. "
                                  "Use Walter.produceOverrides instead." %
                                  (self.NAME))

        nodeType = pm.nodeType(object)
        if nodeType == 'displacementShader':
            return OVERRIDE_DISPLACEMENT
        elif nodeType == 'walterOverride':
            return OVERRIDE_ATTRIBUTE

        return OVERRIDE_SHADER
예제 #46
0
파일: Data.py 프로젝트: Psichari91/Couture
def testGeo(objectList):
    """ !@Brief
    This function checks if selected object are a geometry
    @param objectList: List, a list of selected  pm node
    """

    polygonMesh = []
    nonPolygonMesh = []
    for object in objectList:

        if pm.nodeType(object.getShape(), api=True) == "mesh":
            polygonMesh.append(object)

        else:
            nonPolygonMesh.append(object)

    return polygonMesh,nonPolygonMesh
예제 #47
0
    def convertLightmap(cls, bakeSet, camera, dir, shadows, *args, **kwargs):
        ''' '''
        convertString = ''

        if shadows == True:
            shadowsSwitch = ' -sh'
        else:
            shadowsSwitch = ''

        pm.select(bakeSet)
        bakeObjs = pm.ls(selection=True)
        if bakeObjs:
            if (pm.nodeType(bakeSet) == 'textureBakeSet'):

                lightMapDir = os.path.normpath(os.path.join(dir, 'lightMap'))
                if not os.path.exists(lightMapDir):
                    os.makedirs(lightMapDir)
                if os.name == 'nt':
                    dir = dir.replace('\\', '/')
                fileSwitch = ' -project "' + dir + '"'

                convertString = 'convertLightmap -camera ' + camera + shadowsSwitch + fileSwitch
            else:
                convertString = 'convertLightmap -vm -camera ' + camera + shadowsSwitch + ' -bo ' + bakeSet + ' '

            for obj in bakeObjs:
                pm.select(obj)
                fullPath = pm.ls(selection=True, long=True)
                shadingGroup = pm.listConnections(obj,
                                                  destination=True,
                                                  source=False,
                                                  plugs=False,
                                                  type='shadingEngine')
                try:
                    convertString += ' ' + shadingGroup[0] + ' ' + fullPath[0]
                except:
                    pm.warning(
                        'Your bake set contains geometry without shading groups, graph the connections and check or remove this item: {0} (there may be more than one)'
                        .format(obj))

            try:
                pm.mel.eval(convertString)
            except:
                pm.warning('Something went wrong or you canceled')

        return convertString
예제 #48
0
def create_new_node(nodeType, nodeName=None, parent=None, nonkeyable=True):
    node = pm.createNode(nodeType)

    if 'shape' in pm.nodeType(node, inherited=True):
        # This is a shape node.  Move up to the transform node.
        node = node.getTransform()

    if nodeName:
        node = pm.rename(node, nodeName)

    if parent:
        node = pm.parent(node, parent, r=True)[0]

    if nonkeyable:
        maya_helpers.lock_trs(node, 'unkeyable')

    return node
예제 #49
0
def getAOVsInNetwork(rootNode):
    '''
    returns a map from PyNode to aovs
    
    the aov list contains all registered aovs for that node type, regardless of whether
    they are currently enabled in the globals 
    '''
    results = {}
    for node in pm.listHistory(rootNode, pruneDagObjects=True):
        # TODO: Create a general method to assign AOVs of hidden nodes
        # lambert shader has only translator registered so this is a Lambert Maya node and does not have an AOV tab
        if pm.nodeType(node) == "lambert":
            results[node] = [u'direct_diffuse', u'indirect_diffuse']
        else:
            # TODO: cache this result
            results[node] = [node.attr(at).get() for (aov, at, type) in aovs.getNodeGlobalAOVData(node.type())]
    return results
예제 #50
0
def createTranslatorMenu(node, label=None, nodeType=None, default=None, optionMenuName=None):
    '''
    convenience function for creating a TranslatorControl and attaching it to a non-AE UI
    '''
    if nodeType is None:
        nodeType = pm.nodeType(node)
    kwargs = {}
    if label is not None:
        kwargs['label'] = label
    if optionMenuName:
        kwargs['optionMenuName'] = optionMenuName
    if default:
        registerDefaultTranslator(nodeType, default)
    trans = TranslatorControl(nodeType, **kwargs)
    trans._setToChildMode()
    trans._doSetup(node + '.aiTranslator')
    return trans
예제 #51
0
def transfertSkinCluster():
    oOldSelection = pm.selected()
    _oSource = [oOldSelection[0]]
    _oTarget = oOldSelection[1:]
    oJoints = []
    #Check if there a source mesh
    if len(_oSource) < 1:
        pm.displayWarning('You need to have a source mesh')
    elif len(_oTarget) < 1:
        pm.displayWarning('You need to have a target mesh')
    else:
        #Check if there a skinCluster on the mesh. And add joints of the skinCluster to the lists
        try:
            oJoints.extend(pm.skinCluster(_oSource, query=True,
                                          influence=True))
        except:
            print "Exception: it doesn't appear to have a skinCluster."
        #Warnings : check if in the lists oJoints there's objects that are not joints
        oJointSkin = []
        for o in oJoints:
            if pm.nodeType(o) == 'joint':
                oJointSkin.append(o)
            else:
                pm.warning(
                    "removed the influence of {0} beacuse it's not a joint type object"
                    .format(o))

        #Getting skinCluster from the source mesh
        oSkinClusterSource = GetSkinCluster(_oSource[0])

        #Skin the new mesh and copy weight from the source mesh
        for each in _oTarget:
            print each
            pm.select(clear=True)
            pm.select(oJointSkin)
            pm.select(each, add=True)
            oNewSkinCluster = pm.skinCluster(toSelectedBones=True)
            print 'Transfert DONE'
            pm.copySkinWeights(sourceSkin=oSkinClusterSource,
                               destinationSkin=oNewSkinCluster,
                               influenceAssociation='oneToOne',
                               noMirror=True)
            print 'copy weight DONE'

    pm.select(oOldSelection)
예제 #52
0
파일: core.py 프로젝트: ordinc/rigbits
def get_driver_keys(driverAttr,
                    firstKey=None,
                    prevKey=None,
                    nextKey=None,
                    lastKey=None):
    """
    Returns a list of Driver key values for the given driverAttr.

    If all optional arguments are None, will return list of all values

    Arguments:
        driverAttr (PyNode.Attribute): Driver Ctl.attr
        firstKey (bool):
        prevKey (bool):
        nextKey (bool):
        lastKey (bool):

    Returns:
        List (If all optional None) - List of driver key values
        float (If one specified) - The float value for the driver on that key.
    """
    dirver_con = pm.listConnections(driverAttr)

    keys_list = []
    if len(dirver_con) > 0:
        for con in dirver_con:
            if pm.nodeType(con) in SDK_ANIMCURVES_TYPE:
                SDK_dict = sdk_io.getSDKInfo(con)
                for key in SDK_dict["keys"]:
                    if key[0] not in keys_list:
                        keys_list.append(key[0])

        if firstKey:
            return keys_list[0]

        if prevKey:
            return next_smallest(driverAttr.get(), keys_list)

        if nextKey:
            return next_biggest(driverAttr.get(), keys_list)

        if lastKey:
            return keys_list[-1]
        else:
            return keys_list
예제 #53
0
def yeticonnectAttr(typename,yetishapesr,yetishapetr):
    yetinodes=[]
    if yetishapesr!=[] and yetishapetr!=[]:
        yeticonnects = yetishapesr.listConnections(c=1,type=typename,plugs=1)
        if yeticonnects!=[]:
            for yeticonnect in yeticonnects:
                yeticonnectsr = yeticonnect[0]
                yeticonnecttr = yeticonnect[1]
                yetinode = yeticonnect[1].split(".")[0]
                pm.connectAttr( yeticonnectsr.replace(str(yetishapesr),str(yetishapetr)),yeticonnecttr,f=1)
                if pm.nodeType(yetinode)=="pgYetiMaya":
                    yetiimps = pm.pgYetiGraph(yetinode,listNodes=True,type="import") 
                    if yetiimps!=[]:
                        for yetiimp in yetiimps:
                            if pm.pgYetiGraph(yetinode,node=yetiimp,param="type",getParamValue=1)==0:
                                pm.pgYetiGraph(yetinode,node=yetiimp,param="geometry",setParamValueString=yetishapetr.split("|")[-1].split(":")[-1])
                yetinodes.append(yetinode)
    return yetinodes
예제 #54
0
    def get_output_geo(self):
        self.shader_geo_scroll_list.removeAll()
        selected_material = self.shader_scroll_list01.getSelectItem()[0]
        my_mat = self.mat_dict[selected_material]

        shading_engine = my_mat.shadingGroups()[0]

        shading_engine_inputs = shading_engine.inputs()

        for input in shading_engine_inputs:

            try:
                shape_node = input.getShape()
                node_type = pm.nodeType('%s' % (shape_node))
                if node_type == 'mesh' or node_type == 'nurbsSurface':
                    self.shader_geo_scroll_list.append('%s' % (input))
            except:
                pass
예제 #55
0
    def getVrayMeshlightLightLink(self, vrayMeshLight):
        '''Accept vrayMeshLight as Param and traverse the connections to return corresponding lightlink node'''

        pm.select(cl=True)

        #get list of all connections of type transform for vray meshlight
        lightConnectionsList = vrayMeshLight.listConnections(t='transform',
                                                             et=True)
        pm.select(cl=True)

        #iterate over lightconnectionsList and check children, return if child is of type vrayLightLink
        for obj in lightConnectionsList:
            try:
                if (len(obj.getChildren()) == 1 and pm.nodeType(
                        obj.getChildren()[0]) == 'VRayLightMeshLightLinking'):
                    return obj.getChildren()[0]
            except:
                pass
예제 #56
0
def get_shapes(items=None, shape_filter=('mesh', 'nurbsCurve')):
    """
    Get all shapes from the item list. If none given will use the user selection.

    :param list items: PyNodes to operate on. If none given will use selection.
    :param list shape_filter: Whitelist filter for acceptable shape types.
    :return: List of all the shapes as PyNodes.
    :rtype: list[PyNode]
    """
    items = pm.ls(sl=True) if not items else items

    all_shapes = []
    for item in items:
        for shape in pm.listRelatives(item, shapes=True):
            if pm.nodeType(shape) in shape_filter:
                all_shapes.append(shape)

    return all_shapes
예제 #57
0
def _setSetJointLabelFromName(node):

    if pymel.nodeType(node) == 'joint':
        baseName = None
        side = 0
        left = 1
        right = 2
        currentName = node.nodeName(stripNamespace=True)

        if currentName[0:2] == 'r_':
            side = right
            baseName = currentName[2:]
        elif currentName[0:2] == 'l_':
            side = left
            baseName = currentName[2:]
        elif currentName[0:2] == 'R_':
            side = right
            baseName = currentName[2:]
        elif currentName[0:2] == 'L_':
            side = left
            baseName = currentName[2:]

        elif '_r_' in currentName:
            side = right
            baseName = currentName.replace('_r_', '', 1)

        elif '_l_' in currentName:
            side = left
            baseName = currentName.replace('_l_', '', 1)

        elif '_R_' in currentName:
            side = right
            baseName = currentName.replace('_R_', '', 1)

        elif '_L_' in currentName:
            side = left
            baseName = currentName.replace('_L_', '', 1)

        else:
            baseName = currentName

        node.attr('type').set(18)
        node.side.set(side)
        node.otherType.set(baseName, type='string')
예제 #58
0
def bs_checkNonFreezedVertex(sel=None):
    """
    @ check non freezed vertex of selected geometries.
    Args:
        sel (str): geometries have to check.

    Returns:
            nonFreezedVertexGeometry, nonFreezedVertex.
    """
    if not sel:
        allMesh = pm.ls(typ='mesh')
        allGeoTrans = list()
        for each in allMesh:
            allGeoTrans.append(each.getParent())
        # set all transforms.
        sel = list(set(allGeoTrans))
    nonVertFreezedGeo = []
    nonFreezedVert = []
    newSel = []
    for each in sel:
        latticeGeo = False
        for eachHist in pm.listHistory(each, pdo=True):
            if pm.nodeType(eachHist) == 'ffd':
                latticeGeo = True
        if not latticeGeo:
            newSel.append(each)
    for each in newSel:
        allVertNumbers = pm.modeling.polyEvaluate(each, v=True)
        for v in xrange(allVertNumbers):
            xPoint = pm.getAttr('{0}.vtx[{1}].pntx'.format(each, v))
            yPoint = pm.getAttr('{0}.vtx[{1}].pnty'.format(each, v))
            zPoint = pm.getAttr('{0}.vtx[{1}].pntz'.format(each, v))
            if xPoint == 0 and yPoint == 0 and zPoint == 0:
                pass
            else:
                nonVertFreezedGeo.append(each)
                nonFreezedVert.append('{0}.vtx[{1}]'.format(each, v))
    print nonVertFreezedGeo
    print nonFreezedVert
    if nonVertFreezedGeo:
        return list(set(nonVertFreezedGeo)), nonFreezedVert
    else:
        return False
예제 #59
0
    def printNode(self):
        ''' 노드 목록 출력 '''
        # 내보낼 목록 선택
        sel = pm.selected()

        # 선택된게 없으면 에러
        if not sel:
            raise AttributeError(u'출력할 노드 목록의 일부를 선택하세요.')

        # prefix 처리
        # 정의된 prefix가 없으면 "", 있으면 prefix 끝에 "_"추가
        prefix = self.getPrefix() + "_" if self.getPrefix() else ""

        # 루트들 선택
        roots = []
        for node in sel:
            roots.append(node.root())
        pm.select(roots, hi=True)

        # 다시한번 선택
        sel = pm.selected()

        # 아이템들 스트링형식으로 집어넣음 (조인트와 트랜스폼 노드만)
        result = []
        for node in sel:
            if pm.nodeType(node) in ['transform', 'joint']:

                # prefix가 제외된 노드이름
                nodeName = node.name().replace(prefix, '')

                # 결과 추가
                result.append('"%s", ' % nodeName)

        # 마지막 아이템에서 ', '을 삭제
        if result:
            result[-1] = result[-1][:-2]

        # prefix, subfix 추가
        result.insert(0, '"node":[')
        result.append(']')

        # 내용 출력
        print ''.join(result)
예제 #60
0
def orient_node(sel_jnt, sel_node):
    """ Get the node, joint and nodes type which is joint or not to implement reset transformation.
    :param sel_jnt: The selected joint to get the orientation.
    :param sel_node: The selected node to be oriented.
    :return: None
    """
    pm.select(sel_node, r=True)
    node_type = pm.nodeType(str(sel_node))
    pm.parent(sel_node, sel_jnt)
    if node_type == 'joint':
        pm.setAttr(sel_node + '.translateX', 0)
        pm.setAttr(sel_node + '.translateY', 0)
        pm.setAttr(sel_node + '.translateZ', 0)
        pm.setAttr(sel_node + '.jointOrientX', 0)
        pm.setAttr(sel_node + '.jointOrientY', 0)
        pm.setAttr(sel_node + '.jointOrientZ', 0)
    else:
        pm.makeIdentity()
    pm.select(cl=True)