Exemple #1
0
def triangulateMesh(isObj, simplify, smoothe):
	if isObj and not cmds.objExists('triObj'):
		cmds.select(baseObject)
		cmds.duplicate(baseObject, name = "triObj")
		cmds.select('triObj')

		if smoothe:
			cmds.polySmooth('triObj', c=smoothe)
			cmds.polyReduce(ver = 1)
			cmds.polyReduce(ver = 1)

		if simplify > 0:
			cmds.polyReduce(ver = 1, p = simplify)

		num_faces = cmds.polyEvaluate('triObj', f=True)
		
		print "Triangulating faces..."
		#iterate over faces
		face_i = 0
		while face_i < num_faces:
			if ((num_faces - face_i) % 5 == 0):
				print "Triangulate check: Approximately " + str(num_faces - face_i) + " faces remaining...."
			face = cmds.select('triObj.f['+ str(face_i)+']')		
			verts = getCorners(isObj,face_i)
			if not isCoplanar(verts):
				cmds.polyTriangulate('triObj.f['+ str(face_i)+']')
				num_faces = cmds.polyEvaluate('triObj', f=True)
			face_i +=1
Exemple #2
0
 def changeNumberOfJoints(self, *args):
     self.blueprint_UI_instance.deleteScriptJob()
     
     joints = self.getJoints()
     numJoints = len(joints)
     newNumJoints = cmds.intField(self.numberOfJointsField, q=True, value=True)
     
     startPos = cmds.xform(self.getTranslationControl(joints[0]), q=True, ws=True, t=True)
     endPos = cmds.xform(self.getTranslationControl(joints[numJoints-1]), q=True, ws=True, t=True)
     
     hookObject = self.findHookObjectForLock()
     
     rotationOrder = cmds.getAttr(joints[0] + ".rotateOrder")
     sao_local = cmds.getAttr(self.moduleNamespace+":module_grp.sao_local")
     sao_world = cmds.getAttr(self.moduleNamespace+":module_grp.sao_world")
     
     self.delete()
     
     newInstance = Spline(self.userSpecifiedName, hookObject, newNumJoints, startPos, endPos)
     newInstance.install()
     # We have to refer to the new instance stored in memory
     newJoints = newInstance.getJoints()
     
     cmds.setAttr(newJoints[0]+".rotateOrder", rotationOrder)
     
     cmds.setAttr(newInstance.moduleNamespace+":module_grp.sao_local", sao_local)
     cmds.setAttr(newInstance.moduleNamespace+":module_grp.sao_world", sao_world)
     
     self.blueprint_UI_instance.createScriptJob()
     
     cmds.select(newInstance.moduleNamespace+":module_transform", replace=True)
Exemple #3
0
	def publish(self, makePreview = False, tags = '', notes = '' ):
		"""export shader to library"""
		shad = mn.Node( self.name )
		mc.select( shad.shader, ne = True )
		exportPath = self.path + self.name + '.ma'
		if self.published: #Make a bakup
			self.saveVersion()
			print 'make a f*****g backup!'
		else:
			os.makedirs( self.path )
		self._savedata( tags, notes, None )
		n = mn.Node( self.name )
		"""
		if not n.a.id.exists:
			n.a.id.add()
			print self.id
			n.a.id.v = self.id
		if not n.a.category.exists:
			n.a.category.add()
			n.a.category = self.category
		if not n.a.path.exists:
			n.a.path.add()
			n.a.path.v = exportPath
		"""
		mc.file( exportPath , force = True, options = "v=0", typ = "mayaAscii", pr = True, es = True )
		self.settexturespath( self.path + 'Textures/', exportPath )
		previewtime = 0
		if makePreview:
			print 'creating preview'
			previewtime = self.preview()
def m(p, _t=None):
    if not _t:
        _t = mc.ls(sl=1)

    for i in range (0,len(_t)):
        mc.select(_t[i])
        mc.move(p[0],p[1],p[2])
Exemple #5
0
def orderNextTo(objects, target):
    '''
    places 'objects'/[objects] next to 'target' in hierarchy and ordering

    I found most of the time I use the get/setOrder stuff to relocate objs to another
    with parenting and if in world and hierarchy Nr and all that shit.. this does it inline
    '''
    if not isinstance(objects, list):
        objects = [objects]
    handledObjs = []
    targetParent = m.listRelatives(target, parent=True, fullPath=True)
    targetNr = getOrder(target)
    # handle each object on its own no matter how its parented
    for o in objects:
        oParent = m.listRelatives(o, parent=1, fullPath=1)
        if oParent != targetParent:
            if targetParent:
                o = m.parent(o, targetParent)[0]
            else:
                o = m.parent(o, world=1)[0]
        # else if in same hierarchy already decrease count if obj is before target
        elif getOrder(o) <= targetNr:
            targetNr -= 1
        handledObjs.append(o)
    setOrder(handledObjs, targetNr + 1)
    m.select(handledObjs)
    return handledObjs
Exemple #6
0
    def create(self, parent_transform, style):
        """Create shape"""

        self.parent = parent_transform

        # Add style
        curve_data = Style()[style]
        for curve in curve_data:
            temp = cmds.curve(name="temp_curve", d=1, p=curve['points'], k=curve['knot'])

            # Parent curve under transform
            shapes = cmds.listRelatives(temp, shapes=True)
            for shape_index, shape in enumerate(shapes):
                cmds.parent(shape, parent_transform, shape=True, r=True)

                # Rename shape to be tidy
                new_shape = cmds.rename(shape, "%s%s" % (self.name, shape_index))
                self.nodes.append(new_shape)

            # Remove temp transform
            cmds.delete(temp)

        # Set colors
        self.set_color(name.get_position(self.parent))

        # Match values
        self.scale_shapes(self.scale)
        self.rotate_shapes(self.rotate)

        # Clear selection
        cmds.select(cl=True)
Exemple #7
0
def edgeLoopWeights(edgeList):
    """
    """
    # Check Edge List
    if not edgeList: raise Exception('Invalid or empty edge list!')
    edgeList = cmds.filterExpand(edgeList, ex=True, sm=32) or []
    if not edgeList: raise Exception('Invalid edge list! List of polygon edges required...')

    # Get Mesh from Edges
    mesh = list(set(cmds.ls(edgeList, o=True) or []))
    if len(mesh) > 1:
        raise Exception('Edges from multiple mesh shapes were supplied! ' + str(mesh))
    mesh = mesh[0]

    for edge in edgeList:
        # Get Edge ID
        edgeID = glTools.utils.component.index(edge)

        # Get Vertices from Edge
        edgeVerts = cmds.polyListComponentConversion(edge, fe=True, tv=True)

        # Get Average Vertex Weights
        cmds.select(edgeVerts)
        glTools.tools.copyPasteWeights.averageWeights()

        # Select Edge Loop Vertices
        cmds.polySelect(mesh, edgeLoop=edgeID)
        loopEdges = cmds.ls(sl=1, fl=1)
        loopVerts = cmds.polyListComponentConversion(loopEdges, fe=True, tv=True)
        cmds.select(loopVerts)
        glTools.tools.copyPasteWeights.pasteWeights()

    # Return Result
    return mesh
	def __init__(self) :

		# create a promptDialog for the base group name of our mesh this will help to
		# avoid name conflicts, may be good to modify this at some stage to check if mesh
		# exists and prompt to replace data / key
		result = cmds.promptDialog(
															title='Name',
															message='Enter Name for import',
															button=['OK', 'Cancel'],
															defaultButton='OK',
															cancelButton='Cancel',
															dismissString='Cancel')

		# if ok was pressed lets process the data
		if result == 'OK':
			# first we get the text entered by the user
			self.m_text = cmds.promptDialog(query=True, text=True)
			# now get the obj file to import
			self.m_objFileName=cmds.fileDialog2(caption="Please select obj file to import",fileFilter="*.obj", fm=1)

			cmds.file(self.m_objFileName,i=True,type="OBJ",ns=self.m_text)
			# now the xml file
			basicFilter = "*.xml"
			self.m_pointBakeFile=cmds.fileDialog2(caption="Please select xml file to import",fileFilter=basicFilter, fm=1)
			# select the object imported
			print self.m_pointBakeFile
			cmds.select("%s:Mesh"%(self.m_text))
			# and pass control back to the parser
			parser = xml.sax.make_parser()
			parser.setContentHandler(ParseHandler("%s:Mesh"%(self.m_text)))
			parser.parse(open(str(self.m_pointBakeFile[0]),"r"))
	def crear(self):
			
		#Tipo 1
		if(self.edififio_seleccionado == 0):
			cmds.polyCube(w = self.anchura, d = self.Largo, h = self.Anchura_random, n =  str(self.EdificioName))
			
		#Tipo 2
		elif(self.edififio_seleccionado == 1):
		
			cmds.polyCube(w = self.anchura, d = self.Largo, h = self.Anchura_random, n =  str(self.EdificioName))
			
			#Modificamos las caras aleatoriamente
			for i in range(0, random.randrange(0,3)):
				cmds.polyExtrudeFacet(str(self.EdificioName) + ".f[1]", kft = False, ls = (0.8, 0.8, 0))
				cmds.polyExtrudeFacet(str(self.EdificioName) + ".f[1]", kft = False, ltz = 30)	
			
		#Tipo 3	
		else:
			cmds.polyCube(w = self.anchura, d = self.Largo, h = self.Anchura_random, sx = self.xDiv, sy = self.yDiv, sz = self.zDiv, n = str(self.EdificioName))			
			
			sides = []
			
			#Seleccionamos el edificio
			for i in range(0, 8):
				if(i != 1 and i != 3):
					sides.append(str(self.EdificioName) + ".f[" + str(self.xDiv * self.yDiv * i) + ":" + str((self.xDiv * self.yDiv * (i+1)) - 1) + "]")
			
			#Modificamos las caras para generar ventanas
			cmds.polyExtrudeFacet(sides[0], sides[1], sides[2], sides[3], sides[4], sides[5], kft = False, ls = (0.8, 0.8, 0))
			windows = cmds.ls(sl = True)
			cmds.polyExtrudeFacet(windows[1], windows[2], windows[3], kft = False, ltz = -0.2)
			cmds.select( self.EdificioName)
Exemple #10
0
 def orderedVertsEdgeLoop(cls):
     """
     #select 2 adjasent vertices ( corner and direction vertex)
     #list vertexes on edge loop( for curves )   
     """
     myVert = cmds.ls( os=1, fl=1 )
     if len(myVert)==2:
         firstVert = myVert[0]
         secondVert = myVert[1]
         
         cmds.select (firstVert,secondVert, r =1)
         mel.eval('ConvertSelectionToContainedEdges')        
         firstEdge = cmds.ls( sl=1 )[0]
         
         cmds.polySelectSp( firstEdge, loop =1 )
         edges = cmds.ls( sl=1, fl=1 )
         edgeDict = cls.getEdgeVertDict(edges) #{edge: [vert1, vert2], ...}
         ordered = [firstVert, secondVert]
         for i in range( len(edges)-2 ):            
             del edgeDict[firstEdge]
             #print edgeDict
             for x, y in edgeDict.iteritems():
                 if secondVert in y:                    
                     xVerts = y
                     xVerts.remove(secondVert)
                     firstEdge = x
         
             secondVert = xVerts[0]
             ordered.append( secondVert )
         return ordered
     
     else:
         print 'select 2 adjasent vertex!!'            
 def checkSelObj(self):
     """检查选中的物体是否为mesh节点
 
     Description:
         选有物体且所选的是mesh节点,返回True
         没选物体或所选物体类型不符合,则返回False
 
     Arguments:
         无
 
     Returns:        
         result = True:通过检查
         result = False:没通过检查,释放所有选择
     """
     selObj = cmds.ls(sl =True)
     lenOfSel = len(selObj)
     result = True
     if lenOfSel < 1:
         cmds.confirmDialog(title = "Warning", message = "Please Select Objects!", button = "OK", defaultButton = "OK")
         result = False
     else:
         for eachObj in selObj:
             if cmds.nodeType(eachObj) != "transform":
                 cmds.confirmDialog(title = "Warning", message = "There Has An Object With Incorrect Type!", button = "OK", defaultButton = "OK")
                 cmds.select(deselect = True)  #去除所有选择
                 result = False
                 break
     
     return result
    def _publish_gpu_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb):
        """
        Export a gpu cache for the specified item and publish it  to Shotgun.
        """
        group_name = item["name"].strip("|")
        debug(app = None, method = '_publish_gpu_for_item', message = 'group_name: %s' % group_name, verbose = False)
        tank_type = output["tank_type"]
        publish_template = output["publish_template"]        
                
        # get the current scene path and extract fields from it using the work template:
        scene_path = os.path.abspath(cmds.file(query=True, sn= True))
        fields = work_template.get_fields(scene_path)
        publish_version = fields["version"]

        # update fields with the group name:
        fields["grp_name"] = group_name

        ## create the publish path by applying the fields with the publish template:
        publish_path = publish_template.apply_fields(fields)
        #'@asset_root/publish/gpu/{name}[_{grp_name}].v{version}.abc'
        gpuFileName = os.path.splitext(publish_path)[0].split('\\')[-1] 
        fileDir = '/'.join(publish_path.split('\\')[0:-1])
        debug(app = None, method = '_publish_gpu_for_item', message = 'gpuFileName: %s' % gpuFileName, verbose = False)
        
        ## Now fix the shaders
        shd.fixDGForGPU()
        
        if cmds.objExists('CORE_ARCHIVES_hrc'):
            cmds.setAttr('CORE_ARCHIVES_hrc.visiblity', 0)
        
        if cmds.objExists('ROOT_ARCHIVES_DNT_hrc'):
            cmds.setAttr('ROOT_ARCHIVES_DNT_hrc.visiblity', 0)
                                       
        ## build and execute the gpu cache export command for this item:
        try:
            print '====================='
            print 'Exporting gpu now to %s\%s' % (fileDir, gpuFileName)
            #PUT THE FILE EXPORT COMMAND HERE
            cmds.select(clear = True)
            for geo in cmds.listRelatives(group_name, children = True):
                if 'geo_hrc' in geo:
                    geoGroup = str(group_name)
                    debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False)
                
            cmds.select(geoGroup)
            
            debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False)
            debug(app = None, method = '_publish_gpu_for_item', message = "gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup), verbose = False)
            
            mel.eval("gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup))

            print 'Finished gpu export...'
            print '====================='
            
            if cmds.objExists('dgSHD'):            
                ## Now reconnect the FileIn nodes
                for key, var in filesDict.items():
                    cmds.connectAttr('%s.outColor' % key, '%s.color' % var)
        except Exception, e:
            raise TankError("Failed to export gpu cache file")
Exemple #13
0
    def mirrorJoints(self, topJoint = '', prefix = ['l_', 'r_']):
        """
        mirroring joint, top node needs to contain 'l_' as prefix
        """

        lPrefix = prefix[0]
        rPrefix = prefix[1]
        
        cmds.select(cl = True)
        cmds.joint(n = 'temp_jnt')
        cmds.select(topJoint, r = True)
        cmds.select('temp_jnt', tgl = True)
        self.toggleSelect(topJoint, 'temp_jnt')
        cmds.parent()
        
        cmds.select(topJoint, r = True)
        cmds.mirrorJoint(mirrorYZ = True, mirrorBehavior  = True, myz = True, searchReplace =  prefix)
        
        rJoint = rPrefix + topJoint.split(lPrefix)[-1]
        cmds.select(topJoint, rJoint)
        cmds.parent(w = True)
        
        cmds.delete('temp_jnt')
        
        return rJoint
Exemple #14
0
def select_node_by_type(nodeType):
    sel = cmds.ls(sl=True, l=True)
    sel_ad = cmds.listRelatives(sel, ad=True, f=True) + sel
    cmds.select(cl=True)
    for node in sel_ad:
        if cmds.nodeType(node) == nodeType:
            cmds.select((cmds.listRelatives(node, p=True)), add=True)
Exemple #15
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
def maya_move(angular_velocity, time_step):
            
    objects = cmds.ls(sl=True)
    if objects == []:
        print('* Please select at least an object.')
        return
        
    trajectory = cmds.ls('trajectory')
    
    for i, o in enumerate(objects):
        x = cmds.getAttr(o + '.translateX')
        y = cmds.getAttr(o + '.translateY')
        z = cmds.getAttr(o + '.translateZ')
    
        loc = [x, y, z]
        state = make_state(loc)
                
        state = simulate_circle(state, angular_velocity, time_step)
        
        old_loc = loc
        loc = get_location(state)
        
        cmds.select(o)
        cmds.move(loc[0], loc[1], loc[2])
        
        # draw trajectory for the first object
        if i == 0:
            if trajectory == []:
                cv = cmds.curve(point=[old_loc, loc], degree=1)                
                cmds.rename(cv, 'trajectory')
            else:
                cmds.curve('trajectory', point=[loc], degree=1, append=True)
        
    # keep all objects selected
    cmds.select(objects)
Exemple #17
0
def select_samename_node(name):
    sel = cmds.ls(sl=True)
    cmds.select(cl=True)
    sel_hr = cmds.listRelatives(sel, ad=True) + sel
    for node in sel_hr:
        if node.count(name):
            cmds.select(node, add=True)
def main():
	mm.eval('selectCurveCV("all");')
	sel = mc.ls(sl=1, fl=1)
	grpname = (sel[0].split('.'))
	grpname = grpname[0]+"_grp"
	grp = mc.group(em=1, n=grpname)
	
	for i in sel:
		iname = i.replace('[', '')
		iname = iname.replace(']','')
		iname = iname.replace('.','_')
		
		locname = iname+"_loc"
		clusname = iname+"_clus"	
		
		mc.select(i, r=1)
		print "here"
		cluster = mc.cluster(n=clusname)
	
		location = mc.xform(cluster, q=1, ws=1, sp=1)
		print location
		locator = mc.spaceLocator(n=locname, p=(location[0], location[1], location[2]))
		mc.xform(locator, cp=1)
		set_vis = clusname+"Handle.visibility"
		mc.setAttr(set_vis, 0)
		mc.parent(cluster, locator)
		mc.parent(locator, grp)
		
		shape = mc.listRelatives(locator)
		mc.setAttr((shape[0]+".overrideEnabled"),1)
		mc.setAttr((shape[0]+".overrideColor"),17)
Exemple #19
0
def build(numBindJoints=6, numSpans=None, name='', numSkinJoints=3, width=None):
    '''
    builds a nurbs ribbon
    If width is not specified, width will be set to numBindJoints
    If numSpans is not specified, it will be set to numBindJoints
    
    '''
    if not width:
        width = numBindJoints
    if not numSpans:
        numSpans = numBindJoints
    
    main_grp = cmds.group(empty=1, name=(name + '_grp'))
    plane = cmds.nurbsPlane(axis=(0, 1, 0), ch=0, lengthRatio=(1.0 / width), w=width, u=numSpans, name=(name + '_nurbsPlane'))[0]
    cmds.parent(plane, main_grp)
    
    # Creat Skin joints
    skinJoints = []
    skinJointPositions = common.pointsAlongVector( start=[width*.5, 0, 0], end=[width*-.5, 0, 0], divisions=(numSkinJoints-1) )
    for index in range(len(skinJointPositions)):
        cmds.select(main_grp)
        j = cmds.joint(position = skinJointPositions[index], name=(name + '_' + str(index) + '_jnt'))
        skinJoints.append(j)
        
    # Add skinning to ribbon
    cmds.skinCluster(skinJoints, plane, tsb=1, name=(plane + '_skinCluster'))
    cmds.setAttr(plane+'.inheritsTransform', 0)
    
    # Add follicles
    for index in range(numBindJoints):
        f = rivet.build( mesh=plane, paramU=(1.0 / (numBindJoints-1) * index), paramV=0.5, name=(name + '_' + str(index)))
        cmds.parent(f, main_grp)
        j = cmds.joint(name=(name + '_' + str(index) + '_bnd'))
Exemple #20
0
    def confirmJoints(self):
        """   
        draw joints in locator position
        """

        #- Getting Ball and Toe Location
        self.leftHipPos = cmds.xform('l_hip_Adjust_ctl', q = True, ws = True, t = True)
        self.leftKneePos = cmds.xform('l_knee_Adjust_ctl', q = True, ws = True, t = True)
        self.leftAnklePos = cmds.xform('l_ankle_Adjust_ctl', q = True, ws = True, t = True)
        self.leftBallPos = cmds.xform('l_ball_Adjust_ctl', q = True, ws = True, t = True)
        self.leftToePos = cmds.xform('l_toe_Adjust_ctl', q = True, ws = True, t = True)
        self.leftHeelPos = cmds.xform('l_heel_PivotPosition', q = True, ws = True, t = True)
        self.leftSideInPos = cmds.xform('l_sidein_PivotPosition', q = True, ws = True, t = True)
        self.leftSideOutPos = cmds.xform('l_sideout_PivotPosition', q = True, ws = True, t = True)
        
        #duplicate pivots
        cmds.duplicate('l_heel_PivotPosition', n = 'r_heel_PivotPosition', rr =  True)
        cmds.xform('r_heel_PivotPosition', t = [-self.leftHeelPos[0], self.leftHeelPos[1], self.leftHeelPos[2]])
        cmds.duplicate('l_sidein_PivotPosition', n = 'r_sidein_PivotPosition', rr =  True)
        cmds.xform('r_sidein_PivotPosition', t = [-self.leftSideInPos[0], self.leftSideInPos[1], self.leftSideInPos[2]])
        cmds.duplicate('l_sideout_PivotPosition', n = 'r_sideout_PivotPosition', rr =  True)
        cmds.xform('r_sideout_PivotPosition', t = [-self.leftSideOutPos[0], self.leftSideOutPos[1], self.leftSideOutPos[2]])
        
        cmds.select(cl = True)
        print 'leg Parts : ' , self.legParts
        for elem in self.legElement :
            jointPos = cmds.xform(self.left + elem + '_Adjust_ctl', t = True, q = True, ws = True)
            cmds.joint(n = '%s%s_jnt' %(self.left, elem), p = jointPos)
            
        #- orient joint
        cmds.joint(self.lHipJnt, e = True, oj = 'xzy', secondaryAxisOrient = 'yup', ch = True, zso = True)

        #- delete position locators
        cmds.delete(self.legParts)
Exemple #21
0
    def legCleanup(self):
        for lr in self.lrPrefix:
            #- hide heel pivot
            cmds.setAttr('%sheel_PivotPosition.visibility' %lr, 0)

            #- placing extra control
            cmds.select('%sleg_extra_ctl_grp' %lr, r = True)
            cmds.select('%sankle_jnt' %lr, tgl = True)
            cmds.parent()
            
            #- hide attribute
            cmds.setAttr('%sleg_pv_ctl.visibility' %lr, keyable = False, channelBox = False)
            cmds.setAttr('%sleg_ctl.visibility' %lr, keyable = False, channelBox = False)
            
            #- clean up hierarchy
            self.util.group(['%sik_hip_jnt' %lr, '%sfk_hip_jnt' %lr], '%sfkik_leg_jnt_grp' %lr)
            self.util.group(['%ship_jnt' %lr, '%sfkik_leg_jnt_grp' %lr], '%sleg_jnt_grp' %lr)
            
            #- hide stretchIK locator
            cmds.setAttr('%sstretch_leg_grp.visibility' %lr, 0)
                        
        self.util.group(['l_leg_jnt_grp', 'r_leg_jnt_grp'], 'leg_jnt_grp')    
        children = ['l_leg_pv_ctl_grp', 'r_leg_pv_ctl_grp',
                    'l_fk_hip_ctl_grp', 'r_fk_hip_ctl_grp',
                    'l_leg_ctl_grp', 'r_leg_ctl_grp']
        self.util.group(children, 'leg_ctl_grp')
        self.util.group(['l_stretch_leg_grp', 'r_stretch_leg_grp'], 'stretch_leg_grp')
        self.util.group(['l_heel_PivotPosition', 'r_heel_PivotPosition', 'stretch_leg_grp'], 'leg_misc_grp')    
        
        
            
Exemple #22
0
    def _finger_hydraulics(self):
        """Connects the finger hydraulics."""
        for side in ['L', 'R']:
            for finger in ['pointer', 'middle', 'ring']:
                start_jnt = '%s_%sBase_result_%s' % (side, finger, self.nc.joint)
                end_jnt = '%s_%s1_result_%s' % (side, finger, self.nc.joint)

                if finger == 'ring':
                    finger = 'pinky'
                # END if

                start_hydraulic = '%s_%sHydraulicsStart_%s_%s' % (side, finger, self.nc.joint, self.nc.group)
                mid_hydraulic = '%s_%sHydraulicsMid_%s_%s' % (side, finger, self.nc.joint, self.nc.group)
                end_hydraulic = '%s_%sHydraulicsEnd_%s_%s' % (side, finger, self.nc.joint, self.nc.group)

                cmds.select(cl=True)
                start_offset = cmds.group(n='%s_%sBaseOffset_%s' % (side, finger, self.nc.group), empty=True)
                cmds.select(cl=True)
                end_offset = cmds.group(n='%s_%s2Offset_%s' % (side, finger, self.nc.group), empty=True)

                self.c.snap_a_to_b(start_offset, start_hydraulic)
                self.c.snap_a_to_b(end_offset, end_hydraulic)
                cmds.parent(start_offset, start_jnt)
                cmds.parent(end_offset, end_jnt)

                cmds.parent(start_hydraulic, start_offset)
                cmds.parent(end_hydraulic, end_offset)

                try:
                    cmds.parent(mid_hydraulic, '%s_hand_%s' % (side, self.nc.group))
                except Exception as err:
                    print err
 def __init__(self, start_face):
     self.start_face = start_face
     cmds.select(self.start_face)
     self.start_face_sel = cmds.ls(sl=True)
     self.slice_point = self.start_face_sel[0].find('.')
     self.geom_name = self.start_face_sel[0][:int(self.slice_point)]
     self.ordered_list = [self.start_face]
Exemple #24
0
    def mirror_chain(self, side = None):
        #create one temporary joint at the origin
        tmp_jnt = cmds.joint(position = [0, 0, 0])

        #parent the chain to that joint
        cmds.parent(self.fk_joint_names[0], tmp_jnt)

        #mirror the chain and rename the mirrored side
        if side == 'L':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'R'))
        elif side == 'l':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'r'))
        elif side == 'R':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'L'))
        elif side == 'r':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'l'))
        else:
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1)

        #unparent the chain and delete the temporary joint
        cmds.parent(self.fk_joint_names[0], self.mirrored_fk_joint_names[0], world = 1)        
        cmds.delete(tmp_jnt)

        cmds.select(clear = 1)        
        return self.mirrored_fk_joint_names
Exemple #25
0
    def mirror_chain(self, side = None):
        #create one temporary joint at the origin
        tmp_jnt = cmds.joint(position = [0, 0, 0])

        #parent the chain to that joint
        cmds.parent(self.ik_joint_names[0], tmp_jnt)

        #mirror the chain and rename the mirrored side
        if side == 'L':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'R'))
        elif side == 'l':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'r'))
        elif side == 'R':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'L'))
        elif side == 'r':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'l'))
        else:
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1)

        #unparent the chain and delete the temporary joint
        cmds.parent(self.ik_joint_names[0], self.mirrored_ik_joint_names[0], world = 1)        
        cmds.delete(tmp_jnt)

        cmds.select(clear = 1)

        #rename the side of the mirrored effector correctly and store the ik and effector in a list
        mirrored_ik  = self.mirrored_ik_joint_names[0][0] + self.ik_handle_names[-1][1:]
        mirrored_eff = cmds.rename(self.mirrored_ik_joint_names[-1], self.mirrored_ik_joint_names[0][0] + self.ik_handle_names[-1][1:])
        self.mirrored_ik_handle_names = [mirrored_ik, mirrored_eff]
        self.mirrored_ik_joint_names.pop(-1)
Exemple #26
0
def csvWrite():
    """ This is the path where the csv will be written.  Change this to a path on your local machine. """
    path = "R:/System/CSV_files/armCsv.csv" 
    
    """ Open the csv in maya for writing """
    writer = csv.writer(open(path, 'wb'), delimiter=',')
    
    """ Create a new list based off your selection """
    selectionList = cmds.ls(sl=True)
   
    """ Clear the selection """
    cmds.select(clear=True)
  
    for selection in selectionList:
        """ An empty list to hold both the joint names and the positions """
        jointInfo = []
  
        pos = cmds.xform(selection, q=True, t=True, ws=True)
       
        """ Append the name of the locator and it's position to a new list"""  
        """ I am splitting the positions into seperate variables to make things easier when I try read them later """     
        jointInfo.append(selection)
        jointInfo.append(pos[0])
        jointInfo.append(pos[1])
        jointInfo.append(pos[2])
        """ At this point you could use the joint info to build joints """
        """ Write the data to csv """
        writer.writerow(jointInfo)

    """ Print the joint info so you can see what is happening """
    print jointInfo
Exemple #27
0
def cutSkin(mesh, weightThreshold=0.25, reducePercent=None, parentShape=False):
    """
    Extract a per influence proxy mesh from a skinned mesh based on influence weights.
    @param mesh: Mesh to extract faces from
    @type mesh: str
    @param weightThreshold: Influence to use to extract faces
    @type weightThreshold: float
    @param reducePercent: Influence to use to extract faces
    @type reducePercent: int or None
    """
    # Initialize
    startTime = cmds.timerX()
    cmds.undoInfo(state=False)

    # Get Skin Info
    skin = glTools.utils.skinCluster.findRelatedSkinCluster(mesh)
    if not skin:
        print('Cut Skin: Mesh "" has no skinCluster! Skipping...')
        return None

    # Prune Weights
    glTools.utils.skinCluster.lockSkinClusterWeights(skin, lock=False, lockAttr=False)
    pruneWts = glTools.utils.mathUtils.distributeValue(10, rangeStart=0.001, rangeEnd=weightThreshold)
    cmds.select(mesh)
    for wt in pruneWts:
        try:
            mel.eval('doPruneSkinClusterWeightsArgList 1 {"' + str(wt) + '"}')
        except Exception, e:
            print('Prune weight FAILED (' + mesh + ')! ' + str(e))
            break
 def orientJoints(s):
     """
     Face joints in the correct direction.
     """
     sel = cmds.ls(sl=True)
     err = cmds.undoInfo(openChunk=True)
     try:
         markers = s.markers
         joints = markers.keys()
         with ReSeat(joints):
             for j in joints:
                 m = markers[j]
                 if cmds.objExists(m.marker) and cmds.objExists(j):
                     with Isolate(j):
                         m.setJoint()
                         try:
                             cmds.makeIdentity(
                                 j,
                                 apply=True,
                                 r=True) # Freeze Rotations
                         except RuntimeError:
                             pass
                 else: # User deleted marker / joint. Stop tracking.
                     m.removeMarker()
                     del markers[j]
             cmds.select(sel, r=True)
     except Exception as err:
         raise
     finally:
         cmds.undoInfo(closeChunk=True)
         if err: cmds.undo()
def export_static_ogre(*args):
	export_dir = get_export_dir()
	objects = get_objects()
	ogre_mesh_files = []
	if (cmds.file(q=True, sceneName=True)==''):
		print 'Not a valid scene. Try saving it.'
		return False

	if not export_dir:
		print ("Empty Scene? unable to export.")

	else:
		print ('Export Directory:\n  %s\nOgre files\n' % export_dir)
		for ob in objects:
			name = ob
			if cmds.nodeType(ob) == 'transform':
				name = cmds.listRelatives(ob)[0]
			cmds.select(ob, r=True)
			_path = os.path.abspath( export_dir + ('/%s.mesh' % name) )
			ogre_path = _path.replace(os.sep, '/')
			# print ('select %s' % ob)
			print ('     %s' % ogre_path)

			ogre_mesh_files.append(ogre_path)
					  # 'ogreExport -sel -obj -lu mm -scale 1 -mesh \"aaa.mesh\" -shared -v -n -c -t -tangents TANGENT -tangentsplitmirrored;''
			command = 'ogreExport -sel -obj -lu mm -scale 0.1 -mesh \"%s\" -shared -n -c -t -tangents TANGENT -tangentsplitmirrored;' % ogre_path
			mm.eval(command)
		
		cmds.select(objects)
		print 'fixing materials'
		fix_xml_material_names(ogre_mesh_files)
def selectNode():
    """
    Select node from reference edits UI.
    """
    # Get Selected Ref Node
    refNode = cmds.textScrollList('refEdits_refListTSL', q=True, si=True)
    if not refNode: return
    refNS = glTools.utils.reference.getNamespace(refNode[0]) + ':'

    # Get Selected Nodes
    nodeList = cmds.textScrollList('refEdits_nodeListTSL', q=True, si=True)
    if not nodeList: return

    # Select Nodes
    selNodes = []
    for node in nodeList:

        # Check Node
        editNode = node
        if not cmds.objExists(node): node = node.split('|')[-1]
        if not cmds.objExists(node): node = refNS + node
        if not cmds.objExists(node): raise Exception('Reference edit node "' + editNode + '" not found!')

        # Append to Selection List
        selNodes.append(node)

    # Select Node
    if selNodes: cmds.select(selNodes)
def generate_simple_ik_leg(is_using_ball):
    ik_jnts = [] # For changing its color later
    jnt_tag_length = len(settings.get('jnt_tag'))
    # ============================= Start of Main Function =============================
    hip_jnt_start_rp_fk = stored_joints.get("hip_jnt") # Hip
    if len(cmds.listRelatives(hip_jnt_start_rp_fk, type='joint') or []) > 0: # Check if hip has children
        knee_jnt_middle_rp_fk = cmds.listRelatives(hip_jnt_start_rp_fk, type='joint')[0] # Knee
    ankle_jnt_end_rp_fk = stored_joints.get("ankle_jnt") # Ankle
    
    if is_using_ball: 
        ball_jnt_end_sc1_fk = stored_joints.get("ball_jnt") # Ball
        if len(cmds.listRelatives(ball_jnt_end_sc1_fk, type='joint') or []) > 0: # Check if ball has children
            toe_jnt_end_sc2_fk = cmds.listRelatives(ball_jnt_end_sc1_fk, type='joint')[0] # Toe

    # Creates IK Skeleton
    start_joint_rp_ik = cmds.duplicate(hip_jnt_start_rp_fk, po=True, name = hip_jnt_start_rp_fk[:-jnt_tag_length] + "_IK_Jnt") # Create IK Hip
    middle_joint_rp_ik = cmds.duplicate(knee_jnt_middle_rp_fk, po=True, name = knee_jnt_middle_rp_fk[:-jnt_tag_length] + "_IK_Jnt") # Create IK Knee
    end_joint_rp_ik = cmds.duplicate(ankle_jnt_end_rp_fk, po=True, name = ankle_jnt_end_rp_fk[:-jnt_tag_length] + "_IK_Jnt") # Create IK Ankle
    ik_jnts.append(start_joint_rp_ik)
    ik_jnts.append(middle_joint_rp_ik)
    ik_jnts.append(end_joint_rp_ik)
    
    if is_using_ball: 
        end_joint_sc1_ik = cmds.duplicate(ball_jnt_end_sc1_fk, po=True, name = ball_jnt_end_sc1_fk[:-jnt_tag_length] + "_IK_Jnt") # Create IK Ball
        end_joint_sc2_ik = cmds.duplicate(toe_jnt_end_sc2_fk, po=True, name = ball_jnt_end_sc1_fk[:-jnt_tag_length] + "_IK_Jnt") # Create IK Toe
        ik_jnts.append(end_joint_sc1_ik)
        ik_jnts.append(end_joint_sc2_ik)

    # Recreate Hierarchy (IK Skeleton)
    if len(cmds.listRelatives(start_joint_rp_ik, parent=True) or []) != 0:  # Check if parent is already world
        cmds.parent( start_joint_rp_ik, world=True)
    cmds.parent( middle_joint_rp_ik, start_joint_rp_ik )
    cmds.parent( end_joint_rp_ik, middle_joint_rp_ik )
    
    if is_using_ball: 
        cmds.parent( end_joint_sc1_ik, end_joint_rp_ik )
        cmds.parent( end_joint_sc2_ik, end_joint_sc1_ik )

    # Parent Constraints
    start_joint_rp_ik_pConstraint = cmds.parentConstraint( start_joint_rp_ik, hip_jnt_start_rp_fk )
    middle_joint_rp_ik_pConstraint = cmds.parentConstraint( middle_joint_rp_ik, knee_jnt_middle_rp_fk )
    end_joint_rp_ik_pConstraint = cmds.parentConstraint( end_joint_rp_ik, ankle_jnt_end_rp_fk )
    if is_using_ball: 
        end_joint_sc1_ik_pConstraint = cmds.parentConstraint( end_joint_sc1_ik, ball_jnt_end_sc1_fk )

    # Create Main Rotate-Plane IK Solver
    ikHandle_name = start_joint_rp_ik[0][:-jnt_tag_length] + 'RP_ikHandle'
    ikHandle_rp = cmds.ikHandle( n=ikHandle_name, sj=start_joint_rp_ik[0], ee=end_joint_rp_ik[0], sol='ikRPsolver')

    # Create Ankle to Ball Single-Chain IK Solver
    if is_using_ball: 
        ikHandle_name = end_joint_rp_ik[0][:-jnt_tag_length] + 'SC_ikHandle'
        ikHandle_sc_ball = cmds.ikHandle( n=ikHandle_name, sj=end_joint_rp_ik[0], ee=end_joint_sc1_ik[0], sol='ikSCsolver')
        ikHandle_name = end_joint_sc2_ik[0][:-4] + 'SC_ikHandle'
        ikHandle_sc_toe = cmds.ikHandle( n=ikHandle_name, sj=end_joint_sc1_ik[0], ee=end_joint_sc2_ik[0], sol='ikSCsolver')
        

    if settings.get("using_custom_ik_ctrl"):
        ik_control = settings.get("custom_ik_ctrl_name")
    else:
        ik_control = cmds.curve(name = start_joint_rp_ik[0][:-jnt_tag_length] + 'Ctrl', p=[[-0.569, 0.569, -0.569], [-0.569, 0.569, 0.569], \
                    [0.569, 0.569, 0.569], [0.569, 0.569, -0.569], [-0.569, 0.569, -0.569], [-0.569, -0.569, -0.569], \
                    [0.569, -0.569, -0.569], [0.569, 0.569, -0.569], [0.569, 0.569, 0.569], [0.569, -0.569, 0.569], \
                    [0.569, -0.569, -0.569], [-0.569, -0.569, -0.569], [-0.569, -0.569, 0.569], [0.569, -0.569, 0.569], \
                    [0.569, 0.569, 0.569], [-0.569, 0.569, 0.569], [-0.569, -0.569, 0.569]],d=1) # Creates Cube
                    
        ik_ctrl_grp = cmds.group(name=(ik_control+'Grp'))
        placement_constraint = cmds.pointConstraint(end_joint_rp_ik,ik_ctrl_grp)
        cmds.delete(placement_constraint)

    # Constraint IK Handles to IK Control
    cmds.parentConstraint(ik_control, ikHandle_rp[0], maintainOffset=True)
    if is_using_ball: 
        cmds.parentConstraint(ik_control, ikHandle_sc_ball[0], maintainOffset=True)
        cmds.parentConstraint(ik_control, ikHandle_sc_toe[0], maintainOffset=True)

    if settings.get("using_custom_pvector_ctrl"):
        pvector_ctrl = settings.get("custom_pvector_ctrl")
    else:
        pvector_ctrl = cmds.curve(name= ik_control[:-4] + 'pvector_ctrlCtrl', p=[[0.268, 0.268, 0.0], [0.535, 0.268, 0.0], [0.535, -0.268, -0.0], [0.268, -0.268, -0.0], [0.268, -0.535, -0.0], [-0.268, -0.535, -0.0], [-0.268, -0.268, -0.0], [-0.535, -0.268, -0.0], [-0.535, 0.268, 0.0], [-0.268, 0.268, 0.0], [-0.268, 0.535, 0.0], [0.268, 0.535, 0.0], [0.268, 0.268, 0.0]],d=1)
        pvector_ctrl_ctrl_grp = cmds.group(name=(pvector_ctrl +'Grp'))
        
        placement_constraint = cmds.pointConstraint(middle_joint_rp_ik,pvector_ctrl_ctrl_grp)
        cmds.delete(placement_constraint)
        
        
    cmds.poleVectorConstraint( pvector_ctrl, ikHandle_rp[0] ) 

    #Check if exists (use checker before running)
    if settings.get("using_custom_ikfk_switch"):
        ik_switch_ctrl = settings.get("custom_ikfk_switch_name")
    else:
        ik_switch_ctrl_before_naming = create_fkik_switch()
        ik_switch_ctrl = cmds.rename(ik_switch_ctrl_before_naming, ik_control.replace("_IK_Ctrl", "_") + "switch_ikfkCtrl")
        cmds.setAttr(ik_switch_ctrl + ".overrideEnabled", 1)
        cmds.setAttr(ik_switch_ctrl + ".overrideColor", 17) #Yellow 
                         
    cmds.addAttr(ik_switch_ctrl, niceName='IK FK Switch', longName='ikSwitch', attributeType='bool', defaultValue = 1, keyable = True )
    cmds.addAttr(ik_switch_ctrl, niceName='IK FK Influence', longName='ikInfluence', attributeType='double', defaultValue = 1, keyable = True )
    lock_hide_attr(ik_switch_ctrl, ['tx','ty','tz','rx','ry','rz', 'sx','sy','sz','v'],True,False)
    ik_switch_ctrlGrp = cmds.group(name=(ik_switch_ctrl+'Grp'))

    reverse_node = cmds.createNode('reverse')
    cmds.connectAttr('%s.ikSwitch' % ik_switch_ctrl, '%s.inputX' % reverse_node)

    ctrl_name = hip_jnt_start_rp_fk[:-jnt_tag_length] + settings.get("ctrl_grp_tag")
    if cmds.objExists(ctrl_name):
        cmds.connectAttr('%s.outputX' % reverse_node, '%s.v' % ctrl_name)
        
    ctrl_name = knee_jnt_middle_rp_fk[:-jnt_tag_length] + settings.get("ctrl_grp_tag")
    if cmds.objExists(ctrl_name):
        cmds.connectAttr('%s.outputX' % reverse_node, '%s.v' % ctrl_name)
      
    ctrl_name = ankle_jnt_end_rp_fk[:-jnt_tag_length] + settings.get("ctrl_grp_tag")
    if cmds.objExists(ctrl_name):
        cmds.connectAttr('%s.outputX' % reverse_node, '%s.v' % ctrl_name)  
    
    if is_using_ball: 
        ctrl_name = ball_jnt_end_sc1_fk[:-jnt_tag_length] + settings.get("ctrl_grp_tag")
        if cmds.objExists(ctrl_name):
            cmds.connectAttr('%s.outputX' % reverse_node, '%s.v' % ctrl_name)
        
    cmds.connectAttr('%s.ikSwitch' % ik_switch_ctrl, '%s.v' % ik_control)
    cmds.connectAttr('%s.ikSwitch' % ik_switch_ctrl, '%s.v' % pvector_ctrl)
    
    # Main Ctrl IK Influence
    # Creates Condition (IK Switch is one) > 
    # Reverse goes to FK weight, true data is passed to IK Weight

    condition_node = cmds.createNode('condition')
    cmds.setAttr(condition_node + '.secondTerm', 1)
    cmds.setAttr(condition_node + '.colorIfFalseR', 0)
    cmds.setAttr(condition_node + '.colorIfFalseG', 0)
    cmds.setAttr(condition_node + '.colorIfFalseB', 0)
    cmds.connectAttr('%s.ikSwitch' % ik_switch_ctrl, '%s.firstTerm' % condition_node)
    cmds.connectAttr('%s.ikInfluence' % ik_switch_ctrl, '%s.colorIfTrueR' % condition_node)

    start_joint_rp_ik_pConstraint_lwn = get_last_weight_number(start_joint_rp_ik_pConstraint[0])
    middle_joint_rp_ik_pConstraint_lwn = get_last_weight_number(middle_joint_rp_ik_pConstraint[0])
    end_joint_rp_ik_pConstraint_lwn = get_last_weight_number(end_joint_rp_ik_pConstraint[0])
    if is_using_ball: 
        end_joint_sc1_ik_pConstraint_lwn = get_last_weight_number(end_joint_sc1_ik_pConstraint[0])

    cmds.connectAttr('%s.outColorR' % condition_node, start_joint_rp_ik_pConstraint[0] + '.' + start_joint_rp_ik[0] + "W" + start_joint_rp_ik_pConstraint_lwn)
    cmds.connectAttr('%s.outColorR' % condition_node, middle_joint_rp_ik_pConstraint[0] + '.' + middle_joint_rp_ik[0] + "W" + middle_joint_rp_ik_pConstraint_lwn)
    cmds.connectAttr('%s.outColorR' % condition_node, end_joint_rp_ik_pConstraint[0] + '.' + end_joint_rp_ik[0] + "W" + end_joint_rp_ik_pConstraint_lwn)
    if is_using_ball: 
        cmds.connectAttr('%s.outColorR' % condition_node, end_joint_sc1_ik_pConstraint[0] + '.' + end_joint_sc1_ik[0] + "W" + end_joint_sc1_ik_pConstraint_lwn)

    reverse_condition_node = cmds.createNode('reverse')
    cmds.connectAttr('%s.outColorR' % condition_node, '%s.inputX' % reverse_condition_node)
    
    #Connects constraint weights to reverse node
    def connect_non_ik_weights(constraintName, nonIKWeightList):
        for obj in nonIKWeightList:
            cmds.connectAttr('%s.outputX' % reverse_condition_node, constraintName + '.' + obj)
            
    connect_non_ik_weights(start_joint_rp_ik_pConstraint[0],get_all_weights_but_not_last(start_joint_rp_ik_pConstraint[0]))
    connect_non_ik_weights(middle_joint_rp_ik_pConstraint[0],get_all_weights_but_not_last(middle_joint_rp_ik_pConstraint[0]))
    connect_non_ik_weights(end_joint_rp_ik_pConstraint[0],get_all_weights_but_not_last(end_joint_rp_ik_pConstraint[0]))
    if is_using_ball: 
        connect_non_ik_weights(end_joint_sc1_ik_pConstraint[0],get_all_weights_but_not_last(end_joint_sc1_ik_pConstraint[0]))

    # Colorize Control Start ------------------
    if settings.get("using_colorize_ctrls"):
        controls = [ik_control, pvector_ctrl]
        for ctrl in controls:
            if True == True:
                        cmds.setAttr(ctrl + ".overrideEnabled", 1)
                        if 'right_' in ctrl:
                            cmds.setAttr(ctrl + ".overrideColor", 13) #Red
                        elif 'left_' in ctrl:
                            cmds.setAttr(ctrl + ".overrideColor", 6) #Blue
                        else:
                            cmds.setAttr(ctrl + ".overrideColor", 17) #Yellow                                
                            
    # Create setup grp
    main_ik_grp_name = hip_jnt_start_rp_fk.replace("Jnt","")
    main_ik_grp = cmds.group(name=main_ik_grp_name + "_IK_Setup_grp",em=True)
    cmds.parent(start_joint_rp_ik, main_ik_grp) # Parent to Setup Grp (IK Skeleton)
    solvers_ik_grp = cmds.group(name=main_ik_grp_name + "_solvers_grp",em=True)
    # Parent to Setup Grp (Solvers)
    if is_using_ball: 
        cmds.parent(ikHandle_sc_ball[0], solvers_ik_grp)
        cmds.parent(ikHandle_sc_toe[0], solvers_ik_grp)
        
    cmds.parent(ikHandle_rp[0], solvers_ik_grp) # Parent to Setup Grp (Solvers)
    cmds.parent(solvers_ik_grp, main_ik_grp) # Parent to Setup Grp (Solvers)
    
    cmds.setAttr(solvers_ik_grp + ".v", 0) #Make solvers grp invisible
    cmds.setAttr(start_joint_rp_ik[0] + ".v", 0) #Make ik skeleton invisible
    
    
    ctrls_ik_grp = cmds.group(name=main_ik_grp_name + "_controls_grp",em=True)
    generated_ctrls = [ik_switch_ctrlGrp,pvector_ctrl_ctrl_grp,ik_ctrl_grp]
    for ctrl in generated_ctrls:
        if cmds.objExists(ctrl):
            cmds.parent(ctrl, ctrls_ik_grp)
    cmds.parent(ctrls_ik_grp, main_ik_grp)
    
    ctrls_children = cmds.listRelatives(ctrls_ik_grp, c=True) 
    if ctrls_children == None:
        cmds.delete(ctrls_ik_grp)
    
    # Add some color to the new outliner elements
    change_outliner_color(main_ik_grp,[0.240,1,0.062])
    change_outliner_color(solvers_ik_grp,[1,1,0.126])
    change_outliner_color(ctrls_ik_grp,[1,0.479,0.172])
    for jnt in ik_jnts:
        change_outliner_color(jnt[0],[0.763,0.332,0.892])

    # If not using Ball, make IK control rotate ankle
    if is_using_ball == False: 
        cmds.orientConstraint(ik_control,end_joint_rp_ik)
        
    # Make leg stretchy
    if settings.get('make_stretchy'):
        cmds.select(ikHandle_rp)
        ikHandle = cmds.ls(selection=True, type="ikHandle")
        stretchy_grp = make_stretchy_legs(ikHandle)
        cmds.parent(stretchy_grp, main_ik_grp)
        change_outliner_color(stretchy_grp,[1,0,0])
        cmds.setAttr(stretchy_grp + ".v", 0) #Make it invisible
        
    cmds.select(ik_control)
Exemple #32
0
#to make this a little bicer we will use a list.

#A list = list of items like you would take shopping.#
#To save us some typing we can make a list with all of our joint names in it.#
#In fact, we can make a list of lists so we can have a list for each joint name and position#
#We use square brackets to encapsulate each item in list.#
#That list of lists can even be saved to a variable#

jointinfo = (['joint_upperarm',[0.0,5.0,0.0]],['joint_lowerarm',[1.0,5.0,2.0]],['joint_hand',[0.0,5.0,4.0]])
print jointinfo

#so we have our list, but how do we work with it?
#for this we will call upon the power of loop

cmds.select(d=True)
for item in jointinfo:
    #//print item #print each loop variables in jointinfo
    
    #//print item[0] #print each loop variables of index0 in jointinfo // the index 0 of listed item
    #//print item[1] #print each loop variables of index1 in jointinfo // the index 1 of listem item
    
    cmds.joint(n=item[0],p=item[1]) #this creates joints, with name assigned to listed items index 0, position to listem items index 1
    
//////

#define a list of strings and assign it to the mylist variable.
mylist = ('a','b')
    
#enter a for loop and print each item in my list
for item in mylist:
    def process(self, instance):

        # get settings
        framerange = [
            instance.data.get("frameStart", 1),
            instance.data.get("frameEnd", 1)
        ]
        handles = instance.data.get("handles", 0)
        step = instance.data.get("step", 1.0)
        bake_to_worldspace = instance.data("bakeToWorldSpace", True)

        # get cameras
        members = instance.data['setMembers']
        cameras = cmds.ls(members,
                          leaf=True,
                          shapes=True,
                          long=True,
                          dag=True,
                          type="camera")

        # validate required settings
        assert len(cameras) == 1, "Not a single camera found in extraction"
        assert isinstance(step, float), "Step must be a float value"
        camera = cameras[0]

        # Define extract output file path
        dir_path = self.staging_dir(instance)
        filename = "{0}.abc".format(instance.name)
        path = os.path.join(dir_path, filename)

        # Perform alembic extraction
        with avalon.maya.maintained_selection():
            cmds.select(camera, replace=True, noExpand=True)

            # Enforce forward slashes for AbcExport because we're
            # embedding it into a job string
            path = path.replace("\\", "/")

            job_str = ' -selection -dataFormat "ogawa" '
            job_str += ' -attrPrefix cb'
            job_str += ' -frameRange {0} {1} '.format(framerange[0] - handles,
                                                      framerange[1] + handles)
            job_str += ' -step {0} '.format(step)

            if bake_to_worldspace:
                transform = cmds.listRelatives(camera,
                                               parent=True,
                                               fullPath=True)[0]
                job_str += ' -worldSpace -root {0}'.format(transform)

            job_str += ' -file "{0}"'.format(path)

            with lib.evaluation("off"):
                with avalon.maya.suspended_refresh():
                    cmds.AbcExport(j=job_str, verbose=False)

        if "representations" not in instance.data:
            instance.data["representations"] = []

        representation = {
            'name': 'abc',
            'ext': 'abc',
            'files': filename,
            "stagingDir": dir_path,
        }
        instance.data["representations"].append(representation)

        self.log.info("Extracted instance '{0}' to: {1}".format(
            instance.name, path))
 def Select_OBJ_Fun(self,selectTarget):
     if selectTarget != "":
         cmds.select(selectTarget)
    def check(self):
        cmds.text('sme_startFrame_label', e=True, en=1)
        cmds.floatField('sme_startFrame', e=True, en=1)
        cmds.text('sme_endFrame_label', e=True, en=1)
        cmds.floatField('sme_endFrame', e=True, en=1)
        cmds.text('sme_totalFrames_label',
                  e=True,
                  en=1,
                  l='Total Frames: ' + str(someGlobals.globals['startFrame'] +
                                           someGlobals.globals['endFrame']))
        cmds.optionMenu('sme_frameRate', e=True, en=1)

        filename = re.sub('[^\w\-_\. ]', '',
                          cmds.textField('sme_rigFilename', q=True,
                                         tx=True)).replace(' ', '')
        cmds.textField('sme_rigFilename', e=True, tx=filename)

        dataExists = ''
        if os.path.isfile(someGlobals.globals['exportPath'] + filename +
                          '.fbx'):
            dataExists = ' - Data Exists!'

        cmds.text('sme_rigDataExists_label', e=True, l=dataExists)

        name = re.sub('[^\w\-_\.\ ]', '',
                      cmds.textField('sme_rigName', q=True,
                                     tx=True)).replace(' ', '')
        cmds.textField('sme_rigName', e=True, tx=name)

        rig = cmds.textField('sme_rigToSample', q=True,
                             tx=True).replace(' ', '')
        cmds.textField('sme_rigToSample', e=True, tx=rig)

        selectEnable = 0
        selectCommand = lambda *args: cmds.select(rig, r=True)
        selectColor = someGlobals.color['red']
        if cmds.objExists(rig):
            selectEnable = 1
            selectCommand = lambda *args: cmds.select(rig, r=True)
            selectColor = someGlobals.color['blue']

        bakeEnable = 1
        bakeColor = someGlobals.color['green']
        bakeLabel = 'Bake and Export Rig'
        bakeCommand = lambda *args: self.batch()
        if len(filename) < 1 or len(name) < 1 or cmds.objExists(rig) == False:
            bakeEnable = 0
            bakeColor = someGlobals.color['red']
            bakeLabel = 'Errors Found in Rig Export Parameters'
            bakeCommand = ''

        if (os.path.exists(someGlobals.globals['exportPath']) == False):
            bakeEnable = 0
            bakeColor = someGlobals.color['red']
            bakeCommand = ''
            bakeLabel = 'Invalid Export Path'

        # lets update our globals
        rigFilename = {'filename': filename}
        rigName = {'name': name}
        rigNode = {'node': rig}
        someGlobals.rig.update(rigFilename)
        someGlobals.rig.update(rigName)
        someGlobals.rig.update(rigNode)

        cmds.button('sme_selectRigToExport_button',
                    e=True,
                    en=selectEnable,
                    bgc=selectColor,
                    c=selectCommand)
        cmds.button('sme_rigBake_button',
                    e=True,
                    en=bakeEnable,
                    bgc=bakeColor,
                    l=bakeLabel,
                    c=bakeCommand)
    def Cam_Item_Pressing_Event(self, e):
        """
        mousePressEvent 
        # Note 点击事件触发
        """
        ##   Note 清空所有颜色轮廓
        for i, child in enumerate(self.Cam_Item_Widget.Item_Layout.children()):
            if i != 0:
                if child.Cam_Item.styleSheet() != "":
                    child.Cam_Item.setStyleSheet("")

        self.Cam_Item_Widget.setStyleSheet("")

        ##   Note 坐标偏移
        offset = 90 - self.Cam_Item_Widget.Scroll_Offset
        for i, child in enumerate(self.Cam_Item_Widget.Item_Layout.children()):
            if i != 0:
                ##   Note 如果坐标匹配则载入相关数据
                if child.geometry().contains(e.pos().x(),
                                             e.pos().y() - offset):
                    child.Cam_Item.setStyleSheet(
                        "#Cam_Item{border:3px solid red}")

                    CamName = child.Cam_LE.text()
                    self.Cam_Attribute_Widget.Cam_Name_Label.setText(
                        u"<center> - %s - </center>" % CamName)
                    self.Cam_Attribute_Widget.Cam_Input_Toggle.setVisible(True)
                    self.Cam_Attribute_Widget.Cam_Input_Layout.setVisible(True)
                    self.Cam_Attribute_Widget.Cam_Output_Toggle.setVisible(
                        True)
                    self.Cam_Attribute_Widget.Cam_Output_Layout.setVisible(
                        True)
                    self.Cam_Attribute_Widget.Add_CamGrp_Layout.setVisible(
                        True)
                    self.Cam_Attribute_Widget.Strat_Time_Layout.setVisible(
                        True)
                    self.Cam_Attribute_Widget.End_Time_Layout.setVisible(True)
                    self.Cam_Attribute_Widget.Auto_Catch_Label.setVisible(True)
                    self.Cam_Attribute_Widget.Add_Loc_Layout.setVisible(True)

                    self.Cam_Attribute_Widget.Current_Item = child

                    if os.path.exists(GUI_STATE_PATH):
                        GUI_STATE = {}
                        with open(GUI_STATE_PATH, 'r') as f:
                            GUI_STATE = json.load(f)

                        Attr = GUI_STATE['Cam_Item'][CamName]["Attr"]
                        self.Cam_Attribute_Widget.Add_Crv_LE.setText(
                            Attr["Add_Crv_LE"])
                        self.Cam_Attribute_Widget.Add_Loc_LE.setText(
                            Attr["Add_Loc_LE"])
                        self.Cam_Attribute_Widget.Add_Motion_Path_LE.setText(
                            Attr["Add_Motion_Path_LE"])
                        self.Cam_Attribute_Widget.Add_CamGrp_LE.setText(
                            Attr["Add_CamGrp_LE"])

                        # Note 检查选择
                        if self.Cam_Attribute_Widget.Check_Selection():
                            self.Cam_Attribute_Widget.Strat_Time_SB.setValue(
                                int(Attr["Strat_Time_SB"]))
                            self.Cam_Attribute_Widget.End_Time_SB.setValue(
                                int(Attr["End_Time_SB"]))
                            cmds.select(Attr["Add_CamGrp_LE"])
                            self.Cam_Attribute_Widget.Add_CamGrp_Pick_Fun()
                            cmds.select(Attr["Add_CamGrp_LE"])
                        else:
                            self.Cam_Attribute_Widget.Strat_Time_SB.setValue(0)
                            self.Cam_Attribute_Widget.End_Time_SB.setValue(0)
                            cmds.select(cl=1)
                            self.Cam_Attribute_Widget.Add_CamGrp_Pick_Fun()
                            self.Cam_Attribute_Widget.Add_Motion_Path_Pick_Fun(
                            )
                            self.Cam_Attribute_Widget.Add_Crv_Pick_Fun()
                            self.Cam_Attribute_Widget.Add_Loc_Pick_Fun()

                        self.Save_Json_Fun()
                    else:
                        QMessageBox.warning(self, u"Warning", u"加载参数失败")

                    break
        else:
            ##   Note 遍历全部对象说明没有匹配 使用默认情况
            if self.Cam_Item_Widget.Cam_Base_Label.geometry().contains(
                    e.pos().x(),
                    e.pos().y() - 40):

                self.Cam_Item_Widget.setStyleSheet(
                    "#Cam_Base_Layout{border:3px solid red}")
                self.Cam_Attribute_Widget.Current_Item = self.Cam_Item_Widget

                self.Cam_Attribute_Widget.Cam_Input_Toggle.setVisible(True)
                self.Cam_Attribute_Widget.Cam_Input_Layout.setVisible(True)
                self.Cam_Attribute_Widget.Cam_Output_Toggle.setVisible(False)
                self.Cam_Attribute_Widget.Cam_Output_Layout.setVisible(False)
                # self.Cam_Attribute_Widget.Add_CamGrp_Layout.setVisible(False)
                self.Cam_Attribute_Widget.Strat_Time_Layout.setVisible(False)
                self.Cam_Attribute_Widget.End_Time_Layout.setVisible(False)
                self.Cam_Attribute_Widget.Auto_Catch_Label.setVisible(False)
                # self.Cam_Attribute_Widget.Add_Loc_Layout.setVisible(False)
                Cam_Base_Name = self.Cam_Item_Widget.Cam_LE.text()
                self.Cam_Attribute_Widget.Cam_Name_Label.setText(
                    u"<center> - %s - </center>" % Cam_Base_Name)

                Attr = self.Cam_Item_Widget.Attr
                self.Cam_Attribute_Widget.Add_Crv_LE.setText(
                    Attr["Add_Crv_LE"])
                self.Cam_Attribute_Widget.Add_Motion_Path_LE.setText(
                    Attr["Add_Motion_Path_LE"])
                self.Cam_Attribute_Widget.Add_CamGrp_LE.setText(
                    Attr["Add_CamGrp_LE"])
                self.Cam_Attribute_Widget.Add_Loc_LE.setText(
                    Attr["Add_Loc_LE"])
                # Note 检查选择
                if self.Cam_Attribute_Widget.Check_Selection():
                    cmds.select(Attr["Add_Crv_LE"])
                    self.Cam_Attribute_Widget.Add_Crv_Pick_Fun()
                    cmds.select(Attr["Add_CamGrp_LE"])
                    self.Cam_Attribute_Widget.Add_CamGrp_Pick_Fun()
                    cmds.select(Attr["Add_Loc_LE"])
                    self.Cam_Attribute_Widget.Add_Loc_Pick_Fun()
                    cmds.select(Attr["Add_CamGrp_LE"])
                else:
                    cmds.select(cl=1)
                    self.Cam_Attribute_Widget.Add_Motion_Path_Pick_Fun()
                    self.Cam_Attribute_Widget.Add_Crv_Pick_Fun()
                    self.Cam_Attribute_Widget.Add_CamGrp_Pick_Fun()

                self.Save_Json_Fun()
            else:
                self.Default_Attr_Setting()
def if_exists_select(obj):
    if cmds.objExists(obj):
        cmds.select(obj)
        cmds.headsUpMessage(obj + " selected", verticalOffset=150 )
    else:
        cmds.warning("Object doesn't exist! Did you delete or rename it after loading?")
def CreateButtonPush(*args):
    currentValue = cmds.optionMenu('Object_Type', query=True, value=True)
    if currentValue == 'Fluid Emitter':
        set = cmds.ls(type='fluidEmitter')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='fluidEmitterQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Fluid Emitters')
        else:
            print('No Fluid Emitter in Scene')
    elif currentValue == 'nParticle/Particle Emitter':
        set = cmds.ls(exactType='pointEmitter')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='particleEmitterQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Particle Emitters')
        else:
            print('No Particle Emitter in Scene')
    elif currentValue == 'nRigid':
        set = cmds.ls(type='nRigid')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='nRigidQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all nRigids')
        else:
            print('No nRigid in Scene')
    elif currentValue == 'Fluid Container':
        set = cmds.ls(type='fluidShape')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='fluidShapeQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Fluid Containers')
        else:
            print('No Fluid Container in Scene')
    elif currentValue == 'Nucleus':
        set = cmds.ls(type='nucleus')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='nucleusQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Nucleus')
        else:
            print('No Nucleus in Scene')
    elif currentValue == 'nParticle':
        set = cmds.ls(type='nParticle')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='nParticleQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all nParticles')
        else:
            print('No nParticle in Scene')
    elif currentValue == 'Force Field':
        set = cmds.ls(type='field')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='forceFieldQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Force Fields')
        else:
            print('No Force Field in Scene')
    elif currentValue == 'Legacy Particle':
        set = cmds.ls(exactType='particle')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='ParticleQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Particles')
        else:
            print('No Particle in Scene')
    elif currentValue == 'nCloth':
        set = cmds.ls(exactType='nCloth')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='nClothQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all nClothes')
        else:
            print('No nCloth in Scene')
    elif currentValue == 'Dynamic Constraint':
        set = cmds.ls(exactType='dynamicConstraint')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='dynamicConstraintQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Dynamic Constraints')
        else:
            print('No Dynamic Constraint in Scene')
    elif currentValue == 'Rigid Body':
        set = cmds.ls(exactType='rigidBody')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='rigidBodyQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Rigid Bodies')
        else:
            print('No Rigid Body in Scene')
    elif currentValue == 'Rigid Constraint':
        set = cmds.ls(exactType='rigidConstraint')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='rigidConstraintQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Rigid Constraints')
        else:
            print('No Rigid Constraint in Scene')
    elif currentValue == 'Anim Constraint':
        set = cmds.ls(type='constraint')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='constraintQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Anim Constraints')
        else:
            print('No Anim Constraint in Scene')
    elif currentValue == 'Rigid Body':
        set = cmds.ls(type='rigidBody')
        if bool(set):  # Condition If No Objects Type In Scene
            cmds.select(set)
            cmds.sets(name='rigidBodyQSS', text='gCharacterSet')
            print('Created Quick Selection Set with all Rigid bodies')
        else:
            print('No Rigid Body in Scene')
    def testRename(self):
        # open tree.ma scene in test-samples
        mayaUtils.openTreeScene()

        # clear selection to start off
        cmds.select(clear=True)

        # select a USD object.
        mayaPathSegment = mayaUtils.createUfePathSegment(
            '|world|Tree_usd|Tree_usdShape')
        usdPathSegment = usdUtils.createUfePathSegment('/TreeBase')
        treebasePath = ufe.Path([mayaPathSegment, usdPathSegment])
        treebaseItem = ufe.Hierarchy.createItem(treebasePath)

        ufe.GlobalSelection.get().append(treebaseItem)

        # get the USD stage
        stage = mayaUsd.ufe.getStage(str(mayaPathSegment))

        # by default edit target is set to the Rootlayer.
        self.assertEqual(stage.GetEditTarget().GetLayer(),
                         stage.GetRootLayer())

        self.assertTrue(stage.GetRootLayer().GetPrimAtPath("/TreeBase"))

        # get default prim
        defaultPrim = stage.GetDefaultPrim()
        self.assertEqual(defaultPrim.GetName(), 'TreeBase')

        # TreeBase has two childern: leavesXform, trunk
        assert len(defaultPrim.GetChildren()) == 2

        # get prim spec for defaultPrim
        primspec = stage.GetEditTarget().GetPrimSpecForScenePath(
            defaultPrim.GetPath())

        # set primspec name
        primspec.name = "TreeBase_potato"

        # get the renamed prim
        renamedPrim = stage.GetPrimAtPath('/TreeBase_potato')

        # One must use the SdfLayer API for setting the defaultPrim when you rename the prim it identifies.
        stage.SetDefaultPrim(renamedPrim)

        # get defaultPrim again
        defaultPrim = stage.GetDefaultPrim()
        self.assertEqual(defaultPrim.GetName(), 'TreeBase_potato')

        # make sure we have a valid prims after the primspec rename
        assert stage.GetPrimAtPath('/TreeBase_potato')
        assert stage.GetPrimAtPath('/TreeBase_potato/leavesXform')

        # prim should be called TreeBase_potato
        potatoPrim = stage.GetPrimAtPath('/TreeBase_potato')
        self.assertEqual(potatoPrim.GetName(), 'TreeBase_potato')

        # prim should be called leaves
        leavesPrimSpec = stage.GetObjectAtPath(
            '/TreeBase_potato/leavesXform/leaves')
        self.assertEqual(leavesPrimSpec.GetName(), 'leaves')
Exemple #40
0
def CreatePlaneBtnCmd():
    #create paramaters
    #get base shape
    #get number of divisions

    #Gather Info
    NumberOfDivision = mc.intSliderGrp(divisitonintField, q=True, v=True)
    createCtroller = mc.checkBox(createCtrlCB, q=True, v=True)
    controllerType = mc.radioCollection("ControllerSelectionID",
                                        q=True,
                                        sl=True)
    NameBase = mc.textFieldGrp("ControllerTextFieldID", q=True, tx=True)
    specifyBaseShape = mc.checkBox(SpecifyBaseShapeCB, q=True, v=True)
    BaseShapeFiledText = mc.textField("BasicShapeTextFieldID", q=True, tx=True)

    printInfo()

    #get selection:
    if (mc.ls(sl=True)):
        sel = mc.ls(sl=True)[0]
    else:
        mc.error("Nothing is selected")
        return

    #get Shapes:
    ShapeNodeList = mc.listRelatives(sel, s=True)
    BaseShape = ""
    TargetShape = ""
    for item in ShapeNodeList:
        if mc.getAttr(item + ".intermediateObject"):
            BaseShape = item
        else:
            TargetShape = item
    if specifyBaseShape and BaseShape == "":
        BaseShape = BaseShapeFiledText
    if BaseShape == "":
        print mc.error(
            "Cannot Find Baseshape, please specify BaseShape Mannually")

    #gether per vertex translation and object translation
    baseVertexLocations = GetVertexLocations(BaseShape)
    targetVertexLocations = GetVertexLocations(TargetShape)
    baseTranslation = getTranslateNodePostion(BaseShape)
    targetTranslation = getTranslateNodePostion(TargetShape)

    #printMVector(baseTranslation)

    #get the bounding box of the offsetted vertex
    boundingBoxInfo = GetBoundingBox(baseVertexLocations,
                                     targetVertexLocations, baseTranslation,
                                     targetTranslation)
    boundingBox = boundingBoxInfo[0]
    bIsBoundingBoxValid = boundingBoxInfo[1]
    #print boundingBox, bIsBoundingBoxValid

    if (not bIsBoundingBoxValid):
        mc.error("There is no different between seleted shape and base shape")

    #create divistion Planes:
    MakeDivistionPlan(boundingBox, baseTranslation, targetTranslation,
                      TargetShape, BaseShape, NumberOfDivision)
    print "Divistion Planes Created Succesfully!"
    mc.select(sel, r=True)
Exemple #41
0
 def selEdgeByIntArray(self, inputArray, add=False):
     if not add:
         cmds.select(cl=1)
     for i in inputArray:
         vertString = '%s.e[%s]' % (self.polyName, str(i))
         cmds.select(vertString, add=1)
    def testRenameUndo(self):
        '''Rename USD node.'''

        # open usdCylinder.ma scene in test-samples
        mayaUtils.openCylinderScene()

        # clear selection to start off
        cmds.select(clear=True)

        # select a USD object.
        mayaPathSegment = mayaUtils.createUfePathSegment(
            '|world|mayaUsdTransform|shape')
        usdPathSegment = usdUtils.createUfePathSegment('/pCylinder1')
        cylinderPath = ufe.Path([mayaPathSegment, usdPathSegment])
        cylinderItem = ufe.Hierarchy.createItem(cylinderPath)
        cylinderHierarchy = ufe.Hierarchy.hierarchy(cylinderItem)
        propsItem = cylinderHierarchy.parent()

        propsHierarchy = ufe.Hierarchy.hierarchy(propsItem)
        propsChildrenPre = propsHierarchy.children()

        ufe.GlobalSelection.get().append(cylinderItem)

        # get the USD stage
        stage = mayaUsd.ufe.getStage(str(mayaPathSegment))

        # check GetLayerStack behavior
        self.assertEqual(stage.GetLayerStack()[0], stage.GetSessionLayer())
        self.assertEqual(stage.GetEditTarget().GetLayer(),
                         stage.GetRootLayer())

        # by default edit target is set to the Rootlayer.
        self.assertEqual(stage.GetEditTarget().GetLayer(),
                         stage.GetRootLayer())

        # rename
        cylinderItemType = cylinderItem.nodeType()
        newName = 'pCylinder1_Renamed'
        cmds.rename(newName)

        # The renamed item is in the selection.
        snIter = iter(ufe.GlobalSelection.get())
        pCylinder1Item = next(snIter)
        pCylinder1RenName = str(pCylinder1Item.path().back())

        self.assertEqual(pCylinder1RenName, newName)

        propsChildren = propsHierarchy.children()

        self.assertEqual(len(propsChildren), len(propsChildrenPre))
        self.assertIn(pCylinder1Item, propsChildren)

        cmds.undo()
        self.assertEqual(cylinderItemType,
                         ufe.GlobalSelection.get().back().nodeType())

        def childrenNames(children):
            return [str(child.path().back()) for child in children]

        propsHierarchy = ufe.Hierarchy.hierarchy(propsItem)
        propsChildren = propsHierarchy.children()
        propsChildrenNames = childrenNames(propsChildren)

        self.assertNotIn(pCylinder1RenName, propsChildrenNames)
        self.assertIn('pCylinder1', propsChildrenNames)
        self.assertEqual(len(propsChildren), len(propsChildrenPre))

        cmds.redo()
        self.assertEqual(cylinderItemType,
                         ufe.GlobalSelection.get().back().nodeType())

        propsHierarchy = ufe.Hierarchy.hierarchy(propsItem)
        propsChildren = propsHierarchy.children()
        propsChildrenNames = childrenNames(propsChildren)

        self.assertIn(pCylinder1RenName, propsChildrenNames)
        self.assertNotIn('pCylinder1', propsChildrenNames)
        self.assertEqual(len(propsChildren), len(propsChildrenPre))
Exemple #43
0
    for j in range(4):
        mc.rename('IndexLoc' + str(j + 4), 'MiddleLoc' + str(j))
    for j in range(4, 8):
        mc.rename('IndexLoc' + str(j + 4), 'RingLoc' + str(j - 4))
    for j in range(8, 12):
        mc.rename('IndexLoc' + str(j + 4), 'PinkieLoc' + str(j - 8))


createLoc()

#create IK FK SKIN joints (arm)
shoulderLT = mc.getAttr('ShoulderLeftLoc.t')[0]
elbowLT = mc.getAttr('ElbowLeftLoc.t')[0]
wristLT = mc.getAttr('WristLeftLoc.t')[0]
mc.select(clear=True)
shouder_FK = mc.joint(n='shoulder_FK_JNT')
mc.joint(shouder_FK,
         e=True,
         p=(shoulderLT[0], shoulderLT[1], shoulderLT[2]),
         rad=0.5,
         oj='xyz',
         sao='yup')
elbow_FK = mc.joint(n='elbow_FK_JNT')
mc.joint(elbow_FK,
         e=True,
         p=(elbowLT[0], elbowLT[1], elbowLT[2]),
         rad=0.5,
         oj='xyz',
         sao='yup')
wrist_FK = mc.joint(n='wrist_FK_JNT')
Exemple #44
0
def follicleRivet(surface, baseName=None, U=0.5, V=0.5, attr=False, shape=True, p=None):
    '''
    Create follicle on surface as a rivet hook
    #    return rivet

    Options:
    -baseName (string): base name string used as prefix for all nodes
    -U (float): u placement
    -v (float): v placement
    -attr (bool): add U and V position option attributes to rivet
    -shape (bool): add locator shaped curve to rivet
    -p (node): rivet target parent node

    author: guillaume barlier
    '''
    #    sanity check
    surface, surfaceShp = shapeFunctions.filterShpAndTransform(surface)
    if not (surface and surfaceShp):
        return

    #    define baseName
    if not baseName:
        baseName    =   'rivet'

    #    create follicle
    follicleShp =   cmds.createNode('follicle')
    follicle    =   cmds.listRelatives(follicleShp, p=True)[0]
    cmds.setAttr('%s.inheritsTransform'%follicle, 0)

    cmds.connectAttr('%s.outRotate'%follicleShp, '%s.rotate'%follicle, f=True)
    cmds.connectAttr('%s.outTranslate'%follicleShp, '%s.translate'%follicle, f=True)

    #    set U V
    cmds.setAttr('%s.pu'%follicleShp, U)
    cmds.setAttr('%s.pv'%follicleShp, V)

    #    rename follicle (createNode create the shape)
    follicle    =   cmds.rename(follicle, baseName)
    follicleShp =   cmds.listRelatives(follicle, s=True)[0]

    #    connect surface to follicle
    cmds.connectAttr('%s.worldMatrix[0]'%surfaceShp, '%s.inputWorldMatrix'%follicleShp, f=True)
    if cmds.nodeType(surfaceShp) == 'nurbsSurface':
        cmds.connectAttr('%s.local'%surfaceShp, '%s.inputSurface'%follicleShp, f=True)
    elif cmds.nodeType(surfaceShp) == 'mesh':
        cmds.connectAttr('%s.worldMesh[0]'%surfaceShp, '%s.inputMesh'%follicleShp, f=True)

    #    add curve locator shape
    locatorShp  =   None
    if shape:
        #    rename.hide follicle shape
        follicleShp = cmds.rename(follicleShp, baseName+'FollicleShape')
        cmds.setAttr('%s.v'%follicleShp, 0)

        #    add curve locator shape
        locatorShp  =    handleFunctions.curveLocator(baseName+'CrvLoc', p=follicle, s=True)
        cmds.reorder(locatorShp, front=True )
        controlFunctions.colorShape([locatorShp], 4)

    #    add custom attribute
    if attr:
        attributeFunctions.createSeparator(follicle)
        cmds.addAttr(follicle, ln='parameterU', sn='pu', at='double')
        cmds.setAttr('%s.pu'%follicle, U, k=True)
        cmds.connectAttr('%s.pu'%follicle, '%s.pu'%follicleShp, f=True)

        cmds.addAttr(follicle, ln='parameterV', sn='pv', at='double')
        cmds.setAttr('%s.pv'%follicle, V, k=True)
        cmds.connectAttr('%s.pv'%follicle, '%s.pv'%follicleShp, f=True)

    #    parent rivet
    if p and cmds.objExists(p):
        cmds.parent(follicle, p)

    #    clean and lock
    attributeFunctions.lockAndHideTransforms(follicle)
    attributeFunctions.lockAll(follicleShp)
    cmds.select(cl=True)

    return follicle
Exemple #45
0
    def install_custom(self, joints):
        cmds.select(clear=True)
        ikJoints = []

        if not self.mirrored:
            index = 0
            for joint in self.jointInfo:
                ikJoints.append(
                    cmds.joint(n=self.moduleNamespace + ":IK_" + joint[0],
                               p=joint[1],
                               absolute=True,
                               rotationOrder="xyz"))

                cmds.setAttr(ikJoints[index] + ".visibility", 0)

                if index != 0:
                    cmds.joint(ikJoints[index - 1],
                               edit=True,
                               oj="xyz",
                               sao="yup")

                index += 1
        else:
            rootJointName = self.jointInfo[0][0]
            tempDuplicateNodes = cmds.duplicate(self.originalModule + ":IK_" +
                                                rootJointName,
                                                renameChildren=True)

            cmds.delete(tempDuplicateNodes.pop())

            mirrorXY = False
            mirrorYZ = False
            mirrorXZ = False
            if self.mirrorPlane == "XY":
                mirrorXY = True
            elif self.mirrorPlane == "YZ":
                mirrorYZ = True
            elif self.mirrorPlane == "XZ":
                mirrorXZ = True

            mirrorBehavior = False
            if self.rotationFunction == "behavior":
                mirrorBehavior = True

            mirrorJoints = cmds.mirrorJoint(tempDuplicateNodes[0],
                                            mirrorXY=mirrorXY,
                                            mirrorXZ=mirrorXZ,
                                            mirrorYZ=mirrorYZ,
                                            mirrorBehavior=mirrorBehavior)

            cmds.delete(tempDuplicateNodes)

            cmds.xform(mirrorJoints[0],
                       ws=True,
                       a=True,
                       translation=cmds.xform(self.moduleNamespace + ":" +
                                              rootJointName,
                                              q=True,
                                              ws=True,
                                              t=True))

            for i in range(3):
                jointName = self.jointInfo[i][0]
                newName = cmds.rename(
                    mirrorJoints[i], self.moduleNamespace + ":IK_" + jointName)
                ikJoints.append(newName)

        utils.addNodeToContainer(self.containerName, ikJoints)

        for joint in ikJoints:
            jointName = utils.stripAllNamespaces(joint)[1]
            cmds.container(
                self.containerName,
                edit=True,
                publishAndBind=[joint + ".rotate", jointName + "_R"])

        cmds.setAttr(ikJoints[0] + ".preferredAngleY", -50.0)
        cmds.setAttr(ikJoints[1] + ".preferredAngleY", 50.0)

        # Call on the stretchy ik function from utils
        ikNodes = utils.RP_2segment_stretchy_IK(ikJoints[0], ikJoints[1],
                                                ikJoints[2],
                                                self.containerName)
        locators = (ikNodes[0], ikNodes[1], ikNodes[2])
        distanceNodes = ikNodes[3]

        # Point constraint stretch locators to transform control objects
        constraints = []
        for i in range(3):
            constraints.append(
                cmds.pointConstraint(self.getTranslationControl(joints[i]),
                                     locators[i],
                                     maintainOffset=False)[0])
            cmds.parent(locators[i],
                        self.moduleNamespace + ":module_grp",
                        absolute=True)
            cmds.setAttr(locators[i] + ".visibility", 0)

        utils.addNodeToContainer(self.containerName, constraints)

        scaleTarget = self.getTranslationControl(joints[1])
        paRepresentation = self.createPreferredAngleRepresentation(
            ikJoints[1], scaleTarget)

        cmds.setAttr(paRepresentation + ".axis", lock=True)
Exemple #46
0
def createLoc():
    mc.spaceLocator(n='FootLoc')
    mc.scale(0.6, 0.6, 0.6)
    mc.color(rgb=(0, 0, 1))

    mc.spaceLocator(n='AnkleLoc')
    mc.move(0, head * 0.5, 0)
    mc.scale(0.2, 0.2, 0.2)
    mc.color(rgb=(0.5, 0, 0))

    mc.spaceLocator(n='KneeLoc')
    mc.move(0, head * 2, 0)
    mc.scale(0.3, 0.3, 0.3)
    mc.color(rgb=(0.5, 0.2, 0))

    mc.spaceLocator(n='PelvisLoc')
    mc.move(0, head * 4, 0)
    mc.scale(0.4, 0.4, 0.4)
    mc.color(rgb=(0.5, 0.2, 0.5))

    mc.spaceLocator(n='NeckLoc')
    mc.move(0, head * 6.5, 0)
    mc.scale(0.2, 0.2, 0.2)
    mc.color(rgb=(0, 0.2, 0.5))

    mc.spaceLocator(n='ShoulderLeftLoc')
    mc.move(head, head * 6.5, 0)
    mc.scale(0.2, 0.2, 0.2)
    mc.color(rgb=(0, 0.2, 0.5))

    mc.spaceLocator(n='ElbowLeftLoc')
    mc.move(head * 2.5, head * 6.5, 0)
    mc.scale(0.2, 0.2, 0.2)
    mc.color(rgb=(0, 0.2, 0.5))

    mc.spaceLocator(n='WristLeftLoc')
    mc.move(head * 3.7, head * 6.5, 0)
    mc.scale(0.2, 0.2, 0.2)
    mc.color(rgb=(0, 0.2, 0.5))

    mc.spaceLocator(n='IndexLoc3')
    mc.move(head * 4.4, head * 6.5, 0)
    mc.scale(0.1, 0.1, 0.1)
    mc.color(rgb=(0, 0.2, 0.5))

    mc.spaceLocator(n='IndexLoc0')
    fingerEnd = mc.getAttr('IndexLoc3.tx')
    wrist = mc.getAttr('WristLeftLoc.tx')
    halfhand = wrist + (fingerEnd - wrist) * 0.5
    mc.move(halfhand, head * 6.5, 0)
    mc.scale(0.05, 0.05, 0.05)

    mc.spaceLocator(n='IndexLoc1')
    fingerEnd = mc.getAttr('IndexLoc3.tx')
    middlefingerRoot = mc.getAttr('IndexLoc0.tx')
    halfmiddleFinger = middlefingerRoot + (fingerEnd - middlefingerRoot) * 0.5
    mc.move(halfmiddleFinger, head * 6.5, 0)
    mc.scale(0.05, 0.05, 0.05)

    mc.spaceLocator(n='IndexLoc2')
    fingerEnd = mc.getAttr('IndexLoc3.tx')
    IndexLoc1 = mc.getAttr('IndexLoc1.tx')
    halfmiddleSecondFinger = IndexLoc1 + (fingerEnd - IndexLoc1) * 0.5
    mc.move(halfmiddleSecondFinger, head * 6.5, 0)
    mc.scale(0.05, 0.05, 0.05)

    mc.select('IndexLoc0', 'IndexLoc1', 'IndexLoc2', 'IndexLoc3')
    mc.move(0, 0, 0.2, r=True)

    mc.spaceLocator(n='ShoulderRightLoc')
    mc.move(-head, head * 6.5, 0)
    mc.scale(0.2, 0.2, 0.2)
    mc.color(rgb=(0, 0.2, 0.5))

    mc.spaceLocator(n='HeadLoc')
    mc.move(0, head * 7, 0)
    mc.scale(0.5, 0.5, 0.5)
    mc.color(rgb=(0, 0.2, 0.5))

    mc.spaceLocator(n='HeadEndLoc')
    mc.move(0, head * 8, 0)
    mc.scale(0.7, 0.7, 0.7)
    mc.color(rgb=(0, 0, 2))

    #other fingers besides index
    for i in range(3):
        mc.select('IndexLoc0', 'IndexLoc1', 'IndexLoc2', 'IndexLoc3')
        mc.duplicate()
        mc.move(0, 0, -0.2 * (i + 1), r=True)

    for j in range(4):
        mc.rename('IndexLoc' + str(j + 4), 'MiddleLoc' + str(j))
    for j in range(4, 8):
        mc.rename('IndexLoc' + str(j + 4), 'RingLoc' + str(j - 4))
    for j in range(8, 12):
        mc.rename('IndexLoc' + str(j + 4), 'PinkieLoc' + str(j - 8))
def move_pointer(x, y, z, m):
    cmds.select("pointer" + str(m))
    cmds.move(x, y, z, absolute=True, worldSpace=True, worldSpaceDistance=True)
Exemple #48
0
	def selObj(self , tex = None , *args):
		cmds.select(cmds.textScrollList(tex,q=1,si=1))
def export_obj(name):
    obj_path = os.path.dirname(os.path.realpath(__file__)) + "/folded/snapshots/" + name + ".obj"
    print("Saving file as " + obj_path)
    cmds.select(clear=True)
    cmds.select("shirt")
    mel.eval('file -force -options "groups=0;ptgroups=1;materials=1;smoothing=1;normals=1" -typ "OBJexport" -pr -es "%s";' % obj_path)
def createRig(unusedBasename='DomeStereoCamera'):
    """
  Creates a new stereo rig. Uses a series of Maya commands to build
  a stereo rig.
  
  The optional argument basename defines the base name for each DAG
  object that will be created.
  """

    #Create a random camera letter "extension" to fix the unique camera issue with the camera aim, and aim+up add-on bug
    import string
    import random
    randomLetterPostfix = random.choice(string.ascii_uppercase)
    #print ("The StereoCameraRig Random letter extension is: DomeStereoCamera" + randomLetterPostfix)

    #Put a temp throwaway value of unusedBasename as the createRig input variable
    #Define basename here instead of the regular createRig() variable
    basename = 'DomeStereoCamera' + randomLetterPostfix

    # Create the root of the rig
    #
    root = cmds.createNode('stereoRigTransform', name=basename)

    # The actual basename use is the name of the top transform. If a
    # second rig is created, the default base name may be incremented
    # (e.g. stereoRig1). We want to use the same name for the whole
    # hierarchy.
    # If such a name already exists, root will be a partial path. Keep
    # only the last part for the name.
    #
    rootName = root.split('|')[-1]

    # Create the center (main) camera
    # Connect the center camera attributes to the root
    # Change any default parameters.
    #
    centerCam = cmds.createNode('stereoRigCamera',
                                name=rootName + 'CenterCamShape',
                                parent=root)
    for attr in [
            'stereo', 'interaxialSeparation', 'zeroParallax', 'toeInAdjust',
            'filmOffsetRightCam', 'filmOffsetLeftCam'
    ]:
        cmds.connectAttr(centerCam + '.' + attr, root + '.' + attr)
    cmds.connectAttr(centerCam + '.focalLength', root + '.focalLengthInput')
    #cmds.setAttr( centerCam + '.stereo', 2 )
    cmds.setAttr(centerCam + '.renderable', 0)

    # Create the Frustum node, connect it to the root.
    #
    frustum = __createFrustumNode(centerCam, root, rootName + 'Frustum')

    # Create the left & right eye cameras
    #
    leftCam = __createSlaveCamera(centerCam, rootName + 'Left', root)
    rightCam = __createSlaveCamera(centerCam, rootName + 'Right', root)

    # Set up message attribute connections to define the role of each camera
    #
    cmds.connectAttr(leftCam + '.message', frustum + '.leftCamera')
    cmds.connectAttr(rightCam + '.message', frustum + '.rightCamera')
    cmds.connectAttr(centerCam + '.message', frustum + '.centerCamera')

    # Connect the specific left and right output attributes of the root
    # transform to the corresponding left and right camera attributes.
    #
    cmds.connectAttr(root + '.stereoLeftOffset', leftCam + '.translateX')
    cmds.connectAttr(root + '.stereoRightOffset', rightCam + '.translateX')
    cmds.connectAttr(root + '.stereoLeftAngle', leftCam + '.rotateY')
    cmds.connectAttr(root + '.stereoRightAngle', rightCam + '.rotateY')
    cmds.connectAttr(root + '.filmBackOutputLeft', leftCam + '.hfo')
    cmds.connectAttr(root + '.filmBackOutputRight', rightCam + '.hfo')

    # Lock the attributes that should not be manipulated by the artist.
    #
    for attr in ['translate', 'rotate']:
        cmds.setAttr(leftCam + '.' + attr, lock=True)
        cmds.setAttr(rightCam + '.' + attr, lock=True)

        #---------------------------------------------------------------------------
        # Custom Domemaster3D Setup code
        #---------------------------------------------------------------------------
        import os
    import sys

    # 18 mm focal length = 90 degree FOV
    defaultRealtimeFOV = 18
    # 4 mm focal length = 160 degree FOV
    #defaultRealtimeFOV = 4

    domeOverrideFOV = int(
        os.getenv('DOMEMASTER3D_MAYA_REALTIME_FOV', defaultRealtimeFOV))

    if ((domeOverrideFOV >= 3) and (domeOverrideFOV <= 3500)):
        print("Using a Domemaster3D realtime viewport FOV value of " +
              str(domeOverrideFOV) + ".\n")
    else:
        print(
            "The \"DOMEMASTER3D_MAYA_REALTIME_FOV\" environment variable overridden FOV Value of "
            + str(domeOverrideFOV) +
            " is outside of the acceptable range of 3 mm to 3500mm that Maya accepts as a valid camera field of view value. The default value of "
            + str(defaultRealtimeFOV) + " will be used instead.\n")
        domeOverrideFOV = defaultRealtimeFOV

    # Use the default FOV value or pull the FOV value from the DOMEMASTER3D_MAYA_REALTIME_FOV env variable
    cmds.setAttr(centerCam + '.focalLength', domeOverrideFOV)

    # 4 mm focal length = 160 degree FOV
    #cmds.setAttr( centerCam + '.focalLength', 4 )

    # 18 mm focal length = 90 degree FOV
    #cmds.setAttr( centerCam + '.focalLength', 18 )

    #cmds.setAttr( centerCam + '.stereo', 0 )
    #cmds.setAttr( centerCam + '.zeroParallax', 0.1 )
    #cmds.setAttr( centerCam + '.interaxialSeparation', 0 )

    # Create the fulldome stereo lens shaders
    createLensShaders(centerCam, leftCam, rightCam)

    #Align the base camera to point upwards
    cmds.setAttr(root + '.rotateX', 90)
    cmds.setAttr(root + '.rotateY', 0)
    cmds.setAttr(root + '.rotateZ', 0)

    # Link the new attribute 'Cam Locator Scale' to the dome camera's locator size control
    cmds.addAttr(root,
                 longName='Cam_Locator_Scale',
                 niceName='Cam Locator Scale',
                 attributeType='double',
                 defaultValue=1.0,
                 minValue=0.01)
    cmds.setAttr(root + '.Cam_Locator_Scale', keyable=False, channelBox=True)

    # Result: Connected DomeStereoCamera.Cam_Locator_Scale to DomeStereoCameraLeftShape.locatorScale. //
    cmds.connectAttr(root + '.Cam_Locator_Scale',
                     centerCam + '.locatorScale',
                     force=True)
    cmds.connectAttr(root + '.Cam_Locator_Scale',
                     leftCam + '.locatorScale',
                     force=True)
    cmds.connectAttr(root + '.Cam_Locator_Scale',
                     rightCam + '.locatorScale',
                     force=True)

    #---------------------------------------------------------------------------
    cmds.select(root)

    return [root, leftCam, rightCam]
Exemple #51
0
def uiLoadParentNameObject(self, parentNameObject):
    assert mc.objExists(
        parentNameObject) is True, "'%s' doesn't exist" % parentNameObject
    mc.select(cl=True)
    mc.select(parentNameObject)
    uiLoadAutoNameObject(self)
def release_pointer(time, m):
    cmds.select(clear=True)
    mel.eval('select -tgl pointer' + str(m) + ';')
    mel.eval('setKeyframe -t ' + str(time) + ' { \"dynamicConstraintShape' + str(m) + '.gls\" };')
    mel.eval('setAttr \"dynamicConstraintShape' + str(m) + '.glueStrength\" 0;')
    mel.eval('setKeyframe -t ' + str(time+1) + ' { \"dynamicConstraintShape' + str(m) + '.gls\" };')
def ReplaceEyesWithExternalMeshes():
    oldEyes = mayaUtils.FindMeshByWildcard('FemaleEyes')
    jointLeft = cmds.ls('eye_l', type='joint')[0]
    jointRight = cmds.ls('eye_r', type='joint')[0]
    print oldEyes
    print jointLeft
    print jointRight

    #get old eyes mesh vertical (Y) size
    oldSizeY = mayaUtils.GetBoundingBox(oldEyes)[1]
    print oldSizeY
    cmds.delete(oldEyes)
    mayaUtils.CleanUnusedMaterials()

    print GetSharedResourcesPath()

    leftEyeFilePath = os.path.join(GetSharedResourcesPath(), 'Eye_Left.obj')
    print leftEyeFilePath
    leftEyeMesh = cmds.ls(cmds.file(leftEyeFilePath,
                                    i=True,
                                    returnNewNodes=True),
                          transforms=True)[0]
    externalSizeY = mayaUtils.GetBoundingBox(leftEyeMesh)[1]
    print externalSizeY

    rightEyeFilePath = os.path.join(GetSharedResourcesPath(), 'Eye_Right.obj')
    rightEyeMesh = cmds.ls(cmds.file(rightEyeFilePath,
                                     i=True,
                                     returnNewNodes=True),
                           transforms=True)[0]

    scaleFactor = oldSizeY / externalSizeY
    print 'Scale factor = {}'.format(scaleFactor)

    #scale and move new eyes
    cmds.scale(scaleFactor,
               scaleFactor,
               scaleFactor,
               leftEyeMesh,
               relative=True)
    cmds.matchTransform(leftEyeMesh, jointLeft, position=True, rotation=True)
    cmds.rotate(0, '90deg', 0, leftEyeMesh, relative=True)
    cmds.makeIdentity(leftEyeMesh,
                      apply=True,
                      translate=True,
                      rotate=True,
                      scale=True,
                      normal=1)
    cmds.delete(leftEyeMesh, constructionHistory=True)

    cmds.scale(scaleFactor,
               scaleFactor,
               scaleFactor,
               rightEyeMesh,
               relative=True)
    cmds.matchTransform(rightEyeMesh, jointRight, position=True, rotation=True)
    cmds.rotate(0, '90deg', 0, rightEyeMesh, relative=True)
    cmds.makeIdentity(rightEyeMesh,
                      apply=True,
                      translate=True,
                      rotate=True,
                      scale=True,
                      normal=1)
    cmds.delete(rightEyeMesh, constructionHistory=True)

    #binding
    cmds.skinCluster(jointLeft, leftEyeMesh, tsb=True)
    cmds.select(clear=True)

    cmds.skinCluster(jointRight, rightEyeMesh, tsb=True)
    cmds.select(clear=True)

    cmds.polyUniteSkinned([leftEyeMesh, rightEyeMesh], ch=False)
    cmds.rename('FemaleEyes')
    cmds.select(clear=True)

    sha = cmds.shadingNode('lambert', asShader=True, name='Eyes')
    sg = cmds.sets(empty=True,
                   renderable=True,
                   noSurfaceShader=True,
                   name='Eyes_sg')
    cmds.connectAttr(sha + '.outColor', sg + '.surfaceShader', f=True)
    cmds.sets('FemaleEyes', e=True, forceElement=sg)
Exemple #54
0
def copyAnimation(source=None,
                  destination=None,
                  pasteMethod='replace',
                  offset=0,
                  start=None,
                  end=None,
                  layer=None):
    '''
    Actually do the copy and paste from one node to another. If start and end frame is specified,
    set a temporary key before copying, and delete it afterward.
    '''

    if layer:
        mc.select(destination)
        mc.animLayer(layer, edit=True, addSelectedObjects=True)

        #we want to make sure rotation values are within 360 degrees, so we don't get flipping when blending layers.
        utl.minimizeRotationCurves(source)
        utl.minimizeRotationCurves(destination)

    if pasteMethod == 'replaceCompletely' or not start or not end:
        mc.copyKey(source)
        if layer:
            mc.animLayer(layer, edit=True, selected=True)
        mc.pasteKey(destination, option=pasteMethod, timeOffset=offset)
    else:

        #need to do this per animation curve, unfortunately, to make sure we're not adding or removing too many keys
        animCurves = mc.keyframe(source, query=True, name=True)
        if not animCurves:
            return

        #story cut keytimes as 2 separate lists means we only have to run 2 cutkey commands, rather than looping through each
        cutStart = list()
        cutEnd = list()
        for curve in animCurves:

            #does it have keyframes on the start and end frames?
            startKey = mc.keyframe(curve,
                                   time=(start, ),
                                   query=True,
                                   timeChange=True)
            endKey = mc.keyframe(curve,
                                 time=(end, ),
                                 query=True,
                                 timeChange=True)

            #if it doesn't set a temporary key for start and end
            #and store the curve name in the appropriate list
            if not startKey:
                mc.setKeyframe(curve, time=(start, ), insert=True)
                cutStart.append(curve)
            if not endKey:
                mc.setKeyframe(curve, time=(end, ), insert=True)
                cutEnd.append(curve)

        mc.copyKey(source, time=(start, end))
        if layer:
            for each in mc.ls(type='animLayer'):
                mc.animLayer(each, edit=True, selected=False, preferred=False)
            mc.animLayer(layer, edit=True, selected=True, preferred=True)
        mc.pasteKey(destination,
                    option=pasteMethod,
                    time=(start, end),
                    copies=1,
                    connect=0,
                    timeOffset=offset)

        #if we set temporary source keys, delete them now
        if cutStart:
            mc.cutKey(cutStart, time=(start, ))
        if cutEnd:
            mc.cutKey(cutEnd, time=(end, ))
def PostprocessGenitaliaObject(genitaliaMeshWildcard):
    with mayaUtils.DebugTimer(
            'PostprocessGenitaliaObject(genitaliaMeshWildcard={0})'.format(
                genitaliaMeshWildcard)):
        genitaliaMesh = mayaUtils.FindMeshByWildcard(genitaliaMeshWildcard)
        if not genitaliaMesh:
            print 'Genitalia mesh not found. Aborted'
            return

        print 'Processing {0}'.format(genitaliaMesh)

        genitaliaMesh = cmds.rename(genitaliaMesh,
                                    'FemaleGenitalia')  #rename to proper name

        #replace material with original torso mat
        facesWithTorsoMat = mayaUtils.GetFacesByMatsWildcard(
            genitaliaMesh, 'Torso*')
        mayaUtils.AssignObjectListToShader(facesWithTorsoMat,
                                           'Body')  #use new material name
        # mayaUtils.ArrangeUVByMat(genitaliaMesh, 'Body', su=0.5, sv=0.5, u=0.5, v=0.5)
        mayaUtils.AppendShadingGroupByMat(genitaliaMesh, 'Anus', 'V****a')
        mayaUtils.RenameMaterial('Anus', 'BodyGenitalia')
        cmds.bakePartialHistory(genitaliaMesh, prePostDeformers=True)

        bodyMesh = mayaUtils.FindMeshByWildcard('FemaleBody' + '*',
                                                checkForMatWithName='Body')

        if not bodyMesh:
            print '{0} mesh not found. Aborted'
            return

        cmds.select(clear=True)
        borderVertsList = mayaUtils.GetBorderVertices(genitaliaMesh)
        borderVertsList = cmds.filterExpand(borderVertsList,
                                            sm=31,
                                            expand=True)

        bodySkinCluster = mayaUtils.GetSkinCluster(bodyMesh)
        genitaliaSkinCluster = mayaUtils.GetSkinCluster(genitaliaMesh)

        #transfer attributes manually
        for v in borderVertsList:
            pos = cmds.pointPosition(v, world=True)
            #print pos
            closestVert = mayaUtils.GetClosestVertex(bodyMesh, pos)
            closestVertPos = cmds.xform(closestVert, t=True, ws=True, q=True)
            closestVertNormal = cmds.polyNormalPerVertex(closestVert,
                                                         query=True,
                                                         xyz=True)

            # set position
            cmds.move(closestVertPos[0],
                      closestVertPos[1],
                      closestVertPos[2],
                      v,
                      absolute=True,
                      worldSpace=True)
            # set normal
            cmds.polyNormalPerVertex(v,
                                     xyz=(closestVertNormal[0],
                                          closestVertNormal[1],
                                          closestVertNormal[2]))

            referenceVertInfluences = cmds.skinPercent(bodySkinCluster,
                                                       closestVert,
                                                       query=True,
                                                       transform=None,
                                                       ignoreBelow=0.00001)

            targetInfluences = cmds.skinCluster(genitaliaSkinCluster,
                                                query=True,
                                                influence=True)

            targetTransformValues = []

            for i in referenceVertInfluences:
                if i not in targetInfluences:
                    cmds.skinCluster(genitaliaSkinCluster,
                                     e=True,
                                     addInfluence=i,
                                     weight=0.0)
                    #print i
                referenceInfluenceValuePerVertex = cmds.skinPercent(
                    bodySkinCluster,
                    closestVert,
                    query=True,
                    transform=i,
                    transformValue=True)
                targetTransformValues.append(
                    (i, referenceInfluenceValuePerVertex))

            #print targetTransformValues

            # set weight
            cmds.skinPercent(genitaliaSkinCluster,
                             v,
                             transformValue=targetTransformValues)

        cmds.bakePartialHistory(genitaliaMesh, prePostDeformers=True)
def FixNewJointsOrientation():
    with mayaUtils.DebugTimer('FixNewJointsOrientation'):
        # Root
        mayaUtils.RotateJoint("DAZ_root", 0, 0, 0)

        # Spine
        CopyJointPosition('DAZ_pelvis', 'DAZ_thigh_l', 'yz')

        mayaUtils.RotateJoint("DAZ_pelvis", -90, 0, 90)
        mayaUtils.RotateJoint("DAZ_spine_01", -90, 0, 90)
        AimJointForUnreal('DAZ_spine_01', 'DAZ_spine_02')

        mayaUtils.RotateJoint("DAZ_spine_02", -90, 0, 90)
        AimJointForUnreal('DAZ_spine_02', 'DAZ_spine_03')

        mayaUtils.RotateJoint("DAZ_spine_03", -90, 0, 90)
        AimJointForUnreal('DAZ_spine_03', 'DAZ_neck_01')

        mayaUtils.RotateJoint("DAZ_breast_l", -90, 0, 0)
        mayaUtils.RotateJoint("DAZ_breast_r", 90, 0, 0)

        mayaUtils.RotateJoint("DAZ_neck_01", -90, 0, 90)
        AimJointForUnreal('DAZ_neck_01', 'DAZ_head')
        mayaUtils.RotateJoint("DAZ_head", -90, 0, 90)

        # Leg Left
        mayaUtils.RotateJoint("DAZ_thigh_l", -90, 0, 90)
        mayaUtils.RotateJoint("DAZ_thigh_twist_01_l", -90, 0, 90)
        mayaUtils.RotateJoint("DAZ_calf_l", -90, 0, 90)
        # copy rotation from Leg
        cmds.xform('DAZ_foot_l',
                   absolute=True,
                   rotation=cmds.xform('calf_l',
                                       q=True,
                                       absolute=True,
                                       rotation=True))
        mayaUtils.RotateJoint("DAZ_foot_l", -90, 0, 90)
        AimFootJoint('DAZ_foot_l',
                     'DAZ_ball_l',
                     inAimVector=[0, -1, 0],
                     inUpVector=[1, 0, 0])
        mayaUtils.RotateJoint("DAZ_ball_l", 0, -90,
                              0)  #TODO near but not ideal

        # Leg Right
        mayaUtils.RotateJoint("DAZ_thigh_r", 90, 0, -90)
        mayaUtils.RotateJoint("DAZ_thigh_twist_01_r", 90, 0, -90)
        mayaUtils.RotateJoint("DAZ_calf_r", 90, 0, -90)
        # copy rotation from Leg
        cmds.xform('DAZ_foot_r',
                   absolute=True,
                   rotation=cmds.xform('calf_r',
                                       q=True,
                                       absolute=True,
                                       rotation=True))
        mayaUtils.RotateJoint("DAZ_foot_r", 90, 0, -90)
        AimFootJoint('DAZ_foot_r',
                     'DAZ_ball_r',
                     inAimVector=[0, 1, 0],
                     inUpVector=[-1, 0, 0])
        mayaUtils.RotateJoint("DAZ_ball_r", 180, 90, 0)

        # Arm Left

        #TODO TEST
        CopyJointPosition('DAZ_clavicle_l', 'DAZ_spine_03', 'z')
        mayaUtils.RotateJoint("DAZ_clavicle_l", -90)

        AimJointForUnreal('DAZ_clavicle_l', 'DAZ_upperarm_l')
        mayaUtils.RotateJoint("DAZ_upperarm_l", -90)
        mayaUtils.RotateJoint("DAZ_upperarm_twist_01_l", -90)
        mayaUtils.RotateJoint("DAZ_lowerarm_l", -90)
        mayaUtils.RotateJoint("DAZ_lowerarm_twist_01_l", -90)
        mayaUtils.RotateJoint("DAZ_hand_l", -180)

        mayaUtils.RotateJoint('DAZ_thumb_01_l', -90)
        mayaUtils.RotateJoint('DAZ_thumb_02_l', -90)
        mayaUtils.RotateJoint('DAZ_thumb_03_l', -90)

        #mayaUtils.RotateJoint('DAZ_HandIndex0_L', 90)
        mayaUtils.RotateJoint('DAZ_index_01_l', 180)
        mayaUtils.RotateJoint('DAZ_index_02_l', 180)
        mayaUtils.RotateJoint('DAZ_index_03_l', 180)

        #mayaUtils.RotateJoint('DAZ_HandMid0_L', 90)
        mayaUtils.RotateJoint('DAZ_middle_01_l', 180)
        mayaUtils.RotateJoint('DAZ_middle_02_l', 180)
        mayaUtils.RotateJoint('DAZ_middle_03_l', 180)

        #mayaUtils.RotateJoint('DAZ_HandRing0_L', 90)
        mayaUtils.RotateJoint('DAZ_ring_01_l', 180)
        mayaUtils.RotateJoint('DAZ_ring_02_l', 180)
        mayaUtils.RotateJoint('DAZ_ring_03_l', 180)

        #mayaUtils.RotateJoint('DAZ_HandPinky0_L', 90)
        mayaUtils.RotateJoint('DAZ_pinky_01_l', 180)
        mayaUtils.RotateJoint('DAZ_pinky_02_l', 180)
        mayaUtils.RotateJoint('DAZ_pinky_03_l', 180)

        # Arm Right
        #TODO TEST
        CopyJointPosition('DAZ_clavicle_r', 'DAZ_spine_03', 'z')

        mayaUtils.RotateJoint("DAZ_clavicle_r", 90)
        AimJointForUnreal('DAZ_clavicle_r',
                          'DAZ_upperarm_r',
                          inAimVector=[-1.0, 0.0, 0.0])
        mayaUtils.RotateJoint("DAZ_upperarm_r", 90)
        mayaUtils.RotateJoint("DAZ_upperarm_twist_01_r", 90)
        mayaUtils.RotateJoint("DAZ_lowerarm_r", 90)
        mayaUtils.RotateJoint("DAZ_lowerarm_twist_01_r", 90)
        mayaUtils.RotateJoint("DAZ_hand_r", 0)

        mayaUtils.RotateJoint('DAZ_thumb_01_r', 90)
        mayaUtils.RotateJoint('DAZ_thumb_02_r', 90)
        mayaUtils.RotateJoint('DAZ_thumb_03_r', 90)

        #mayaUtils.RotateJoint('DAZ_HandIndex0_R', -90, 180)
        mayaUtils.RotateJoint('DAZ_index_01_r', 0)
        mayaUtils.RotateJoint('DAZ_index_02_r', 0)
        mayaUtils.RotateJoint('DAZ_index_03_r', 0)

        #mayaUtils.RotateJoint('DAZ_HandMid0_R', -90, 180)
        mayaUtils.RotateJoint('DAZ_middle_01_r', 0)
        mayaUtils.RotateJoint('DAZ_middle_02_r', 0)
        mayaUtils.RotateJoint('DAZ_middle_03_r', 0)

        #mayaUtils.RotateJoint('DAZ_HandRing0_R', -90, 180)
        mayaUtils.RotateJoint('DAZ_ring_01_r', 0)
        mayaUtils.RotateJoint('DAZ_ring_02_r', 0)
        mayaUtils.RotateJoint('DAZ_ring_03_r', 0)

        #mayaUtils.RotateJoint('DAZ_HandPinky0_R', -90, 180)
        mayaUtils.RotateJoint('DAZ_pinky_01_r', 0)
        mayaUtils.RotateJoint('DAZ_pinky_02_r', 0)
        mayaUtils.RotateJoint('DAZ_pinky_03_r', 0)

        #Toes
        for t in [
                'toebig_01', 'toebig_02', 'toeindex_01', 'toeindex_02',
                'toemid_01', 'toemid_02', 'toering_01', 'toering_02',
                'toepinky_01', 'toepinky_02'
        ]:
            mayaUtils.RotateJoint('DAZ_' + t + '_l', 0, 90)
            mayaUtils.RotateJoint('DAZ_' + t + '_r', 0, -90)

        # facial rig
        mayaUtils.RotateJoint("DAZ_tongue_01", 0, -90, 0)
        mayaUtils.RotateJoint("DAZ_tongue_02", 0, -90, 0)
        mayaUtils.RotateJoint("DAZ_tongue_03", 0, -90, 0)
        mayaUtils.RotateJoint("DAZ_tongue_04", 0, -90, 0)

        mayaUtils.RotateJoint("DAZ_eye_l", 0, -90, 180)
        mayaUtils.RotateJoint("DAZ_eye_r", 0, -90, 180)

        # selecting original joints of face rig
        children = cmds.listRelatives('DAZ_head', allDescendents=True) or []

        for child in children:
            if child in ['DAZ_eye_l', 'DAZ_eye_r'
                         ] or child.startswith('DAZ_tongue_'):
                continue  # skip already rotated
            mayaUtils.RotateJoint('DAZ_' + child, 0, -90,
                                  0)  # but rotating skeleton copy

        cmds.select(clear=True)
Exemple #57
0
        def thighJnts(side):

            import maya.cmds as mc

            # refer to the no roll attribute control
            attrCtrl = "%s_leg_SW_ctrl" % side
            rev = mc.createNode("reverse", n="%s_leg_01_no_twist_rev" % side)
            mc.connectAttr("%s.%s_nr" % (attrCtrl, side), "%s.ix" % rev)

            # refer to thigh joints
            jnt1 = ("%s_leg_01_deform_ctrl_01" % side)
            jnt2 = ("%s_leg_01_deform_ctrl_02" % side)
            jnt3 = ("%s_leg_01_deform_ctrl_03" % side)
            jnt4 = ("%s_leg_01_deform_ctrl_04" % side)

            # refer to thigh nt joints
            ntjnt1 = ("%s_leg_01_no_twist_ctrl_01" % side)
            ntjnt2 = ("%s_leg_01_no_twist_ctrl_02" % side)
            ntjnt3 = ("%s_leg_01_no_twist_ctrl_03" % side)
            ntjnt4 = ("%s_leg_01_no_twist_ctrl_04" % side)

            # controls
            tempCrcl1 = mc.circle(n="%s_tempCircle1" % side)
            mc.delete(tempCrcl1, ch=True)
            mc.rotate(90, 0, 0, "%s.cv[0:9]" % tempCrcl1[0], r=1)
            mc.scale(1.2, .6, .3, "%s.cv[0:9]" % tempCrcl1[0], r=1)
            mc.parent("%sShape" % tempCrcl1[0], ntjnt1, s=True, r=True)
            mc.select(cl=True)
            mc.delete(tempCrcl1[0])

            oriConst1 = mc.orientConstraint(jnt1, ntjnt1, mo=True)
            mc.connectAttr("%s.ox" % rev, "%s.w0" % oriConst1[0])

            tempCrcl2 = mc.circle(n="%s_tempCircle2" % side)
            mc.delete(tempCrcl2, ch=True)
            mc.rotate(90, 0, 0, "%s.cv[0:9]" % tempCrcl2[0], r=1)
            mc.scale(1.2, .6, .3, "%s.cv[0:9]" % tempCrcl2[0], r=1)
            mc.parent("%sShape" % tempCrcl2[0], ntjnt2, s=True, r=True)
            mc.select(cl=True)
            mc.delete(tempCrcl2[0])

            oriConst2 = mc.orientConstraint(jnt2, ntjnt2, mo=True)
            mc.connectAttr("%s.ox" % rev, "%s.w0" % oriConst2[0])

            tempCrcl3 = mc.circle(n="%s_tempCircle3" % side)
            mc.delete(tempCrcl3, ch=True)
            mc.rotate(90, 0, 0, "%s.cv[0:9]" % tempCrcl3[0], r=1)
            mc.scale(1.2, .6, .3, "%s.cv[0:9]" % tempCrcl3[0], r=1)
            mc.parent("%sShape" % tempCrcl3[0], ntjnt3, s=True, r=True)
            mc.select(cl=True)
            mc.delete(tempCrcl3[0])

            oriConst3 = mc.orientConstraint(jnt3, ntjnt3, mo=True)
            mc.connectAttr("%s.ox" % rev, "%s.w0" % oriConst3[0])

            tempCrcl4 = mc.circle(n="%s_tempCircle4" % side)
            mc.delete(tempCrcl4, ch=True)
            mc.rotate(90, 0, 0, "%s.cv[0:9]" % tempCrcl4[0], r=1)
            mc.scale(1.2, .6, .3, "%s.cv[0:9]" % tempCrcl4[0], r=1)
            mc.parent("%sShape" % tempCrcl4[0], ntjnt4, s=True, r=True)
            mc.select(cl=True)
            mc.delete(tempCrcl4[0])

            oriConst4 = mc.orientConstraint(jnt4, ntjnt4, mo=True)
            mc.connectAttr("%s.ox" % rev, "%s.w0" % oriConst4[0])

            theSet = mc.sets(ntjnt1,
                             ntjnt2,
                             ntjnt3,
                             ntjnt4,
                             n="%s_thigh_NoTwistJoints_skin_set" % side)
            mc.sets(theSet, add="skin_set")
def CollapseUVTile(shape, pUVtile):
    cmds.select(clear=True)
    print 'CollapseUVTile shape: {0}, pUVtile: {1}'.format(shape, pUVtile)
    matched_faces = selUtils.GetFacesInUTile(shape, pUVtile)
    cmds.polyEditUV(matched_faces, relative=True, uValue=(-1.0 * pUVtile))
    cmds.select(clear=True)
Exemple #59
0
        def legsfollicles(side, section):

            import maya.cmds as mc

            # list important objects
            constantName = ("%s_leg_%s_deform" % (side, section))
            legSwitch = ("%s_leg_SW_ctrl" % side)
            deformGRP = ("%s_leg_%s_deform_grp" % (side, section))
            surface = ("%s_ns_no_twist" % constantName)

            # first transformGeometry
            tg0 = mc.createNode("transformGeometry", n="%s_tg0" % surface)
            mc.connectAttr(
                "%sShape.local" % surface,
                "%s.ig" % tg0,
            )
            mc.connectAttr("%s.wim" % deformGRP, "%s.txf" % tg0)

            # first curveFromSurfaceIso
            cfsi0 = mc.createNode("curveFromSurfaceIso",
                                  n="%s_cfsi0" % surface)
            mc.connectAttr("%s.og" % tg0, "%s.is" % cfsi0)
            mc.setAttr("%s.minValue" % cfsi0, 0)
            mc.setAttr("%s.maxValue" % cfsi0, 1)

            # second curveFromSurfaceIso
            cfsi1 = mc.createNode("curveFromSurfaceIso",
                                  n="%s_cfsi1" % surface)
            mc.connectAttr("%s.og" % tg0, "%s.is" % cfsi1)
            mc.setAttr("%s.minValue" % cfsi1, 0)
            mc.setAttr("%s.maxValue" % cfsi1, 1)
            mc.setAttr("%s.iv" % cfsi1, 1)

            # first rebuildCurve
            rc0 = mc.createNode("rebuildCurve", n="%s_rc0" % surface)
            mc.connectAttr("%s.oc" % cfsi0, "%s.ic" % rc0)
            mc.setAttr("%s.keepRange" % rc0, 0)

            # second rebuildCurve
            rc1 = mc.createNode("rebuildCurve", n="%s_rc1" % surface)
            mc.connectAttr("%s.oc" % cfsi1, "%s.ic" % rc1)
            mc.setAttr("%s.keepRange" % rc1, 0)

            # evenspread switch
            essw = mc.createNode("blendTwoAttr", n="%s_essw" % surface)
            mc.connectAttr("%s.evenspread" % deformGRP, "%s.ab" % essw)
            mc.setAttr("%s.i[0]" % essw, 1)

            # first avgCurves
            ac0 = mc.createNode("avgCurves", n="%s_ac0" % surface)
            mc.connectAttr("%s.oc" % cfsi0, "%s.ic1" % ac0)
            mc.connectAttr("%s.oc" % rc0, "%s.ic2" % ac0)
            mc.connectAttr("%s.o" % essw, "%s.w1" % ac0)
            mc.connectAttr("%s.evenspread" % deformGRP, "%s.w2" % ac0)
            mc.setAttr("%s.automaticWeight" % ac0, 0)

            # second avgCurves
            ac1 = mc.createNode("avgCurves", n="%s_ac1" % surface)
            mc.connectAttr("%s.oc" % cfsi1, "%s.ic1" % ac1)
            mc.connectAttr("%s.oc" % rc1, "%s.ic2" % ac1)
            mc.connectAttr("%s.o" % essw, "%s.w1" % ac1)
            mc.connectAttr("%s.evenspread" % deformGRP, "%s.w2" % ac1)
            mc.setAttr("%s.automaticWeight" % ac1, 0)

            # loft
            loft = mc.createNode("loft", n="%s_loft" % surface)
            mc.connectAttr("%s.oc" % ac0, "%s.ic[0]" % loft)
            mc.connectAttr("%s.oc" % ac1, "%s.ic[1]" % loft)
            mc.setAttr("%s.uniform" % loft, 1)
            mc.setAttr("%s.autoReverse" % loft, 0)
            mc.setAttr("%s.reverseSurfaceNormals" % loft, 1)

            # second transformGeometry
            tg1 = mc.createNode("transformGeometry", n="%s_tg1" % surface)
            mc.connectAttr(
                "%s.os" % loft,
                "%s.ig" % tg1,
            )
            mc.connectAttr("%s.wm[0]" % deformGRP, "%s.txf" % tg1)

            # --------------------------

            # follicles

            # first follicle
            fol1 = mc.createNode("follicle", n="%s_att_01Shape" % surface)
            mc.connectAttr("%s.og" % tg1, "%s.is" % fol1)
            mc.connectAttr("%s.outRotate" % fol1, "%s_att_01.r" % surface)
            mc.connectAttr("%s.outTranslate" % fol1, "%s_att_01.t" % surface)
            mc.parent("%s_att_01" % surface, deformGRP)
            mc.setAttr("%s.parameterU" % fol1, 0.125)
            mc.setAttr("%s.parameterV" % fol1, 0.5)
            mc.setAttr("%s_att_01.inheritsTransform" % surface, 0)

            # second follicle
            fol2 = mc.createNode("follicle", n="%s_att_02Shape" % surface)
            mc.connectAttr("%s.og" % tg1, "%s.is" % fol2)
            mc.connectAttr("%s.outRotate" % fol2, "%s_att_02.r" % surface)
            mc.connectAttr("%s.outTranslate" % fol2, "%s_att_02.t" % surface)
            mc.parent("%s_att_02" % surface, deformGRP)
            mc.setAttr("%s.parameterU" % fol2, 0.375)
            mc.setAttr("%s.parameterV" % fol2, 0.5)
            mc.setAttr("%s_att_02.inheritsTransform" % surface, 0)

            # third follicle
            fol3 = mc.createNode("follicle", n="%s_att_03Shape" % surface)
            mc.connectAttr("%s.og" % tg1, "%s.is" % fol3)
            mc.connectAttr("%s.outRotate" % fol3, "%s_att_03.r" % surface)
            mc.connectAttr("%s.outTranslate" % fol3, "%s_att_03.t" % surface)
            mc.parent("%s_att_03" % surface, deformGRP)
            mc.setAttr("%s.parameterU" % fol3, 0.625)
            mc.setAttr("%s.parameterV" % fol3, 0.5)
            mc.setAttr("%s_att_03.inheritsTransform" % surface, 0)

            # fourth follicle
            fol4 = mc.createNode("follicle", n="%s_att_04Shape" % surface)
            mc.connectAttr("%s.og" % tg1, "%s.is" % fol4)
            mc.connectAttr("%s.outRotate" % fol4, "%s_att_04.r" % surface)
            mc.connectAttr("%s.outTranslate" % fol4, "%s_att_04.t" % surface)
            mc.parent("%s_att_04" % surface, deformGRP)
            mc.setAttr("%s.parameterU" % fol4, 0.875)
            mc.setAttr("%s.parameterV" % fol4, 0.5)
            mc.setAttr("%s_att_04.inheritsTransform" % surface, 0)

            # --------------------------

            # post follicle actions

            # first orig joint
            jntOrig1 = mc.duplicate(
                "%s_leg_%s_deform_SKN_01_orig" % (side, section),
                po=True,
                n="%s_leg_%s_no_twist_SKN_01_orig" % (side, section),
                ic=False)
            mc.setAttr("%s.v" % jntOrig1[0], k=True, cb=True, l=False)
            mc.setAttr("%s.v" % jntOrig1[0], 1)
            mc.setAttr("%s.ds" % jntOrig1[0], 0)
            jnt1 = mc.joint(n="%s_leg_%s_no_twist_SKN_01" % (side, section))
            mc.parent(jnt1, jntOrig1[0], r=True)
            mc.select(cl=True)
            jntCtrl1 = mc.joint(n="%s_leg_%s_no_twist_ctrl_01" %
                                (side, section))
            mc.parent(jntCtrl1, jntOrig1[0], r=True)
            mc.parent(jntOrig1[0], "%s_att_01" % surface, r=True)
            mc.parent(jntOrig1[0], deformGRP)
            mc.setAttr("%s.drawStyle" % jntOrig1[0], 2)
            mc.setAttr("%s.drawStyle" % jnt1, 2)
            mc.setAttr("%s.drawStyle" % jntCtrl1, 2)

            # first multMatrix
            mm1 = mc.createNode("multMatrix",
                                n="%s_leg_%s_no_twist_SKN_01_mm" %
                                (side, section))
            mc.connectAttr("%s_att_01.m" % surface, "%s.i[0]" % mm1)
            mc.connectAttr("%s.pim" % jntOrig1[0], "%s.i[1]" % mm1)

            # first decomposeMatrix
            dm1 = mc.createNode("decomposeMatrix",
                                n="%s_leg_%s_no_twist_SKN_01_dm" %
                                (side, section))
            mc.connectAttr("%s.o" % mm1, "%s.inputMatrix" % dm1)
            mc.connectAttr("%s.outputRotate" % dm1, "%s.r" % jntOrig1[0])
            mc.connectAttr("%s.outputTranslate" % dm1, "%s.t" % jntOrig1[0])
            mc.setAttr("%s.jo" % jntOrig1[0], 0, 0, 0)

            # connect joints accordingly
            mc.connectAttr("%s.t" % jntCtrl1, "%s.t" % jnt1)
            mc.connectAttr("%s.r" % jntCtrl1, "%s.r" % jnt1)
            mc.connectAttr("%s.s" % jntCtrl1, "%s.s" % jnt1)
            mc.connectAttr("%s.ro" % jntCtrl1, "%s.ro" % jnt1)

            # second orig joint
            jntOrig2 = mc.duplicate(
                "%s_leg_%s_deform_SKN_02_orig" % (side, section),
                po=True,
                n="%s_leg_%s_no_twist_SKN_02_orig" % (side, section),
                ic=False)
            mc.setAttr("%s.v" % jntOrig2[0], k=True, cb=True, l=False)
            mc.setAttr("%s.v" % jntOrig2[0], 1)
            mc.setAttr("%s.ds" % jntOrig2[0], 0)
            jnt2 = mc.joint(n="%s_leg_%s_no_twist_SKN_02" % (side, section))
            mc.parent(jnt2, jntOrig2[0], r=True)
            mc.select(cl=True)
            jntCtrl2 = mc.joint(n="%s_leg_%s_no_twist_ctrl_02" %
                                (side, section))
            mc.parent(jntCtrl2, jntOrig2[0], r=True)
            mc.parent(jntOrig2[0], "%s_att_02" % surface, r=True)
            mc.parent(jntOrig2[0], deformGRP)
            mc.setAttr("%s.drawStyle" % jntOrig2[0], 2)
            mc.setAttr("%s.drawStyle" % jnt2, 2)
            mc.setAttr("%s.drawStyle" % jntCtrl2, 2)

            # second multMatrix
            mm2 = mc.createNode("multMatrix",
                                n="%s_leg_%s_no_twist_SKN_02_mm" %
                                (side, section))
            mc.connectAttr("%s_att_02.m" % surface, "%s.i[0]" % mm2)
            mc.connectAttr("%s.pim" % jntOrig2[0], "%s.i[1]" % mm2)

            # second decomposeMatrix
            dm2 = mc.createNode("decomposeMatrix",
                                n="%s_leg_%s_no_twist_SKN_02_dm" %
                                (side, section))
            mc.connectAttr("%s.o" % mm2, "%s.inputMatrix" % dm2)
            mc.connectAttr("%s.outputRotate" % dm2, "%s.r" % jntOrig2[0])
            mc.connectAttr("%s.outputTranslate" % dm2, "%s.t" % jntOrig2[0])
            mc.setAttr("%s.jo" % jntOrig2[0], 0, 0, 0)

            # connect joints accordingly
            mc.connectAttr("%s.t" % jntCtrl2, "%s.t" % jnt2)
            mc.connectAttr("%s.r" % jntCtrl2, "%s.r" % jnt2)
            mc.connectAttr("%s.s" % jntCtrl2, "%s.s" % jnt2)
            mc.connectAttr("%s.ro" % jntCtrl2, "%s.ro" % jnt2)

            # third orig joint
            jntOrig3 = mc.duplicate(
                "%s_leg_%s_deform_SKN_03_orig" % (side, section),
                po=True,
                n="%s_leg_%s_no_twist_SKN_03_orig" % (side, section),
                ic=False)
            mc.setAttr("%s.v" % jntOrig3[0], k=True, cb=True, l=False)
            mc.setAttr("%s.v" % jntOrig3[0], 1)
            mc.setAttr("%s.ds" % jntOrig3[0], 0)
            jnt3 = mc.joint(n="%s_leg_%s_no_twist_SKN_03" % (side, section))
            mc.parent(jnt3, jntOrig3[0], r=True)
            mc.select(cl=True)
            jntCtrl3 = mc.joint(n="%s_leg_%s_no_twist_ctrl_03" %
                                (side, section))
            mc.parent(jntCtrl3, jntOrig3[0], r=True)
            mc.parent(jntOrig3[0], "%s_att_03" % surface, r=True)
            mc.parent(jntOrig3[0], deformGRP)
            mc.setAttr("%s.drawStyle" % jntOrig3[0], 2)
            mc.setAttr("%s.drawStyle" % jnt3, 2)
            mc.setAttr("%s.drawStyle" % jntCtrl3, 2)

            # third multMatrix
            mm3 = mc.createNode("multMatrix",
                                n="%s_leg_%s_no_twist_SKN_03_mm" %
                                (side, section))
            mc.connectAttr("%s_att_03.m" % surface, "%s.i[0]" % mm3)
            mc.connectAttr("%s.pim" % jntOrig3[0], "%s.i[1]" % mm3)

            # third decomposeMatrix
            dm3 = mc.createNode("decomposeMatrix",
                                n="%s_leg_%s_no_twist_SKN_03_dm" %
                                (side, section))
            mc.connectAttr("%s.o" % mm3, "%s.inputMatrix" % dm3)
            mc.connectAttr("%s.outputRotate" % dm3, "%s.r" % jntOrig3[0])
            mc.connectAttr("%s.outputTranslate" % dm3, "%s.t" % jntOrig3[0])
            mc.setAttr("%s.jo" % jntOrig3[0], 0, 0, 0)

            # connect joints accordingly
            mc.connectAttr("%s.t" % jntCtrl3, "%s.t" % jnt3)
            mc.connectAttr("%s.r" % jntCtrl3, "%s.r" % jnt3)
            mc.connectAttr("%s.s" % jntCtrl3, "%s.s" % jnt3)
            mc.connectAttr("%s.ro" % jntCtrl3, "%s.ro" % jnt3)

            # fourth orig joint
            jntOrig4 = mc.duplicate(
                "%s_leg_%s_deform_SKN_04_orig" % (side, section),
                po=True,
                n="%s_leg_%s_no_twist_SKN_04_orig" % (side, section),
                ic=False)
            mc.setAttr("%s.v" % jntOrig4[0], k=True, cb=True, l=False)
            mc.setAttr("%s.v" % jntOrig4[0], 1)
            mc.setAttr("%s.ds" % jntOrig4[0], 0)
            jnt4 = mc.joint(n="%s_leg_%s_no_twist_SKN_04" % (side, section))
            mc.parent(jnt4, jntOrig4[0], r=True)
            mc.select(cl=True)
            jntCtrl4 = mc.joint(n="%s_leg_%s_no_twist_ctrl_04" %
                                (side, section))
            mc.parent(jntCtrl4, jntOrig4[0], r=True)
            mc.parent(jntOrig4[0], "%s_att_04" % surface, r=True)
            mc.parent(jntOrig4[0], deformGRP)
            mc.setAttr("%s.drawStyle" % jntOrig4[0], 2)
            mc.setAttr("%s.drawStyle" % jnt4, 2)
            mc.setAttr("%s.drawStyle" % jntCtrl4, 2)

            # fourth multMatrix
            mm4 = mc.createNode("multMatrix",
                                n="%s_leg_%s_no_twist_SKN_04_mm" %
                                (side, section))
            mc.connectAttr("%s_att_04.m" % surface, "%s.i[0]" % mm4)
            mc.connectAttr("%s.pim" % jntOrig4[0], "%s.i[1]" % mm4)

            # fourth decomposeMatrix
            dm4 = mc.createNode("decomposeMatrix",
                                n="%s_leg_%s_no_twist_SKN_04_dm" %
                                (side, section))
            mc.connectAttr("%s.o" % mm4, "%s.inputMatrix" % dm4)
            mc.connectAttr("%s.outputRotate" % dm4, "%s.r" % jntOrig4[0])
            mc.connectAttr("%s.outputTranslate" % dm4, "%s.t" % jntOrig4[0])
            mc.setAttr("%s.jo" % jntOrig4[0], 0, 0, 0)

            # connect joints accordingly
            mc.connectAttr("%s.t" % jntCtrl4, "%s.t" % jnt4)
            mc.connectAttr("%s.r" % jntCtrl4, "%s.r" % jnt4)
            mc.connectAttr("%s.s" % jntCtrl4, "%s.s" % jnt4)
            mc.connectAttr("%s.ro" % jntCtrl4, "%s.ro" % jnt4)
def MakeBendCorrectiveJoint(name, referenceJnt, parentJnt, donorJntsList=None):
    if donorJntsList is None:
        donorJntsList = [parentJnt, referenceJnt]

    skinClusters = mayaUtils.GetAllSkinClustersInfluencedByJoints(
        donorJntsList, True)
    print 'Creating bend corrective joint {0} parented: {1}, referenced: {2}, skins: {3}'.format(
        name, parentJnt, referenceJnt, skinClusters)

    cmds.select(clear=True)
    cmds.select(referenceJnt)
    cmds.joint(name=name)
    if not parentJnt == referenceJnt:
        cmds.parent(name, parentJnt)

    cmds.orientConstraint(donorJntsList, name, maintainOffset=True)

    cmds.select(clear=True)

    for skinClusterName in skinClusters:
        cmds.skinCluster(skinClusterName,
                         e=True,
                         selectInfluenceVerts=donorJntsList[0])
        sel = cmds.ls(selection=True, flatten=True)
        onlyVertices = cmds.filterExpand(sel, sm=31, expand=True)
        intersectedVerts = []

        prune_value = 0.001

        for v in onlyVertices:
            if cmds.skinPercent(
                    skinClusterName, v, transform=donorJntsList[0],
                    query=True) > prune_value:
                if cmds.skinPercent(
                        skinClusterName, v, transform=donorJntsList[1],
                        query=True) > prune_value:
                    intersectedVerts.append(v)

        cmds.skinCluster(skinClusterName,
                         e=True,
                         addInfluence=name,
                         weight=0.0)
        cmds.select(clear=True)
        for v in intersectedVerts:
            sumNewWeight = 0
            transformValueList = []
            oldWeights = []
            jointsCount = len(donorJntsList)

            for j in donorJntsList:
                w = cmds.skinPercent(skinClusterName,
                                     v,
                                     transform=j,
                                     query=True)
                #print 'skinPercent Vert: {0} j:{1} w:{2}'.format(v, j, w)
                oldWeights.append(w)

            totalWeight = sum(oldWeights)

            for i in range(0, jointsCount):
                newWeight = oldWeights[i] * hazMath.SmoothStep01(
                    hazMath.Clamp01(oldWeights[i] / totalWeight))
                sumNewWeight += newWeight
                transformValueList.append([donorJntsList[i], newWeight])

            totalWeight -= prune_value

            transformValueList.append([
                name,
                hazMath.Clamp(totalWeight - sumNewWeight, 0.0, totalWeight)
            ])
            cmds.skinPercent(skinClusterName,
                             v,
                             transformValue=transformValueList)