Exemplo n.º 1
0
 def _plotter_avrg(self):
     '''plots a locator to a vertice or face per keyframe in a timeline'''
     selObj=cmds.ls(sl=1, fl=1)      
     if len(selObj)>0:
         pass
     else:
         print "Select 1 object" 
         return     
     getTopRange=cmds.playbackOptions(q=1, max=1)+1#get framerange of scene to set keys in iteration 
     getLowRange=cmds.playbackOptions(q=1, min=1)-1#get framerange of scene to set keys in iteration 
     edgeBucket=[]
     getRange=arange(getLowRange,getTopRange, 1 )
     getloc=cmds.spaceLocator(n=selObj[0]+"cnstr_lctr")
     cmds.normalConstraint(selObj[0], getloc[0])
     placeloc=cmds.spaceLocator(n=selObj[0]+"lctr")
     for each in getRange:
         cmds.currentTime(each)            
         transform=cmds.xform(selObj, q=1, ws=1, t=1)
         posBucketx=self.array_median_find(transform[0::3])
         posBuckety=self.array_median_find(transform[1::3])
         posBucketz=self.array_median_find(transform[2::3])
         cmds.xform(getloc[0], ws=1, t=(posBucketx, posBuckety, posBucketz))  
         cmds.SetKeyTranslate(getloc[0])
         cmds.xform(placeloc[0], ws=1, t=(posBucketx, posBuckety, posBucketz))
         cmds.SetKeyTranslate(placeloc[0])               
         rotate=cmds.xform(getloc[0], q=True, ws=1, ro=True)
         cmds.xform(placeloc[0], ws=1, ro=rotate)  
         cmds.SetKeyRotate(placeloc[0])
         cmds.currentTime(each)            
Exemplo n.º 2
0
def eyeRigFixes():
    # Fix normal constraint to locators
    selLocs = mc.ls(sl=True)
    target = 'CT_eyeBallHeadIntersecter_srf_0'
    zeroTarget = 'RT_eyeBallIntersect_srf_0'
    for eachLoc in selLocs:
        cons = mc.normalConstraint(target, eachLoc)
        mc.normalConstraint(zeroTarget, eachLoc, e=True, w=0)
Exemplo n.º 3
0
def addJntsOnSurfIntersection(surf1, surf2, jntsNum):
    '''
    Places jnts along intersection curve between surf1 and surf2
    naming convention based on surf1
    '''
    
    # intersect surfaces
    crvGrp, intNode = mc.intersect(surf1, surf2, fs=True, ch=True, o=True, cos=False)[:2]
    intNode = mc.rename(intNode, surf1+'_ints')
    crvGrp = mc.rename(crvGrp, surf1+'_ints_crv_grp')
    crv = mc.listRelatives(crvGrp, c=True)[0]
    crv = mc.rename(crv, surf1+'_ints_crv')
    
    # rebuild curve to jntNum spans
    rbdCrv, rbdNode = mc.rebuildCurve(crv, ch=True, o=True, rpo=False, spans=jntsNum, rt=0, kr=2, n=crv+'_rbd_crv')
    rbdNode = mc.rename(rbdNode, crv+'_rbd')
    
    # offset curve to control size of eye hole
    offsetCrv, offsetNode = mc.offsetCurve(rbdCrv, ch=True, distance=0, o=True, ugn=0, n=crv+'_offset_crv')
    offsetNode = mc.rename(offsetNode, crv+'_offset')
    
    locs = []
    locName = '_'.join(surf1.split('_')[:2])
    # attach locators to intersection curve
    for locId in range(jntsNum):
        loc = mc.spaceLocator(n=locName+'_loc_%d' % locId)[0]
        rt.attachToMotionPath(offsetCrv, locId, loc, fm=False)
        mc.setAttr(loc+'.localScale', 0.05, 0.05, 0.05)
        locs.append(loc)
        
    # normal constraint to surf1
    for loc in locs:
        mc.normalConstraint(surf2, loc, aim=(1,0,0))
    
    jnts = []
    # add joints under locators
    for loc in locs:
        mc.select(cl=True)
        jnt = mc.joint(n=loc.replace('_loc_','_jnt_'))
        rt.parentSnap(jnt, loc)
        mc.setAttr(jnt+'.jointOrient', 0,0,0)
        jnts.append(jnt)
        
    # groups
    grp = mc.group(crvGrp, offsetCrv, rbdCrv, locs, n=surf1+'_intersect_loc_grp')
    
    # create offset attribute
    mc.addAttr(grp, ln='collideOffset', at='double', dv=0, k=True)
    offsetPlug = cn.create_multDoubleLinear(grp+'.collideOffset', -1)
    mc.connectAttr(offsetPlug, offsetNode+'.distance', f=True)
    
    # connect debug
    rt.connectVisibilityToggle(offsetCrv, grp, 'offsetCrv', False)
    rt.connectVisibilityToggle(rbdCrv, grp, 'rebuildCrv', False)
    rt.connectVisibilityToggle(crvGrp, grp, 'intersectCrv', False)
    rt.connectVisibilityToggle(locs, grp, 'crvLocs', False)
    rt.connectVisibilityToggle(jnts, grp, 'crvJnts', False)
Exemplo n.º 4
0
def geometryNormalConstraintRun():
	currentSelection = cmds.ls(selection=True)

	if len(currentSelection) > 1:
		ground = currentSelection[len(currentSelection)- 1]

		for i in range(len(currentSelection) - 1):
			cmds.geometryConstraint(ground , currentSelection[i])
			cmds.normalConstraint(ground , currentSelection[i], aim=[0,1,0], u=[0,1,0], wut="Vector", wu=[0,1,0])
	else:
		cmds.confirmDialog(t="Warning", message="You must select at least two geometry objects. Last object will always be considered the ground target", button=["OK"], icon="warning")
Exemplo n.º 5
0
def surfaceControlCreate(ctrlLocs,ctrlDriveMesh,guideMesh,ctrlType='joint',ctrlShape='sphere',ctrlScale=0.05,ctrlLod='primary',prefix=''):
	'''
	Generate surface constrainted control
	@param ctrlLocs: 
	@type ctrlLocs: list
	@param ctrlDriveMesh: 
	@type ctrlDriveMesh: str
	@param guideMesh: 
	@type guideMesh: str
	@param ctrlType: 
	@type ctrlType: str
	@param ctrlShape: 
	@type ctrlShape: str
	@param ctrlScale: 
	@type ctrlScale: str
	@param ctrlLod: 
	@type ctrlLod: str
	@param prefix: Naming prefix for new nodes
	@type prefix: str
	'''
	# ==========
	# - Checks -
	# ==========
	
	# ===================================
	# - Constrain Locator To Drive Mesh -
	# ===================================
	
	# Build Target Vertex List
	vtxList = [ctrlDriveMesh+'.vtx['+str(mc.getAttr(loc+'.vtx'))+']' for loc in ctrlLocs]
	meshConstraint = glTools.tools.autoRivet.meshVertexConstraintList(vtxList,ctrlLocs,orient=False,prefix=prefix)
	
	# Orient Locators to Guide Mesh
	for loc in ctrlLocs:
		mc.delete( mc.normalConstraint(guideMesh,loc,aim=[0,0,1],u=[1,0,0],wut='vector',wu=[1,0,0]) )
	
	# =================================
	# - Create Controls From Locators -
	# =================================
	
	locCtrl = glTools.rig.face_utils.controlFromLocator(	ctrlLocs,
														ctrlType,
														ctrlShape,
														ctrlScale,
														ctrlLod,
														orient=True,
														parentToLoc=True	)
	
	# =================
	# - Return Result -
	# =================
	
	result = {}
	
	result['locator'] = ctrlLocs
	result['ctrl'] = locCtrl['ctrl']
	result['ctrlGrp'] = locCtrl['ctrlGrp']
	result['constraint'] = meshConstraint
	
	return result
Exemplo n.º 6
0
def jointPerVertex(ptList,orientSurface='',prefix='',suffix='jnt'):
	'''
	'''
	# Generate position list from input point
	posList = []
	for pt in ptList: posList.append(glTools.utils.base.getPosition(pt))
	
	# Create joints
	jntList = []
	for i in range(len(posList)):
		
		# Clear selection
		mc.select(cl=1)
		
		# Get string index
		strInd = glTools.utils.stringUtils.stringIndex(i+1,2)
		
		# Create joint
		jnt = mc.joint(n=prefix+'_'+strInd+'_'+suffix)
		# Position joint
		mc.move(posList[i][0],posList[i][1],posList[i][2],jnt,ws=True,a=True)
		
		# Orient joint
		if mc.objExists(orientSurface): mc.delete(mc.normalConstraint(orientSurface,jnt))
		
		# Append return list
		jntList.append(jnt)
	
	# Return Result
	return  jntList
Exemplo n.º 7
0
def doPositionLocator(locatorName,locInfo):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Position a locator with locator info generated from returnInfoForLoc

	ARGUMENTS:
	locatorName(string)
	locInfo(dict)

	RETURNS:
	success(bool)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	if search.returnObjectType(locatorName) == 'locator':
		objTrans = locInfo['position']
		objRot = locInfo['rotation']
		correctRo = locInfo['rotationOrder']

		mc.move (objTrans[0],objTrans[1],objTrans[2], locatorName)
		mc.setAttr ((locatorName+'.rotateOrder'), correctRo)

		#Rotate
		if locInfo['objectType'] == 'polyFace':
			constBuffer = mc.normalConstraint((locInfo['createdFrom']),locatorName)
			mc.delete(constBuffer[0])
		else:
			mc.rotate (objRot[0], objRot[1], objRot[2], locatorName, ws=True)

		return True
	else:
		guiFactory.warning('Not a locator.')
		return False
Exemplo n.º 8
0
def alignToUV(targetObj="none", sourceObj="none", sourceU=0.0, sourceV=0.0, mainAxis="+z", secAxis="+x", UorV="v"):
	"""
	inputs should be 1. targetObj 2. sourceObj 3. sourceU 4. sourceV 5. mainAxis(lowerCase, + or -, i.e."-x" 8. secAxis (lowcase, + or -) 7, UorV ("u" or "v" for the direction along surface for the sec axis)
"""

	axisDict = {"+x":(1,0,0), "+y":(0,1,0), "+z":(0,0,1), "-x":(-1,0,0), "-y":(0,-1,0), "-z":(0,0,-1)}

	#Does this create a new node? no To create a node, use the flag "ch=True". That creates a pointOnSurface node
	pos = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, position=True)
	posVec = om.MVector(pos[0], pos[1], pos[2])
	cmds.xform(targetObj, ws=True, t=pos)

	#get normal, tanU and tanV at selected UV position on source surface
	tanV = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tv=True)
	tanU = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tu=True)
	norm = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, nn=True)

	#decide where up axis is on normal constraint, u or v tangent
	if UorV == "v":
		wup = tanV
	elif UorV == "u":
		wup = tanU

	#create normal constraint
	nc = cmds.normalConstraint(sourceObj, targetObj, aimVector=axisDict[mainAxis], upVector=axisDict[secAxis], worldUpVector=(wup))
	cmds.delete(nc) #delete constraint
Exemplo n.º 9
0
def targetAliasList(constraint):
	'''
	Return a list of targets (drivers) attribute aliases for the specified constraint node
	@param constraint: The constraint node whose targets will be returned
	@type constraint: str
	'''
	# Check Constraint
	if not isConstraint(constraint):
		raise Exception('Constraint "'+constraint+'" does not exist!!')
	
	# Get Target List
	targetList = []
	constraintType = mc.objectType(constraint)
	if constraintType == 'aimConstraint': targetList = mc.aimConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'geometryConstraint': targetList = mc.geometryConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'normalConstraint': targetList = mc.normalConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'orientConstraint': targetList = mc.orientConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'parentConstraint': targetList = mc.parentConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'pointConstraint': targetList = mc.pointConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'poleVectorConstraint': targetList = mc.poleVectorConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'scaleConstraint': targetList = mc.scaleConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'tangentConstraint': targetList = mc.tangentConstraint(constraint,q=True,weightAliasList=True)
	
	# Check Target List
	if not targetList: targetList = []
	
	# Return Result
	return targetList
Exemplo n.º 10
0
 def __init__(self, root_obj_name, sel_name, run_option):
     # this function runs the script
     face_sel = cmds.ls(sl=True, fl=True) # makes a selection from the UI
     Face_Center()# passes the selection into Face_Center class to find centers of faces in face_sel
     self.run_option = run_option
     self.sel_name = sel_name
     self.dupe_geo_list = []
     for dummy_item in face_sel:                        
         for key, val in FACE_CENTER_DICT.iteritems(): # loops through global dict to find relevant coordinates
             if self.run_option == 'Instance':
                 dummy_new_geo = cmds.instance(root_obj_name)
             elif self.run_option == 'Duplicate':
                 dummy_new_geo = cmds.duplicate(root_obj_name)
             cmds.setAttr( str(dummy_new_geo[0])+'.translateX', val[0] )
             cmds.setAttr( str(dummy_new_geo[0])+'.translateY', val[1] )
             cmds.setAttr( str(dummy_new_geo[0])+'.translateZ', val[2] )
             dummy_constr = cmds.normalConstraint(dummy_item, str(dummy_new_geo[0]), aimVector = (0,1,0), u = (0,1,0), worldUpType= 0, wu = (0, 1, 0))
             cmds.delete(dummy_constr)
             self.dupe_geo_list.append(dummy_new_geo)
         cmds.setAttr( str(root_obj_name)+'.translateX', 0 )
         cmds.setAttr( str(root_obj_name)+'.translateY', 0 )
         cmds.setAttr( str(root_obj_name)+'.translateZ', 0 )
         cmds.setAttr( str(root_obj_name)+'.rotateX', 0 )
         cmds.setAttr( str(root_obj_name)+'.rotateY', 0 )
         cmds.setAttr( str(root_obj_name)+'.rotateZ', 0 )               
         FACE_CENTER_DICT.clear() # memory management purposes 
     self.sel_name_grp=cmds.group( em=True, name=self.sel_name ) # creates a group to house the duplicated geometries
     for dummy_geo in self.dupe_geo_list:
         cmds.parent( dummy_geo, str(self.sel_name_grp) )                
Exemplo n.º 11
0
def buildLinearPoints(	curve,
						numCtrl,
						useDistance	= False,
						guideSrf	= None,
						orient		= False,
						prefix		= None,
						suffix		= None ):
	'''
	Create locators along curve and project to mesh using geometry and normal constraints.
	'''
	# ==========
	# - Checks -
	# ==========
	
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(curve)
	if not suffix: suffix = 'jnt'
	
	# Build Controls
	ctrls = glTools.tools.createAlongCurve.create(	curve,
													'locator',
													objCount=numCtrl,
													parent=False,
													useDistance=useDistance,
													minPercent=0.0,
													maxPercent=1.0,
													spacing=1.0,
													prefix=prefix,
													suffix=suffix	)
	
	# Attach Controls
	for ctrl in ctrls:
		
		mc.select(ctrl)
		jnt = mc.joint()
		
		attach = glTools.utils.attach.attachToCurve(	curve,
													ctrl,
													useClosestPoint=True,
													uAttr='param',
													prefix=prefix	)
		
		# Constrain to Guide
		if guideSrf:
			
			# Constrain Position
			geomConst = mc.geometryConstraint(guideSrf,ctrl)[0]
			
			# Constrain Orient
			if orient:
				normConst = mc.normalConstraint(	guideSrf,
													ctrl,
													aimVector=(0,0,1),
													upVector=(-1,0,0),
													worldUpType='vector' )[0]
				
				mc.connectAttr(attach[0]+'.tangent',normConst+'.worldUpVector',f=True)
	
	# Return Result
	return ctrls
Exemplo n.º 12
0
def NomalCylinder():
	size = 0.5
	obj = mc.ls(sl=True,fl=True)
	if obj:
		for i in obj:
			val = 0
			cy  = mc.polyCylinder(r=size,h=2,sx=8,sy=1,sz=1,ax=(0,1,0),rcp=0,cuv=3,ch=1)
			pos = mc.xform(i,q=True,t=True,ws=True)
			for axis in ['X','Y','Z']:
				mc.setAttr('%s.translate%s'%(cy[0],axis),pos[val])
				val += 1
			source = i.split('.')
			mc.normalConstraint(source[0],cy,weight=1,aimVector=(0,1,0),upVector=(0,1,0),worldUpType="vector",worldUpVector=(0,1,0))
			mc.geometryConstraint(source[0],cy,weight=1)
		print 'Create!'
	else:
		print 'Not select'
Exemplo n.º 13
0
def attachObjectToMesh (obj, mesh, aim=False):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Rotation not working!
    DESCRIPTION:
    Script to rename a joint chain list
    
    ARGUMENTS:
    jointList(list) - list of joints in order
    startJointName(string) - what you want the root named
    interiorJointRootName(string) - what you want the iterative name to be
    
    RETURNS:
    newJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ Make a transform group """
    surfaceFollowGroup =  mc.group (w=True, empty=True)
    originalPosGroup = rigging.groupMeObject(obj,False)
    
    surfaceFollowGroup = mc.rename(surfaceFollowGroup,(obj+'_surfaceFollowGroup'))
    attributes.storeInfo(surfaceFollowGroup,'object',obj)  
    
    
    """ make the closest point node """
    closestPointNode = mc.createNode ('closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh,shapes=True)
    
    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((originalPosGroup+'.translate'),(closestPointNode+'.inPosition'))
    attributes.doConnectAttr((controlSurface[0]+'.worldMesh'),(closestPointNode+'.inMesh'))
    attributes.doConnectAttr((controlSurface[0]+'.worldMatrix'),(closestPointNode+'.inputMatrix'))

    """ Contect the locator to the info node"""
    attributes.doConnectAttr ((closestPointNode+'.position'),(surfaceFollowGroup+'.translate'))
    
    
    mc.normalConstraint(mesh,surfaceFollowGroup,worldUpType='object',worldUpObject=originalPosGroup)
    mc.parentConstraint(mesh,originalPosGroup, maintainOffset = True)
    return [surfaceFollowGroup]
Exemplo n.º 14
0
def orientTemplateToComponent():
    # Get selection
    selection = cmds.ls (sl=True)
    length = len(selection)
    
    # If statement to see if enough things were selected
    if length < 2:
        print "Not enough things selected to run script."
        
    else: 
        # First thing selected is controller
        thingA = selection[0] 
        
        # Second thing selected is the object/component you want to snap and orient template to
        thingB = selection[1]
        
        # Get position of thingB
        cmds.select (thingB, r=True)
        cmds.setToolTo('moveSuperContext')
        tempLoc =  cmds.spaceLocator(p=cmds.manipMoveContext('Move', q=True, p=True), a=True)
        cmds.xform(cp=True)
       
        # Get constraint settings from UI
       
        aimValue1 = cmds.floatFieldGrp ("MPCCarUI|MPCCar_mainColumnLayout|MPCCar_mainTabLayout|Step_2|orientAimAttrs", q=True, value1=True)
        aimValue2 = cmds.floatFieldGrp ("MPCCarUI|MPCCar_mainColumnLayout|MPCCar_mainTabLayout|Step_2|orientAimAttrs", q=True, value2=True)
        aimValue3 = cmds.floatFieldGrp ("MPCCarUI|MPCCar_mainColumnLayout|MPCCar_mainTabLayout|Step_2|orientAimAttrs", q=True, value3=True)
        upValue1 = cmds.floatFieldGrp ("MPCCarUI|MPCCar_mainColumnLayout|MPCCar_mainTabLayout|Step_2|orientUpAttrs", q=True, value1=True)
        upValue2 = cmds.floatFieldGrp ("MPCCarUI|MPCCar_mainColumnLayout|MPCCar_mainTabLayout|Step_2|orientUpAttrs", q=True, value1=True)
        upValue3 = cmds.floatFieldGrp ("MPCCarUI|MPCCar_mainColumnLayout|MPCCar_mainTabLayout|Step_2|orientUpAttrs", q=True, value1=True)
       
        # Normal constraint the TEMP loc
        cmds.normalConstraint (thingB, tempLoc[0], w=1, aimVector = (aimValue1, aimValue2, aimValue3), upVector = (upValue1, upValue2, upValue3), worldUpType="vector", worldUpVector = (0, 1, 0))
       
        # Move thingA with parent constraint with maintain offset turned off
        tempParentConstraint = cmds.parentConstraint ( (tempLoc[0]), (thingA), mo=False )
        
        # Delete things
        cmds.delete (tempParentConstraint,  tempLoc[0] )
Exemplo n.º 15
0
def locMeClosestUVOnSurface(obj, surface, pivotOnSurfaceOnly=False):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's of a surface

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    locBuffer = locMeObject(obj)
    pivotLoc = locMeObject(obj)

    controlSurface = mc.listRelatives(surface, shapes=True)
    """ make the closest point node """
    closestPointNode = mc.createNode('closestPointOnSurface')
    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((locBuffer + '.translate'),
                             (closestPointNode + '.inPosition'))
    attributes.doConnectAttr((controlSurface[0] + '.worldSpace'),
                             (closestPointNode + '.inputSurface'))
    """ make the pointOnSurfaceNode """
    pointOnSurfaceNode = mc.createNode('pointOnSurfaceInfo')
    """ Connect the info node to the surface """
    attributes.doConnectAttr((controlSurface[0] + '.worldSpace'),
                             (pointOnSurfaceNode + '.inputSurface'))
    """ Contect the pos group to the info node"""
    attributes.doConnectAttr((pointOnSurfaceNode + '.position'),
                             (pivotLoc + '.translate'))
    attributes.doConnectAttr((closestPointNode + '.parameterU'),
                             (pointOnSurfaceNode + '.parameterU'))
    attributes.doConnectAttr((closestPointNode + '.parameterV'),
                             (pointOnSurfaceNode + '.parameterV'))

    if pivotOnSurfaceOnly != True:
        position.movePointSnap(locBuffer, pivotLoc)
    else:
        rigging.copyPivot(locBuffer, pivotLoc)

    mc.delete(closestPointNode)
    mc.delete(pointOnSurfaceNode)
    mc.delete(pivotLoc)

    #Rotate
    constBuffer = mc.normalConstraint(surface, locBuffer)
    mc.delete(constBuffer[0])

    return locBuffer
Exemplo n.º 16
0
    def scatter_by_faces(self):

        """
        Method to scatter node by target surface faces
        """

        face_count = cmds.polyEvaluate(self.surface, f=True )

        if face_count >= self.copies:

            face_num_list = range(1, face_count + 1)
            random.shuffle(face_num_list)

            for face_num in face_num_list[0:self.copies]:
                
                current_face = "%s.f[%s]" % (self.surface, face_num)
                
                face_wsp = cmds.xform(current_face, query=True, worldSpace=True, boundingBox=True)
                xmin, ymin, zmin, xmax, ymax, zmax = face_wsp
                
                pos_x = xmin + ((xmax - xmin) / 2)
                pos_y = ymin + ((ymax - ymin) / 2)
                pos_z = zmin + ((zmax - zmin) / 2)
                
                new_obj = self.copy_obj()

                cmds.setAttr("%s.tx" % new_obj, float(pos_x))
                cmds.setAttr("%s.ty" % new_obj, float(pos_y))
                cmds.setAttr("%s.tz" % new_obj, float(pos_z))
                
                random_scale = random.uniform(self.scale_min, self.scale_max)
                cmds.setAttr("%s.scaleX" % new_obj, random_scale)
                cmds.setAttr("%s.scaleY" % new_obj, random_scale)
                cmds.setAttr("%s.scaleZ" % new_obj, random_scale)
                
                constraint = cmds.normalConstraint(current_face,
                                                   new_obj,
                                                   aimVector=[0, 1, 0],
                                                   upVector=[0,1,0],
                                                   worldUpType="scene")
                cmds.delete(constraint)

                self.randomize_wire_color(new_obj)

                self.copied_nodes.append(new_obj)
        else:
            message = "With Faces method You need to specify a number of copies"
            message += "\nsmaller or equal the faces on the surface node!\n"
            message += "Currently the surface has %s faces" % face_count
            response = QtGui.QMessageBox.question(self, "Face count - Copies", message)
Exemplo n.º 17
0
    def creating_instances(self):

        self.scattered_group = []
        self.scatter_randomizer()

        for vertex in self.percentage_selection:
            new_geo = cmds.instance(self.to_transfer_sel)
            vtx_pos = cmds.xform([vertex], query=True, translation=True)
            cmds.xform(new_geo,
                       translation=vtx_pos,
                       scale=self.randomize_scale(),
                       rotation=self.randomize_rotation(),
                       worldSpace=True)
            self.scattered_group.extend(new_geo)

            if self.collect_normals:
                cmds.normalConstraint(vertex, new_geo)

        self.scatter_materials()

        instance_group = cmds.group(self.scattered_group, name='scatter_group')

        return instance_group
Exemplo n.º 18
0
 def onionSkin(self):
     selObj=cmds.ls(sl=1, fl=1)       
     if len(selObj)==1:
         pass
     else:
         print "Select 1 object" 
     getRange=cmds.playbackOptions(q=1, max=1)#get framerange of scene to set keys in iteration 
     getRange=int(getRange)#change framerange to an integer. May have to change this to a float iterator on a half key blur(butterfly wings)
     for each in range(getRange):
         for item in selObj:
             getloc=cmds.spaceLocator(n=item+"cnstr_lctr")
             cmds.normalConstraint(item, getloc[0])
             getNum="%04d" % (each,)
             placeloc=cmds.spaceLocator(n=item+'FR'+str(getNum)+"_lctr")
             transform=cmds.xform(item, q=True, ws=1, t=True)
             cmds.xform(getloc[0], ws=1, t=transform)  
             cmds.SetKeyTranslate(getloc[0])
             cmds.xform(placeloc[0], ws=1, t=transform)
             cmds.SetKeyTranslate(placeloc[0])               
             rotate=cmds.xform(getloc[0], q=True, ws=1, ro=True)
             cmds.xform(placeloc[0], ws=1, ro=rotate)  
             cmds.SetKeyRotate(placeloc[0])
             maya.mel.eval( "playButtonStepForward;" )
             cmds.delete(getloc[0])
Exemplo n.º 19
0
def locMeClosestUVOnSurface(obj, surface, pivotOnSurfaceOnly = False):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's of a surface

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	locBuffer = locMeObject(obj)
	pivotLoc = locMeObject(obj)

	controlSurface = mc.listRelatives(surface,shapes=True)

	""" make the closest point node """
	closestPointNode = mc.createNode ('closestPointOnSurface')
	""" to account for target objects in heirarchies """
	attributes.doConnectAttr((locBuffer+'.translate'),(closestPointNode+'.inPosition'))
	attributes.doConnectAttr((controlSurface[0]+'.worldSpace'),(closestPointNode+'.inputSurface'))

	""" make the pointOnSurfaceNode """
	pointOnSurfaceNode = mc.createNode ('pointOnSurfaceInfo')
	""" Connect the info node to the surface """
	attributes.doConnectAttr  ((controlSurface[0]+'.worldSpace'),(pointOnSurfaceNode+'.inputSurface'))
	""" Contect the pos group to the info node"""
	attributes.doConnectAttr ((pointOnSurfaceNode+'.position'),(pivotLoc+'.translate'))
	attributes.doConnectAttr ((closestPointNode+'.parameterU'),(pointOnSurfaceNode+'.parameterU'))
	attributes.doConnectAttr  ((closestPointNode+'.parameterV'),(pointOnSurfaceNode+'.parameterV'))

	if pivotOnSurfaceOnly != True:
		position.movePointSnap(locBuffer,pivotLoc)
	else:
		rigging.copyPivot(locBuffer,pivotLoc)


	mc.delete(closestPointNode)
	mc.delete(pointOnSurfaceNode)
	mc.delete(pivotLoc)

	#Rotate
	constBuffer = mc.normalConstraint(surface,locBuffer)
	mc.delete(constBuffer[0])

	return locBuffer
Exemplo n.º 20
0
def locMeEdgeLoop(polyEdge):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Creates a locator from an edgeloop

	ARGUMENTS:
	polyEdge(string)

	RETURNS:
	locatorName(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	# Get the loop
	if ':' in polyEdge:
		edges = mc.ls(polyEdge,flatten=True)
	elif ',' in polyEdge:
		edges = polyEdge
	else:
		edges = search.returnEdgeLoopFromEdge(polyEdge)

	mc.select(cl=True)
	mc.select(edges)

	mel.eval("PolySelectConvert 3")
	edgeVerts = mc.ls(sl=True,fl=True)
	postList = []
	for vert in edgeVerts:
		posList.append(mc.pointPosition(vert,w=True))
	objTrans = distance.returnAveragePointPosition(posList)
	mc.select(cl=True)

	# Make the loc
	locatorName = createLocFromObject(polyEdge)
	mc.move (objTrans[0],objTrans[1],objTrans[2], locatorName)

	# aim it
	posList = []
	for vtx in edgeVerts:
		posList.append( mc.pointPosition(vtx,w=True) )

	polyBuffer = geo.createPolyFromPosList(posList)

	constBuffer = mc.normalConstraint(polyBuffer,locatorName)
	mc.delete(constBuffer[0])
	mc.delete(polyBuffer)

	return locatorName
Exemplo n.º 21
0
    def perform_scatter(self):
        self.count = self.count +1
        instances = []
        pos_list = []
        percentage_destination = []
        for idx in range(0, len(self.destination_verts)):
            rand.seed(idx)
            rand_value = rand.random()
            if rand_value <= self.percentage:
                percentage_destination.append(self.destination_verts[idx])

        for vert in percentage_destination:
            self.randomize()
            new_instance = cmds.instance(self.source_object,
                                         name=(str(self.source_object[0]) +
                                               "_instance" +
                                               str(self.count) + "_"))
            position = cmds.pointPosition(vert, world=True)
            cmds.xform(new_instance, translation=position)

            if self.align_to_normal:
                constraint = cmds.normalConstraint(vert, new_instance,
                                                   aimVector=[0, 1, 0])
                cmds.delete(constraint)
            cmds.xform(new_instance, objectSpace=True, relative=True,
                       rotation=(self.rot_x, self.rot_y, self.rot_z),
                       scale=(self.scale_x, self.scale_y, self.scale_z))
            instances.append(new_instance)

        count = len(instances)
        sums = [0, 0, 0]
        for item in instances:
            pos = cmds.xform(item, q=True, t=True)
            pos_list.append(pos)
            sums[0] += pos[0]
            sums[1] += pos[1]
            sums[2] += pos[2]
        center = [sums[0] / count, sums[1] / count, sums[2] / count]

        idx = 0
        for pos in pos_list:
            print(pos[0])
            dist_x = (center[0] - pos[0]) * self.clump_amount
            dist_y = (center[1] - pos[1]) * self.clump_amount
            dist_z = (center[2] - pos[2]) * self.clump_amount
            cmds.xform(instances[idx], objectSpace=True, relative=True,
                       translation=(dist_x, dist_y, dist_z))
            idx = idx + 1
Exemplo n.º 22
0
def locMeEdgeLoop(polyEdge):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Creates a locator from an edgeloop

	ARGUMENTS:
	polyEdge(string)

	RETURNS:
	locatorName(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    # Get the loop
    if ':' in polyEdge:
        edges = mc.ls(polyEdge, flatten=True)
    elif ',' in polyEdge:
        edges = polyEdge
    else:
        edges = search.returnEdgeLoopFromEdge(polyEdge)

    mc.select(cl=True)
    mc.select(edges)

    mel.eval("PolySelectConvert 3")
    edgeVerts = mc.ls(sl=True, fl=True)
    postList = []
    for vert in edgeVerts:
        posList.append(mc.pointPosition(vert, w=True))
    objTrans = distance.returnAveragePointPosition(posList)
    mc.select(cl=True)

    # Make the loc
    locatorName = createLocFromObject(polyEdge)
    mc.move(objTrans[0], objTrans[1], objTrans[2], locatorName)

    # aim it
    posList = []
    for vtx in edgeVerts:
        posList.append(mc.pointPosition(vtx, w=True))

    polyBuffer = geo.createPolyFromPosList(posList)

    constBuffer = mc.normalConstraint(polyBuffer, locatorName)
    mc.delete(constBuffer[0])
    mc.delete(polyBuffer)

    return locatorName
Exemplo n.º 23
0
def interactive_plane( aJnt ):
	
	try:
		bJnt = cmds.listRelatives( aJnt, children = True, type = 'joint' )[0]
	except TypeError:
		raise RuntimeError( 'You must pass a joint as the parent, %s doesn\'t seem to be a joint.' % hierarchy_parent )
		
	cJnt = cmds.listRelatives( bJnt, children = True, type = 'joint' )[0]
	
	aPos, bPos, cPos = cmds.xform( aJnt, ws = True, q = True, t = True), cmds.xform( bJnt, ws=True, q=True, t=True ), cmds.xform( cJnt, ws=True, q=True, t=True )
	aVec, bVec, cVec = om.MVector( aPos ), om.MVector( bPos ), om.MVector( cPos )
	
	polyFacet = cmds.polyCreateFacet( ch=True, tx=True, p=[aVec, bVec, cVec] )[0]
	plane = cmds.plane( s=10, p=[(aVec.x + bVec.x + cVec.x)/3, (aVec.y+bVec.y+cVec.y)/3, (aVec.z+bVec.z+cVec.z)/3] )
	cmds.delete( cmds.normalConstraint( polyFacet, plane, aimVector=[0,0,1], upVector=[0,1,0] ) )
	
	return polyFacet
Exemplo n.º 24
0
    def orient_to_normals(self):

        self.selection = cmds.ls(os=True, fl=True)
        self.vert_list = cmds.ls(selection=True, fl=True)
        cmds.filterExpand(self.vert_list, selectionMask=31, expand=True) or []
        self.obj_vert_list = cmds.ls(self.vert_list[1] + ".vtx[*]",
                                     flatten=True)

        if self.is_whole_object:
            self.den_list = random.sample(
                self.obj_vert_list,
                int(float(len(self.obj_vert_list) * self.def_density)))
        else:
            self.den_list = random.sample(
                self.vert_list,
                int(float(len(self.vert_list)) * self.def_density))

        self.object_to_instance = self.selection[0]
        self.main_object = self.selection[1]

        # print(vertex_name)

        if cmds.objectType(self.object_to_instance, isType="transform"):

            for self.vertex in self.den_list:
                self.new_instance = cmds.instance(self.object_to_instance)

                self.position = cmds.pointPosition(self.vertex, w=True)

                cmds.move(self.position[0],
                          self.position[1],
                          self.position[2],
                          self.new_instance,
                          a=True,
                          ws=True)

                self.nconst = cmds.normalConstraint(self.main_object,
                                                    self.new_instance,
                                                    aim=(0.0, 1.0, 0.0))
                cmds.rename(self.new_instance, "instance")

                cmds.delete(self.nconst)

        else:
            print("Please ensure the first object you select is a transform.")
Exemplo n.º 25
0
    def doOrientObjToSurface(self,l_targets,obj,deleteConstraint = True):
	"""
	constraint
	"""
	if type(l_targets) is not list:l_targets = [l_targets]
	try:
	    constBuffer = mc.normalConstraint(l_targets,obj,
                                              aimVector=self._aimVector,
                                              upVector=self._upVector,
                                              worldUpType = self._worldUpType)
	    if deleteConstraint:
		mc.delete(constBuffer)
		return True
	    return constBuffer
	    
	except StandardError,error:
	    log.error(error)	
	    return False
Exemplo n.º 26
0
 def create(self, scatter_location):
     instance_object = cmds.instance(self.selected_object,
                                     name=self.selected_object)
     self.get_xyz_location(scatter_location)
     cmds.move(self.x_location, self.y_location, self.z_location,
               instance_object)
     if self.normal_aligned:
         constraint = cmds.normalConstraint(scatter_location,
                                            instance_object,
                                            aimVector=[0.0, 1.0, 0.0])
         #cmds.delete(constraint)
     self.randomize()
     cmds.scale(self.scale_x, self.scale_y, self.scale_z, instance_object)
     cmds.rotate(self.rotation_x, self.rotation_y, self.rotation_z,
                 instance_object)
     cmds.move(self.x_location + self.x_location_offset,
               self.y_location + self.y_location_offset,
               self.z_location + self.z_location_offset, instance_object)
Exemplo n.º 27
0
def alignToUV(targetObj="none",
              sourceObj="none",
              sourceU=0.0,
              sourceV=0.0,
              mainAxis="+z",
              secAxis="+x",
              UorV="v"):
    """
	inputs should be 1. targetObj 2. sourceObj 3. sourceU 4. sourceV 5. mainAxis(lowerCase, + or -, i.e."-x" 8. secAxis (lowcase, + or -) 7, UorV ("u" or "v" for the direction along surface for the sec axis)
"""

    axisDict = {
        "+x": (1, 0, 0),
        "+y": (0, 1, 0),
        "+z": (0, 0, 1),
        "-x": (-1, 0, 0),
        "-y": (0, -1, 0),
        "-z": (0, 0, -1)
    }

    #Does this create a new node? no To create a node, use the flag "ch=True". That creates a pointOnSurface node
    pos = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, position=True)
    posVec = om.MVector(pos[0], pos[1], pos[2])
    cmds.xform(targetObj, ws=True, t=pos)

    #get normal, tanU and tanV at selected UV position on source surface
    tanV = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tv=True)
    tanU = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tu=True)
    norm = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, nn=True)

    #decide where up axis is on normal constraint, u or v tangent
    if UorV == "v":
        wup = tanV
    elif UorV == "u":
        wup = tanU

    #create normal constraint
    nc = cmds.normalConstraint(sourceObj,
                               targetObj,
                               aimVector=axisDict[mainAxis],
                               upVector=axisDict[secAxis],
                               worldUpVector=(wup))
    cmds.delete(nc)  #delete constraint
Exemplo n.º 28
0
    def doOrientObjToSurface(self, l_targets, obj, deleteConstraint=True):
        """
	constraint
	"""
        if type(l_targets) is not list: l_targets = [l_targets]
        try:
            constBuffer = mc.normalConstraint(l_targets,
                                              obj,
                                              aimVector=self._aimVector,
                                              upVector=self._upVector,
                                              worldUpType=self._worldUpType)
            if deleteConstraint:
                mc.delete(constBuffer)
                return True
            return constBuffer

        except StandardError, error:
            log.error(error)
            return False
Exemplo n.º 29
0
def positionPoleVectorControl(startJoint, endJoint, poleVectorNode, distance):
	"""NOTE: If each joint in your chain has more than 1 joint, make sure the joint that will be part of the IK chain, 
	are the first children, otherwise you will get bad results."""
	#figure out all the joints between startJoint and endJoint
	
	jointChainList = []
	jointChainList.append(startJoint)
	j = 0
	currentJoint = startJoint
	while j==0:
		currentJointChildren = cmds.listRelatives(currentJoint, c=1, type="joint")
		if len(currentJointChildren) > 1:
			cmds.warning("whoo, the specified start joint has more than 1 children, please choose another start joint")
		
			
		nextJoint = currentJointChildren[0]
		if nextJoint == endJoint:
			j=1
		else:
			jointChainList.append(nextJoint)
		currentJoint = nextJoint
	
	jointChainList.append(endJoint)
	
	#get position in space of each joint so we can create the polygon
	coordinatesList = []
	for j in jointChainList:
		jCoord = cmds.xform(j, q=1, ws=1, rp=1)
		coord = tuple(jCoord)
		coordinatesList.append(coord)
	
	polyPlane = cmds.polyCreateFacet( p=coordinatesList )[0]
	alignNodes(poleVectorNode, jointChainList[1])
	
	cmds.delete(cmds.geometryConstraint(polyPlane, poleVectorNode))
	cmds.delete(cmds.normalConstraint(polyPlane, poleVectorNode, upVector=[1, 0, 0], aimVector=[0, 0, 1]))
	
	cmds.xform(poleVectorNode, objectSpace=1, relative=1, t=[distance, distance, 0])
	
	cmds.delete(polyPlane)
Exemplo n.º 30
0
    def scatter_by_volume(self):

        """
        Method to scatter node by target surface volume/area
        """

        surface_wsp = cmds.xform(self.surface, query=True, worldSpace=True, boundingBox=True)
        xmin, ymin, zmin, xmax, ymax, zmax = surface_wsp

        for copy_num in range(1, self.copies + 1):

            pos_x = random.uniform(xmin, xmax)
            pos_y = random.uniform(ymin, ymax)
            pos_z = random.uniform(zmin, zmax)

            new_obj = self.copy_obj()

            cmds.setAttr("%s.tx" % new_obj, float(pos_x))
            cmds.setAttr("%s.ty" % new_obj, float(pos_y))
            cmds.setAttr("%s.tz" % new_obj, float(pos_z))

            random_scale = random.uniform(self.scale_min, self.scale_max)
            cmds.setAttr("%s.scaleX" % new_obj, random_scale)
            cmds.setAttr("%s.scaleY" % new_obj, random_scale)
            cmds.setAttr("%s.scaleZ" % new_obj, random_scale)

            g_constrain = cmds.geometryConstraint(self.surface, new_obj, weight=10)

            n_constraint = cmds.normalConstraint(self.surface,
                                               new_obj,
                                               aimVector=[0, 1, 0],
                                               upVector=[0,1,0],
                                               worldUpType="scene")
            cmds.delete(n_constraint)
            cmds.delete(g_constrain)

            self.randomize_wire_color(new_obj)

            self.copied_nodes.append(new_obj)
Exemplo n.º 31
0
def doPositionLocator(locatorName, locInfo):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Position a locator with locator info generated from returnInfoForLoc

	ARGUMENTS:
	locatorName(string)
	locInfo(dict)

	RETURNS:
	success(bool)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    if search.returnObjectType(locatorName) == 'locator':
        objTrans = locInfo['position']
        objRot = locInfo['rotation']
        correctRo = locInfo['rotationOrder']
        rotateAxis = locInfo['rotateAxis']

        mc.move(objTrans[0], objTrans[1], objTrans[2], locatorName)
        mc.setAttr((locatorName + '.rotateOrder'), correctRo)

        #Rotate
        if locInfo['objectType'] == 'polyFace':
            constBuffer = mc.normalConstraint((locInfo['createdFrom']),
                                              locatorName)
            mc.delete(constBuffer[0])
        else:
            attributes.doSetAttr(locatorName, 'rotateOrder', correctRo)
            mc.rotate(objRot[0], objRot[1], objRot[2], locatorName, ws=True)
            for i, a in enumerate(['X', 'Y', 'Z']):
                attributes.doSetAttr(locatorName, 'rotateAxis{0}'.format(a),
                                     rotateAxis[i])
        return True
    else:
        guiFactory.warning('Not a locator.')
        return False
Exemplo n.º 32
0
def locMeClosestPointOnMesh(obj, mesh):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the closest point of a mesh to a target object

	ARGUMENTS:
	obj(string)
	mesh(string)

	RETURNS:
	locatorName(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    locatorName = locMeObject(obj)
    """ make the closest point node """
    closestPointNode = mc.createNode('closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh, shapes=True)
    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((obj + '.translate'),
                             (closestPointNode + '.inPosition'))
    attributes.doConnectAttr((controlSurface[0] + '.worldMesh'),
                             (closestPointNode + '.inMesh'))
    attributes.doConnectAttr((controlSurface[0] + '.worldMatrix'),
                             (closestPointNode + '.inputMatrix'))
    """ Contect the locator to the info node"""
    attributes.doConnectAttr((closestPointNode + '.position'),
                             (locatorName + '.translate'))

    faceIndex = mc.getAttr(closestPointNode + '.closestFaceIndex')
    face = ('%s%s%i%s' % (mesh, '.f[', faceIndex, ']'))

    mc.delete(closestPointNode)
    #Rotate
    constBuffer = mc.normalConstraint(face, locatorName)
    mc.delete(constBuffer[0])

    return locatorName
Exemplo n.º 33
0
def locMeClosestPointOnMesh(obj, mesh):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the closest point of a mesh to a target object

	ARGUMENTS:
	obj(string)
	mesh(string)

	RETURNS:
	locatorName(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	locatorName = locMeObject(obj)

	""" make the closest point node """
	closestPointNode = mc.createNode ('closestPointOnMesh')
	controlSurface = mc.listRelatives(mesh,shapes=True)

	""" to account for target objects in heirarchies """
	attributes.doConnectAttr((obj+'.translate'),(closestPointNode+'.inPosition'))
	attributes.doConnectAttr((controlSurface[0]+'.worldMesh'),(closestPointNode+'.inMesh'))
	attributes.doConnectAttr((controlSurface[0]+'.worldMatrix'),(closestPointNode+'.inputMatrix'))

	""" Contect the locator to the info node"""
	attributes.doConnectAttr ((closestPointNode+'.position'),(locatorName+'.translate'))


	faceIndex = mc.getAttr(closestPointNode+'.closestFaceIndex')
	face = ('%s%s%i%s' %(mesh,'.f[',faceIndex,']'))

	mc.delete(closestPointNode)
	#Rotate
	constBuffer = mc.normalConstraint(face,locatorName)
	mc.delete(constBuffer[0])

	return locatorName
Exemplo n.º 34
0
 def __init__(self, root_obj_name, sel_name, run_option):
     # this function runs the script
     face_sel = cmds.ls(sl=True, fl=True)  # makes a selection from the UI
     Face_Center(
     )  # passes the selection into Face_Center class to find centers of faces in face_sel
     self.run_option = run_option
     self.sel_name = sel_name
     self.dupe_geo_list = []
     for dummy_item in face_sel:
         for key, val in FACE_CENTER_DICT.iteritems(
         ):  # loops through global dict to find relevant coordinates
             if self.run_option == 'Instance':
                 dummy_new_geo = cmds.instance(root_obj_name)
             elif self.run_option == 'Duplicate':
                 dummy_new_geo = cmds.duplicate(root_obj_name)
             cmds.setAttr(str(dummy_new_geo[0]) + '.translateX', val[0])
             cmds.setAttr(str(dummy_new_geo[0]) + '.translateY', val[1])
             cmds.setAttr(str(dummy_new_geo[0]) + '.translateZ', val[2])
             dummy_constr = cmds.normalConstraint(dummy_item,
                                                  str(dummy_new_geo[0]),
                                                  aimVector=(0, 1, 0),
                                                  u=(0, 1, 0),
                                                  worldUpType=0,
                                                  wu=(0, 1, 0))
             cmds.delete(dummy_constr)
             self.dupe_geo_list.append(dummy_new_geo)
         cmds.setAttr(str(root_obj_name) + '.translateX', 0)
         cmds.setAttr(str(root_obj_name) + '.translateY', 0)
         cmds.setAttr(str(root_obj_name) + '.translateZ', 0)
         cmds.setAttr(str(root_obj_name) + '.rotateX', 0)
         cmds.setAttr(str(root_obj_name) + '.rotateY', 0)
         cmds.setAttr(str(root_obj_name) + '.rotateZ', 0)
         FACE_CENTER_DICT.clear()  # memory management purposes
     self.sel_name_grp = cmds.group(
         em=True, name=self.sel_name
     )  # creates a group to house the duplicated geometries
     for dummy_geo in self.dupe_geo_list:
         cmds.parent(dummy_geo, str(self.sel_name_grp))
Exemplo n.º 35
0
def targetList(constraint):
    '''
	Return a list of targets (drivers) for the specified constraint node
	@param constraint: The constraint node whose targets will be returned
	@type constraint: str
	'''
    # Check Constraint
    if not isConstraint(constraint):
        raise Exception('Constraint "' + constraint + '" does not exist!!')

    # Get Target List
    targetList = []
    constraintType = mc.objectType(constraint)
    if constraintType == 'aimConstraint':
        targetList = mc.aimConstraint(constraint, q=True, tl=True)
    elif constraintType == 'geometryConstraint':
        targetList = mc.geometryConstraint(constraint, q=True, tl=True)
    elif constraintType == 'normalConstraint':
        targetList = mc.normalConstraint(constraint, q=True, tl=True)
    elif constraintType == 'orientConstraint':
        targetList = mc.orientConstraint(constraint, q=True, tl=True)
    elif constraintType == 'parentConstraint':
        targetList = mc.parentConstraint(constraint, q=True, tl=True)
    elif constraintType == 'pointConstraint':
        targetList = mc.pointConstraint(constraint, q=True, tl=True)
    elif constraintType == 'poleVectorConstraint':
        targetList = mc.poleVectorConstraint(constraint, q=True, tl=True)
    elif constraintType == 'scaleConstraint':
        targetList = mc.scaleConstraint(constraint, q=True, tl=True)
    elif constraintType == 'tangentConstraint':
        targetList = mc.tangentConstraint(constraint, q=True, tl=True)

    # Check Target List
    if not targetList: targetList = []

    # Return Result
    return targetList
    def alignKneeVectors(self, *args):

        sides = ["_L_", "_R_"]

        for i in sides:

            kneeCon = cmds.ls(self.prefix + i + "Knee_Con")

            cmds.parent(kneeCon, w=True)

            heelPos = cmds.xform(cmds.ls(self.prefix + i + "INV_Heel_Jnt",
                                         type='joint'),
                                 q=True,
                                 t=True,
                                 ws=True)
            hipPos = cmds.xform(cmds.ls(self.prefix + i + "Hip_Jnt",
                                        type='joint'),
                                q=True,
                                t=True,
                                ws=True)
            kneePos = cmds.xform(cmds.ls(self.prefix + i + "Knee_Jnt",
                                         type='joint'),
                                 q=True,
                                 t=True,
                                 ws=True)

            createPolyPoint = cmds.polyCreateFacet(p=[(hipPos), (kneePos),
                                                      (heelPos)],
                                                   ch=False)
            conPointConstraint = cmds.pointConstraint(
                cmds.ls(self.prefix + i + "Knee_Jnt", type='joint'), kneeCon)
            nConstraint = cmds.normalConstraint(createPolyPoint[0], kneeCon)
            cmds.delete(conPointConstraint)
            cmds.delete(nConstraint)
            cmds.delete(createPolyPoint)

            cmds.move(0, 0, 0.3 * self.conRadius, kneeCon, os=True, r=True)
Exemplo n.º 37
0
def jointPerVertex(ptList, orientSurface='', prefix='', suffix='jnt'):
    '''
	'''
    # Generate position list from input point
    posList = []
    for pt in ptList:
        posList.append(glTools.utils.base.getPosition(pt))

    # Create joints
    jntList = []
    for i in range(len(posList)):

        # Clear selection
        mc.select(cl=1)

        # Get string index
        strInd = glTools.utils.stringUtils.stringIndex(i + 1, 2)

        # Create joint
        jnt = mc.joint(n=prefix + '_' + strInd + '_' + suffix)
        # Position joint
        mc.move(posList[i][0],
                posList[i][1],
                posList[i][2],
                jnt,
                ws=True,
                a=True)

        # Orient joint
        if mc.objExists(orientSurface):
            mc.delete(mc.normalConstraint(orientSurface, jnt))

        # Append return list
        jntList.append(jnt)

    # Return Result
    return jntList
Exemplo n.º 38
0
def targetList(constraint):
    """
    Return a list of targets (drivers) for the specified constraint node
    @param constraint: The constraint node whose targets will be returned
    @type constraint: str
    """
    # Check Constraint
    if not isConstraint(constraint):
        raise Exception('Constraint "' + constraint + '" does not exist!!')

    # Get Target List
    targetList = []
    constraintType = cmds.objectType(constraint)
    if constraintType == 'aicmdsonstraint':
        targetList = cmds.aicmdsonstraint(constraint, q=True, tl=True)
    elif constraintType == 'geometryConstraint':
        targetList = cmds.geometryConstraint(constraint, q=True, tl=True)
    elif constraintType == 'normalConstraint':
        targetList = cmds.normalConstraint(constraint, q=True, tl=True)
    elif constraintType == 'orientConstraint':
        targetList = cmds.orientConstraint(constraint, q=True, tl=True)
    elif constraintType == 'parentConstraint':
        targetList = cmds.parentConstraint(constraint, q=True, tl=True)
    elif constraintType == 'pointConstraint':
        targetList = cmds.pointConstraint(constraint, q=True, tl=True)
    elif constraintType == 'poleVectorConstraint':
        targetList = cmds.poleVectorConstraint(constraint, q=True, tl=True)
    elif constraintType == 'scaleConstraint':
        targetList = cmds.scaleConstraint(constraint, q=True, tl=True)
    elif constraintType == 'tangentConstraint':
        targetList = cmds.tangentConstraint(constraint, q=True, tl=True)

    # Check Target List
    if not targetList: targetList = []

    # Return Result
    return targetList
Exemplo n.º 39
0
def targetList(constraint):
    ''' Return a list of targets (drivers) for the specified constraint node
    :param constraint str: The constraint node whose targets will be returned
    :return: List of target drivers for specified constraint
    :rtype: list
    '''
    # Check Constraint
    if not isConstraint(constraint):
        raise Exception('Constraint {0} does not exist!!'.format(constraint))

    # Get Target List
    targetList = []
    constraintType = cmds.objectType(constraint)
    if constraintType == 'aimConstraint':
        targetList = cmds.aimConstraint(constraint, q=True, tl=True)
    elif constraintType == 'geometryConstraint':
        targetList = cmds.geometryConstraint(constraint, q=True, tl=True)
    elif constraintType == 'normalConstraint':
        targetList = cmds.normalConstraint(constraint, q=True, tl=True)
    elif constraintType == 'orientConstraint':
        targetList = cmds.orientConstraint(constraint, q=True, tl=True)
    elif constraintType == 'parentConstraint':
        targetList = cmds.parentConstraint(constraint, q=True, tl=True)
    elif constraintType == 'pointConstraint':
        targetList = cmds.pointConstraint(constraint, q=True, tl=True)
    elif constraintType == 'poleVectorConstraint':
        targetList = cmds.poleVectorConstraint(constraint, q=True, tl=True)
    elif constraintType == 'scaleConstraint':
        targetList = cmds.scaleConstraint(constraint, q=True, tl=True)
    elif constraintType == 'tangentConstraint':
        targetList = cmds.tangentConstraint(constraint, q=True, tl=True)

    # Check Target List
    if not targetList: targetList = []

    # Return Result
    return targetList
Exemplo n.º 40
0
def lsOrientJointsToPlane(jntList, downVector=[1,0,0], normalVector=[0,0,1]):
    '''
    arguments:
    jntList - [startJnt, midJnt, endJnt]
    downVector (optional) - vector that points to the child joint, defaults to +X
    normalVector (optional) - vector for axis of rotation, defaults to +Z
    
    todo:
    1. options for orienting startJnt and endJnt when necessary
    2. use API for calculating vectors, instead of creating arbitrary polys and constraints... though this should work for now...
    ''' 
    
    # get joint positions
    startJntPos = mc.xform(jntList[0], q=1, ws=1, t=1)
    midJntPos = mc.xform(jntList[1], q=1, ws=1, t=1)
    endJntPos = mc.xform(jntList[2], q=1, ws=1, t=1)
    
    # create poly to act as rotate plane
    tempPoly = mc.polyCreateFacet(ch=0, p=[startJntPos, midJntPos, endJntPos], n="tempPoly_getNormal")
    
    # create locator to get normal vector 
    tempLoc = mc.spaceLocator(n="tempLoc_getNormal")[0]
    mc.xform(tempLoc, ws=1, t=midJntPos)
    normalCons = mc.normalConstraint(tempPoly, tempLoc) # default: X-axis aligns with normal vector
    mc.delete(normalCons)
    
    # orient midJnt (jntList[1])
    mc.move(1,0,0, tempLoc, os=1, r=1)
    mc.parent(jntList[2], w=1)
    aimCons = mc.aimConstraint(jntList[2], jntList[1], aim=downVector, u=normalVector, wuo=tempLoc, wut=2, wu=[1,0,0])
    mc.delete(aimCons)
    mc.makeIdentity(jntList[1], a=1, r=1)
    mc.parent(jntList[2],jntList[1])
        
    # cleanup
    mc.delete(tempPoly, tempLoc)
Exemplo n.º 41
0
def targetList(constraint):
	'''
	Return a list of targets (drivers) for the specified constraint node
	@param constraint: The constraint node whose targets will be returned
	@type constraint: str
	'''
	# Check constraint
	if not mc.objExists(constraint): raise UserInputError('Constraint '+constraint+' does not exist!!')
	constraintType = mc.objectType(constraint)
	# Get target list
	targetList = []
	if constraintType == 'aimConstraint': targetList = mc.aimConstraint(constraint,q=True,tl=True)
	elif constraintType == 'geometryConstraint': targetList = mc.geometryConstraint(constraint,q=True,tl=True)
	elif constraintType == 'normalConstraint': targetList = mc.normalConstraint(constraint,q=True,tl=True)
	elif constraintType == 'orientConstraint': targetList = mc.orientConstraint(constraint,q=True,tl=True)
	elif constraintType == 'parentConstraint': targetList = mc.parentConstraint(constraint,q=True,tl=True)
	elif constraintType == 'pointConstraint': targetList = mc.pointConstraint(constraint,q=True,tl=True)
	elif constraintType == 'poleVectorConstraint': targetList = mc.poleVectorConstraint(constraint,q=True,tl=True)
	elif constraintType == 'scaleConstraint': targetList = mc.scaleConstraint(constraint,q=True,tl=True)
	elif constraintType == 'tangentConstraint': targetList = mc.tangentConstraint(constraint,q=True,tl=True)
	# Check target list
	if not targetList: targetList = []
	# Return result
	return targetList
Exemplo n.º 42
0
def limbsSetUp(initialSelec):    
    #++ functions ++# 
    def makeIKRibbon(selectedName):

        
        rollNamingFirst = '_roll_1_skin_joint'
        rollNamingEnd = '_roll_end_joint'
        selecRollFirst = selectedName+rollNamingFirst
        selecRollEnd = selectedName+rollNamingEnd



        if cmds.objExists('spik_GRP') is False:
            spikGRP = cmds.group(empty=True, w=True, n='spik_GRP')
        else:
            spikGRP = cmds.ls('spik_GRP')[0]


        #!!!!!!!!!
        sideName = selectedName

        if selectedName.split('_')[0] == 'shoulder':
            sideName = sideName.replace('shoulder', 'arm')
        elif selectedName.split('_')[0] == 'elbow':
            sideName = sideName.replace('elbow', 'arm')

        elif selectedName.split('_')[0] == 'thigh':
            sideName = sideName.replace('thigh', 'leg')
        elif selectedName.split('_')[0] == 'knee':
            sideName = sideName.replace('knee', 'leg')

        sideName = sideName.replace('_joint', '')
        #!!!!!!!!!

        spikHandle = cmds.ikHandle(sj=selecRollFirst, ee=selecRollEnd, sol='ikSplineSolver', pcv=False, ns=4, n=selectedName + '_spik_handle')
        spikCRV = selectedName+'_spik_curve'
        cmds.rename('curve1', spikCRV)

        curvePoint = cmds.pointOnCurve(spikCRV, p=True)


        jointNum = 1
        spikJNTList = []
        for i in range(7):
            spikJntPos = cmds.pointPosition(spikCRV+'.cv['+str(i)+']')
            cmds.select(cl=True)
            if i != 1 and i != 5:
                spikJNT = cmds.joint(p=spikJntPos, n=selectedName+'_spik_'+str(jointNum)+'_joint', rad=2)
                cmds.hide(spikJNT)
                if i == 6:            
                    aligner(spikJNT, selecRollEnd, Const='orient')
                else:
                    aligner(spikJNT, selecRollFirst, Const='orient')
                cmds.makeIdentity(spikJNT, apply=True, t=0, r=1, s=0, n=1, pn=1)
                spikJNTList.append(spikJNT)
                jointNum += 1



        cmds.select(spikJNTList, r=True)
        cmds.select(spikCRV, add=True)
        cmds.skinCluster(tsb=True, dr=4.0)

        spikCtrlList = makeController(spikJNTList, parent=True, )



        crvInfoNode = cmds.createNode('curveInfo', n=spikCRV+'_crvINFO')
        cmds.connectAttr(spikCRV+'.worldSpace[0]', crvInfoNode+'.inputCurve')

        mdNode1 = cmds.createNode('multiplyDivide', n=spikCRV+'_MD1')
        cmds.setAttr(mdNode1+'.operation', 2)
        mdNode2 = cmds.createNode('multiplyDivide', n=spikCRV+'_MD2')
        cmds.setAttr(mdNode2+'.operation', 2)
        crvLength = cmds.getAttr(crvInfoNode+'.arcLength')
        cmds.setAttr(mdNode2+'.input2X', crvLength)
        cmds.connectAttr(crvInfoNode+'.arcLength', mdNode1+'.input1X')
        cmds.connectAttr(mdNode1+'.outputX', mdNode2+'.input1X')


        rollList = cmds.listRelatives(selecRollFirst, c=True, ad=True, type='joint')
        list.reverse(rollList)
        rollList.insert(0, selecRollFirst)
    

        for i in range(len(rollList)):
            cmds.connectAttr(mdNode2+'.outputX', rollList[i]+'.scaleX')

        val1 = 0.75
        val2 = 0.25

        for i in range(1,4):
            cmds.select(spikCtrlList[0], r=True)
            cmds.select(spikCtrlList[-1], add=True)
            
            ctrlConst = cmds.listRelatives(spikCtrlList[i], parent=True)[0]
            cmds.select(ctrlConst, add=True)
            
            cmds.pointConstraint(mo=False, weight=1)
            
            cmds.setAttr(ctrlConst+'_pointConstraint1.'+spikCtrlList[0]+'W0', val1)
            cmds.setAttr(ctrlConst+'_pointConstraint1.'+spikCtrlList[-1]+'W1', val2)

            val1 -= 0.25 
            val2 += 0.25 

        rotJNT1 = cmds.duplicate(rollList[0], po=True, n=selectedName+'_rot_1_ik_joint')
        rotJNT2 = cmds.duplicate(rollList[-1], po=True, n=selectedName+'_rot_2_ik_joint')

        cmds.parent(rotJNT1, w=True)
        cmds.parent(rotJNT2, rotJNT1)

        rotSCik = cmds.ikHandle(sj=rotJNT1[0], ee=rotJNT2[0], sol='ikSCsolver', n=selectedName + '_rot_SCik_handle')

        cmds.parent(selectedName + '_rot_SCik_handle', spikCtrlList[-1])

        rotGRP = cmds.group(empty=True, n=selectedName+'_rot_GRP', w=True)
        aligner(rotGRP, spikCtrlList[0], Const='parent')


        for i in range(1,4):
            spikCtrlPos = cmds.listRelatives(cmds.listRelatives(spikCtrlList[i], ap=True, p=True), p=True)
            cmds.parent(spikCtrlPos, rotGRP)

        cmds.select(rotJNT1, r=True)
        cmds.select(rotGRP, add=True)
        cmds.orientConstraint(mo=True)

        cmds.parent(rotJNT1, spikCtrlList[0])

        cmds.hide(rotJNT1)
        cmds.hide(rotSCik)
        cmds.hide(spikHandle[0])

        #!!!!!!!!!
        if cmds.objExists(sideName+'_spik_GRP') is False:
            sidespikGRP = cmds.group(empty=True, w=True, n=sideName+'_spik_GRP')
        else:
            sidespikGRP = cmds.ls(sideName+'_spik_GRP')[0]
        #!!!!!!!!!

        selectedspikGRP = cmds.group(empty=True, w=True, n=selectedName+'_spik_GRP')
        cmds.parent(spikHandle[0], spikCRV, selectedspikGRP)
        cmds.parent(selectedspikGRP, sidespikGRP)

        return spikCtrlList


    #++ MAIN ++#

    
    print(initialSelec)
    side = initialSelec.split('_')[1]
    selecFirst = initialSelec
    selecSecond = (cmds.listRelatives(selecFirst, c=True))[0]
    selecThird = (cmds.listRelatives(selecSecond, c=True))[0]

    #* make IK set
    dup = cmds.duplicate(initialSelec, renameChildren=True, n=initialSelec.replace('_joint', '_IK_joint'))
    cmds.rename(dup[1], dup[1].replace('_joint1', '_IK_joint'))
    cmds.rename(dup[2], dup[2].replace('_joint1', '_IK_joint'))

    #* make FK set
    dup = cmds.duplicate(initialSelec, renameChildren=True, n=initialSelec.replace('_joint', '_FK_joint'))
    cmds.rename(dup[1], dup[1].replace('_joint1', '_FK_joint'))
    cmds.rename(dup[2], dup[2].replace('_joint1', '_FK_joint'))


    selectedIKFirst = initialSelec.replace('_joint', '_IK_joint')
    selectedIKMiddle = (cmds.listRelatives(selectedIKFirst, c=True))[0]
    selectedIKLast = (cmds.listRelatives(selectedIKMiddle, c=True))[0]

    selectedFKFirst = initialSelec.replace('_joint', '_FK_joint')
    selectedFKMiddle = (cmds.listRelatives(selectedFKFirst, c=True))[0]
    selectedFKLast = (cmds.listRelatives(selectedFKMiddle, c=True))[0]



    selectedName1 = selecFirst.replace('_joint', '')
    ribbonCtrls1 = makeIKRibbon(selectedName1)

    selectedName2 = selecSecond.replace('_joint', '')
    ribbonCtrls2 = makeIKRibbon(selectedName2)

    selectedName3 = selecThird.replace('_joint', '')




    #++ get Side GRP name ++#

    sideGRPName = initialSelec

    if initialSelec.split('_')[0] == 'shoulder':
        sideGRPName = sideGRPName.replace('shoulder', 'arm')

    elif initialSelec.split('_')[0] == 'thigh':
        sideGRPName = sideGRPName.replace('thigh', 'leg')

    sideGRPName = sideGRPName.replace('_joint', '')




    #++ initial classify +##

    rollShoulderGRP = makeOwnGRP(selectedName1+'_roll_1_skin_joint', style='GRP')
    rollElbowGRP = makeOwnGRP(selectedName2+'_roll_1_skin_joint', style='GRP')


    skinJointGRP = cmds.group(empty=True, p='joint_GRP', n=sideGRPName+'_joint_GRP')
    # cmds.parent(rollShoulderGRP, rollElbowGRP, skinJointGRP)


    if cmds.objExists('global_GRP') is False:
        globalGRP = cmds.group(empty=True, w=True, n='global_GRP')
    else:
        globalGRP = cmds.ls('global_GRP')[0]

    if cmds.objExists('Extras') is False:
        extras = cmds.group(empty=True, w=True, n='Extras')
    else:
        extras = cmds.ls('Extras')[0]
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    cmds.select(cl=True)
    cmds.select(globalGRP, hi=True)
    check = cmds.ls(sl=True)

    if ('joint_GRP' in check) is False:
        cmds.parent('joint_GRP', globalGRP)
        cmds.parent('spik_GRP', extras)
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



    #++ func ELbow Lock ++#

    upCtrlPosLast = selecFirst.replace('_joint', '_spik_5_Pos')
    lowCtrlPosFirst = selecSecond.replace('_joint', '_spik_1_Pos')

    lockGRP = cmds.group(empty=True, n=selectedName2+'_lock_ctrl_GRP')
    aligner(lockGRP, lowCtrlPosFirst, Const='parent')

    lockCtrl = makeController(lockGRP, shape='star')

    cmds.parent(upCtrlPosLast, lowCtrlPosFirst, lockGRP)
    # cmds.delete(lockGRP)

    addCustomAttribute(lockCtrl)

    cmds.addAttr(lockCtrl, ln='Sub_Controller_Visibility', nn="Sub Controller Visibility", at="enum", en="Off:On")
    cmds.setAttr(lockCtrl[0]+'.Sub_Controller_Visibility', e=1, keyable=1)

    cmds.connectAttr(lockCtrl[0]+'.Sub_Controller_Visibility', ribbonCtrls1[-1]+'.visibility')
    cmds.connectAttr(lockCtrl[0]+'.Sub_Controller_Visibility', ribbonCtrls2[0]+'.visibility')

    # cmds.parentConstraint(lockCtrl[0], lockGRP, mo=True)




    #++ Follow Codes Belongs Main ++#

    lockCtrlPos = getRoot(nodType='transform', sel=lockCtrl)
    cmds.parentConstraint(selectedIKMiddle, lockCtrlPos, mo=True)

    cmds.parentConstraint(selectedIKFirst, getRoot(nodType='transform', sel=ribbonCtrls1[0]))
    cmds.parentConstraint(selectedIKLast, getRoot(nodType='transform', sel=ribbonCtrls2[-1]))





    #:: Main classify ::#

    sideIKGRP = cmds.group(empty=True, w=True, n=sideGRPName+'_IK_GRP')
    ribbonCtrlPos1 = getRoot(nodType='transform', sel=ribbonCtrls1[0])
    ribbonCtrlPos2 = getRoot(nodType='transform', sel=ribbonCtrls1[1])
    ribbonCtrlPos4 = getRoot(nodType='transform', sel=ribbonCtrls2[-2])
    ribbonCtrlPos5 = getRoot(nodType='transform', sel=ribbonCtrls2[-1])


    sideBendctrlGRP = cmds.group(empty=True, w=True, n=sideGRPName+'_bend_ctrl_GRP')
    cmds.parent(ribbonCtrlPos2, ribbonCtrlPos4, sideBendctrlGRP)




    #++ Make IK controller ++# 

    wristIKsubCtrl = makeController(selectedIKLast, shape='star', addName='_sub', scale=0.8)
    wristIKmainCtrl = makeController(selectedIKLast, shape='star', addName='_main', scale=1.1)
    cmds.parent(getRoot(sel=wristIKsubCtrl, nodType='transform'), wristIKmainCtrl)

    shoulderIKCtrl = makeController(selectedIKFirst, shape='star')

    rpIKHandle = cmds.ikHandle(sj=selectedIKFirst, ee=selectedIKLast, sol='ikRPsolver', n=selectedName1+'_IK_handle')
    cmds.parent(rpIKHandle[0], wristIKsubCtrl)
    cmds.hide(rpIKHandle)

    controllerColor(shoulderIKCtrl, 'red')
    controllerColor(wristIKmainCtrl, 'red')
    controllerColor(wristIKsubCtrl, 'red')

    cmds.parent(getRoot(sel=wristIKmainCtrl, nodType='transform'), sideIKGRP)
    cmds.parent(getRoot(sel=shoulderIKCtrl, nodType='transform'), sideIKGRP)


    #++ make FK Controllers ++#

    shoulderFKctrl = makeController(selectedFKFirst, scale=1.2)
    controllerColor(shoulderFKctrl, 'yellow')
    shoulderFKctrlPos = getRoot(sel=shoulderFKctrl, nodType='transform')
    addCustomAttribute(shoulderFKctrl)
    cmds.addAttr(shoulderFKctrl, ln='stretch', nn='stretch', at='float', minValue=0, defaultValue=1)
    cmds.setAttr(shoulderFKctrl[0]+'.stretch', e=1, keyable=1)

    elbowFKctrl = makeController(selectedFKMiddle, scale=1.2)
    controllerColor(elbowFKctrl, 'yellow')
    elbowFKctrlPos = getRoot(sel=elbowFKctrl, nodType='transform')
    addCustomAttribute(elbowFKctrl)
    cmds.addAttr(elbowFKctrl, ln='stretch', nn='stretch', at='float', minValue=0, defaultValue=1)
    cmds.setAttr(elbowFKctrl[0]+'.stretch', e=1, keyable=1)

    wristFKctrl = makeController(selectedFKLast, scale=1.2)
    controllerColor(wristFKctrl, 'yellow')
    wristFKctrlPos = getRoot(sel=wristFKctrl, nodType='transform')

    sideFKGRP = cmds.group(empty=True, w=True, n=sideGRPName+'_FK_GRP')
    cmds.parent(shoulderFKctrlPos, elbowFKctrlPos, wristFKctrlPos, sideFKGRP)


    #++ make fk connections ++#

    cmds.parentConstraint(selectedFKMiddle, lockCtrlPos, mo=True) 
    cmds.parentConstraint(selectedFKLast, ribbonCtrlPos5, mo=True)
    cmds.parentConstraint(selectedFKFirst, ribbonCtrlPos1, mo=True)

    cmds.parentConstraint(selectedIKMiddle, rollElbowGRP, mo=True)
    cmds.parentConstraint(selectedFKMiddle, rollElbowGRP, mo=True)

    cmds.parentConstraint(shoulderFKctrl, selectedFKFirst, mo=True)
    cmds.orientConstraint(elbowFKctrl, selectedFKMiddle)

    cmds.pointConstraint(selectedFKLast, cmds.listRelatives(wristFKctrl, p=True)[0], mo=True)
    cmds.pointConstraint(selectedFKMiddle, cmds.listRelatives(elbowFKctrl, p=True)[0])

    #* fk shoulder controller drives elbow controller GRP by orient Constraining
    cmds.orientConstraint(shoulderFKctrl, cmds.listRelatives(elbowFKctrl, p=True)[0], mo=True)
    cmds.orientConstraint(elbowFKctrl, cmds.listRelatives(wristFKctrl, p=True)[0], mo=True)

    #* fk shoulder and elbow stretch connections
    cmds.connectAttr(shoulderFKctrl[0]+'.stretch', selectedFKFirst+'.scaleX')
    cmds.connectAttr(elbowFKctrl[0]+'.stretch', selectedFKMiddle+'.scaleX')


    #++ hands and finger setUp ++#
    wristRootJNT = selectedName3+'_root_joint'
    wristRootGRP = makeOwnGRP(wristRootJNT, style='GRP')
    cmds.parent(wristRootGRP, 'joint_GRP')
    cmds.pointConstraint(selectedIKLast, wristRootGRP, mo=True)
    cmds.pointConstraint(selectedFKLast, wristRootGRP, mo=True)


    #++ Set Orientation Buffer Locators ++#
    ikWristLoc = cmds.spaceLocator(n=selectedName3+'_ik_loc')
    aligner(ikWristLoc, wristIKsubCtrl, Const='parent')
    cmds.parent(ikWristLoc, wristIKsubCtrl)

    fkWristLoc = cmds.spaceLocator(n=selectedName3+'_fk_loc')
    aligner(fkWristLoc, wristFKctrl, Const='parent')
    cmds.parent(fkWristLoc, wristFKctrl)

    cmds.orientConstraint(ikWristLoc, fkWristLoc, wristRootGRP, mo=True)




    #++ pole Vector Controller ++#

    polVecCtrl = makeController(selectedIKMiddle, addName='_poleVector', shape='cube', scale=1.1)
    controllerColor(polVecCtrl, 'pink')
    poleVecPoly = cmds.polyCreateFacet(p=[cmds.xform(selectedIKFirst, q=True, t=True, ws=True), cmds.xform(selectedIKMiddle, q=True, t=True, ws=True), 
                            cmds.xform(selectedIKLast, q=True, t=True, ws=True)], ch=True, tx=1, n='poleVecPoly')

    cmds.select(cl=True)
    poleVtx = '{0}.vtx[1]'.format(poleVecPoly[0])
    poleVecPos = getRoot(sel=polVecCtrl, nodType='transform')
    cmds.normalConstraint(poleVtx, poleVecPos)

    cmds.delete(poleVecPoly)
    cmds.poleVectorConstraint(polVecCtrl, rpIKHandle[0])

    cmds.parent(poleVecPos, sideIKGRP)




    def fingerSetUp(side, sidectrlGRP):        

        #++ make FK finger Controllers ++#
        fingerFKJNTLists = cmds.ls('finger_*'+side+'*_FK_joint', type='joint')
        fingerFKJNTLists = list(filter(lambda x: 'end' not in x, fingerFKJNTLists)) #* or -> [f for f in fingerFKJNTLists if '_end_' not in f]

        fingerAllCtrlLists = makeController(selec=fingerFKJNTLists, scale=0.3)

        for i in fingerAllCtrlLists:
            controllerColor(i, 'yellow')

        for i in range(len(fingerFKJNTLists)):
            cmds.parentConstraint(fingerAllCtrlLists[i], fingerFKJNTLists[i], mo=True)

        #* separate finger Controller Lists by 3 then make child the later(-1) to the former(-2) 
        fingerCtrlLists = list(filter(lambda x: 'root' not in x and '0' not in x, fingerAllCtrlLists))
        fingerCtrlLists = [fingerCtrlLists[f:f+3] for f in range(0, len(fingerCtrlLists), 3)]

        cmds.parent(getRoot(sel=fingerCtrlLists[0][-1], nodType='transform'), fingerCtrlLists[0][-2])
        cmds.parent(getRoot(sel=fingerCtrlLists[0][-2], nodType='transform'), fingerCtrlLists[0][-3])

        cmds.parent(getRoot(sel=fingerCtrlLists[1][-1], nodType='transform'), fingerCtrlLists[1][-2])
        cmds.parent(getRoot(sel=fingerCtrlLists[1][-2], nodType='transform'), fingerCtrlLists[1][-3])

        cmds.parent(getRoot(sel=fingerCtrlLists[2][-1], nodType='transform'), fingerCtrlLists[2][-2])
        cmds.parent(getRoot(sel=fingerCtrlLists[2][-2], nodType='transform'), fingerCtrlLists[2][-3])

        cmds.parent(getRoot(sel=fingerCtrlLists[3][-1], nodType='transform'), fingerCtrlLists[3][-2])
        cmds.parent(getRoot(sel=fingerCtrlLists[3][-2], nodType='transform'), fingerCtrlLists[3][-3])

        cmds.parent(getRoot(sel=fingerCtrlLists[4][-1], nodType='transform'), fingerCtrlLists[4][-2])
        # cmds.parent(getRoot(sel=fingerCtrlLists[4][-2], nodType='transform'), fingerCtrlLists[4][-3])

        if filter(lambda x: '0' in x, fingerAllCtrlLists) is not 0:
            #fingerAllCtrlLists = [fingerAllCtrlLists[f:f+4] for f in range(0, len(fingerAllCtrlLists), 4)]
            cmds.parent(getRoot(sel=fingerCtrlLists[0][-3], nodType='transform'), fingerAllCtrlLists[0])
            cmds.parent(getRoot(sel=fingerCtrlLists[1][-3], nodType='transform'), fingerAllCtrlLists[4])
            cmds.parent(getRoot(sel=fingerCtrlLists[2][-3], nodType='transform'), fingerAllCtrlLists[8])
            cmds.parent(getRoot(sel=fingerCtrlLists[3][-3], nodType='transform'), fingerAllCtrlLists[13])
            cmds.parent(getRoot(sel=fingerCtrlLists[4][-2], nodType='transform'), fingerAllCtrlLists[18])
            if filter(lambda x: 'root' in x, fingerAllCtrlLists) is not 0:
                cmds.parent(getRoot(sel=fingerAllCtrlLists[8], nodType='transform'), fingerAllCtrlLists[12])
                cmds.parent(getRoot(sel=fingerAllCtrlLists[13], nodType='transform'), fingerAllCtrlLists[17])
                cmds.parent(getRoot(sel=fingerAllCtrlLists[12], nodType='transform'), fingerAllCtrlLists[17])
                
        fingerFKctrlGRP = cmds.group(empty=True, w=True, n='finger_FK_ctrl_GRP')
        aligner(fingerFKctrlGRP, wristRootJNT, Const='parent')

        if cmds.objExists('finger_'+side+'_ctrl_GRP') is False:
            fingerCtrlGRP = cmds.group(empty=True, w=True, n='finger_'+side+'_ctrl_GRP')
            aligner(fingerCtrlGRP, wristRootJNT, Const='parent')
        else: 
            fingerCtrlGRP = cmds.ls('finger_'+side+'_ctrl_GRP')[0]

        cmds.parent(getRoot(sel=fingerCtrlLists[0][0], nodType='transform'), fingerFKctrlGRP)
        cmds.parent(getRoot(sel=fingerCtrlLists[1][0], nodType='transform'), fingerFKctrlGRP)
        cmds.parent(getRoot(sel=fingerCtrlLists[2][0], nodType='transform'), fingerFKctrlGRP)
        # cmds.parent(getRoot(sel=fingerCtrlLists[3][0], nodType='transform'), fingerFKctrlGRP)
        cmds.parent(getRoot(sel=fingerCtrlLists[4][0], nodType='transform'), fingerFKctrlGRP)

        cmds.parent(fingerFKctrlGRP, fingerCtrlGRP)

        cmds.parentConstraint(wristRootJNT, fingerCtrlGRP, mo=True)


        #++ make IK finger Controllers ++#
        fingerIKJNTLists = cmds.ls('finger_*'+side+'*_IK_joint', type='joint')
        fingerIKJNTLists = [f for f in fingerIKJNTLists if '_0_' not in f]

        fingerIKJNTLists = [fingerIKJNTLists[f:f+4] for f in range(0, len(fingerIKJNTLists), 4)]

        fingerIKhandle1 = cmds.ikHandle(sj=fingerIKJNTLists[0][0], ee=fingerIKJNTLists[0][-1], solver='ikSCsolver', n=fingerIKJNTLists[0][0].split('_')[1]+side+'_IK_handle')
        fingerIKhandle2 = cmds.ikHandle(sj=fingerIKJNTLists[1][0], ee=fingerIKJNTLists[1][-1], solver='ikSCsolver', n=fingerIKJNTLists[1][0].split('_')[1]+side+'_IK_handle')
        fingerIKhandle3 = cmds.ikHandle(sj=fingerIKJNTLists[2][0], ee=fingerIKJNTLists[2][-1], solver='ikSCsolver', n=fingerIKJNTLists[2][0].split('_')[1]+side+'_IK_handle')
        fingerIKhandle4 = cmds.ikHandle(sj=fingerIKJNTLists[3][0], ee=fingerIKJNTLists[3][-1], solver='ikSCsolver', n=fingerIKJNTLists[3][0].split('_')[1]+side+'_IK_handle')
        fingerIKhandle5 = cmds.ikHandle(sj=fingerIKJNTLists[4][0], ee=fingerIKJNTLists[4][-1], solver='ikSCsolver', n=fingerIKJNTLists[4][0].split('_')[1]+side+'_IK_handle')

        cmds.hide(fingerIKhandle1[0])
        cmds.hide(fingerIKhandle2[0])
        cmds.hide(fingerIKhandle3[0])
        cmds.hide(fingerIKhandle4[0])
        cmds.hide(fingerIKhandle5[0])


        for i in range(0, 5):
            for j in range(len(fingerIKJNTLists[i])-1):
                cmds.connectAttr(fingerIKJNTLists[i][j]+'.rotate', cmds.listRelatives(fingerCtrlLists[i][j], p=True)[0]+'.rotate')

        fingerIKctrl1 = makeController(fingerIKJNTLists[0][-1], shape='cube', scale=0.6)
        controllerColor(fingerIKctrl1, 'red')
        fingerIKctrl2 = makeController(fingerIKJNTLists[1][-1], shape='cube', scale=0.6)
        controllerColor(fingerIKctrl2, 'red')
        fingerIKctrl3 = makeController(fingerIKJNTLists[2][-1], shape='cube', scale=0.6)
        controllerColor(fingerIKctrl3, 'red')
        fingerIKctrl4 = makeController(fingerIKJNTLists[3][-1], shape='cube', scale=0.6)
        controllerColor(fingerIKctrl4, 'red')
        fingerIKctrl5 = makeController(fingerIKJNTLists[4][-1], shape='cube', scale=0.6)
        controllerColor(fingerIKctrl5, 'red')

        cmds.parent(fingerIKhandle1[0], fingerIKctrl1)
        cmds.parent(fingerIKhandle2[0], fingerIKctrl2)
        cmds.parent(fingerIKhandle3[0], fingerIKctrl3)
        cmds.parent(fingerIKhandle4[0], fingerIKctrl4)
        cmds.parent(fingerIKhandle5[0], fingerIKctrl5)

        fingerIKctrlGRP = cmds.group(empty=True, w=True, n='finger_IK_ctrl_GRP')
        aligner(fingerIKctrlGRP, wristRootJNT, Const='parent')

        cmds.parent(getRoot(sel=fingerIKctrl1[0], nodType='transform'), fingerIKctrlGRP)
        cmds.parent(getRoot(sel=fingerIKctrl2[0], nodType='transform'), fingerIKctrlGRP)
        cmds.parent(getRoot(sel=fingerIKctrl3[0], nodType='transform'), fingerIKctrlGRP)
        cmds.parent(getRoot(sel=fingerIKctrl4[0], nodType='transform'), fingerIKctrlGRP)
        cmds.parent(getRoot(sel=fingerIKctrl5[0], nodType='transform'), fingerIKctrlGRP)

        cmds.parent(fingerIKctrlGRP, fingerCtrlGRP)
        cmds.parent(fingerCtrlGRP, sidectrlGRP)



    #++ make Twist SetUp ++# 
    twistJNT = cmds.duplicate(selecFirst, parentOnly=True, n=selectedName1+'_twist_joint')
    twistEndJNT = cmds.duplicate(selecSecond, parentOnly=True, n=selectedName1+'_twist_end_joint')
    twistRotJNT = cmds.duplicate(selecFirst, parentOnly=True, n=selectedName1+'_twist_rot_joint')

    cmds.parent(twistJNT, w=True)
    cmds.parent(twistEndJNT, twistJNT)
    upTwistJNTGRP = makeOwnGRP(twistJNT, style='GRP')


    upTwistikHandle = cmds.ikHandle(sj=twistJNT[0], ee=twistEndJNT[0], solver='ikRPsolver', n=twistJNT[0].replace('_joint', '_ik_handle'))
    upTwistikHandleGRP = makeOwnGRP(upTwistikHandle[0], style='GRP')
   
    cmds.setAttr(upTwistikHandle[0]+'.poleVectorX', 0)
    cmds.setAttr(upTwistikHandle[0]+'.poleVectorY', 0)
    cmds.setAttr(upTwistikHandle[0]+'.poleVectorZ', 0)

    cmds.pointConstraint(selectedIKFirst, upTwistJNTGRP, mo=True)
    cmds.pointConstraint(selectedFKFirst, upTwistJNTGRP, mo=True)
    cmds.pointConstraint(selectedIKMiddle, upTwistikHandleGRP, mo=True)
    cmds.pointConstraint(selectedFKMiddle, upTwistikHandleGRP, mo=True)

    cmds.parent(twistRotJNT, w=True)
    upTwistRotGRP = makeOwnGRP(twistRotJNT, style='GRP')
    cmds.parentConstraint(selectedIKFirst, upTwistRotGRP, mo=True)
    cmds.parentConstraint(selectedFKFirst, upTwistRotGRP, mo=True)
    cmds.orientConstraint(twistJNT, twistRotJNT, mo=True)

    uptwistMD = cmds.createNode('multiplyDivide', n=twistJNT[0]+'_MD')
    if side == 'R':
        cmds.setAttr(uptwistMD+'.input2X', 1)
    else:
        cmds.setAttr(uptwistMD+'.input2X', -1)
        
    cmds.connectAttr(twistRotJNT[0]+'.rotateX', uptwistMD+'.input1X')
    cmds.connectAttr(uptwistMD+'.outputX', selectedName1+'_spik_handle.twist')

    #* Make Wrist Twist SetUp from here
    wristTwistJNT = cmds.duplicate(wristRootJNT, po=True, n=wristRootJNT.replace('_root_joint', '_twist_root_joint'))
    wristTwistRotJNT = cmds.duplicate(wristRootJNT, po=True, n=wristRootJNT.replace('_root_joint', '_rot_joint'))
    wristTwistEndJNT = cmds.duplicate(wristRootJNT.replace('_root_joint', '_end_joint'), po=True, n=wristRootJNT.replace('_end_joint', '_twist_end_joint'))

    cmds.parent(wristTwistJNT, w=True)
    cmds.parent(wristTwistEndJNT, wristTwistJNT)

    lowTwistikHandle = cmds.ikHandle(sj=wristTwistJNT[0], ee=wristTwistEndJNT[0], solver='ikRPsolver', n=wristTwistJNT[0].replace('_root_joint', '_ik_handle'))
    cmds.setAttr(lowTwistikHandle[0]+'.poleVectorX', 0)
    cmds.setAttr(lowTwistikHandle[0]+'.poleVectorY', 0)
    cmds.setAttr(lowTwistikHandle[0]+'.poleVectorZ', 0)
    lowTwistikHandleGRP = makeOwnGRP(lowTwistikHandle[0], style='GRP')
    cmds.parentConstraint(wristIKsubCtrl, lowTwistikHandleGRP, mo=True)
    cmds.parentConstraint(wristFKctrl, lowTwistikHandleGRP, mo=True)

    wristTwistJNTGRP = makeOwnGRP(wristTwistJNT, style='GRP')
    wristTwistRotJNTGRP = makeOwnGRP(wristTwistRotJNT, style='GRP')
    cmds.pointConstraint(selectedIKLast, wristTwistJNTGRP, mo=True)
    cmds.pointConstraint(selectedFKLast, wristTwistJNTGRP, mo=True)
    cmds.parentConstraint(wristRootJNT, wristTwistRotJNTGRP, mo=True)
    cmds.orientConstraint(wristTwistJNT, wristTwistRotJNT, mo=True)

    lowtwistMD = cmds.createNode('multiplyDivide', n=wristTwistJNT[0]+'_MD')
    cmds.setAttr(lowtwistMD+'.input2X', -1)
    cmds.connectAttr(wristTwistRotJNT[0]+'.rotateX', lowtwistMD+'.input1X')
    cmds.connectAttr(lowtwistMD+'.outputX', selectedName2+'_spik_handle.twist')


    #* classify hierarchy and make lowArm fk controlls whole lowArmtwist System to prevent double transform 
    upJNTsGRP = cmds.group(empty=True, w=True, n=selectedName1+'_joint_GRP')
    lowJNTsGRP = cmds.group(empty=True, w=True, n=selectedName2+'_joint_GRP')
    aligner(lowJNTsGRP, selectedFKMiddle, Const='parent')


    cmds.parent(upTwistJNTGRP, upJNTsGRP)
    cmds.parent(upTwistRotGRP, upJNTsGRP)
    cmds.parent(rollShoulderGRP, upJNTsGRP)

    cmds.parent(rollElbowGRP, lowJNTsGRP)
    cmds.parent(wristTwistJNTGRP, lowJNTsGRP)
    cmds.parent(wristRootGRP, lowJNTsGRP)
    cmds.parent(wristTwistRotJNTGRP, lowJNTsGRP)

    cmds.parent(upJNTsGRP, skinJointGRP)
    cmds.parent(lowJNTsGRP, skinJointGRP)

    cmds.parentConstraint(selectedIKMiddle, lowJNTsGRP, mo=True)
    cmds.parentConstraint(selectedFKMiddle, lowJNTsGRP, mo=True)



    #++ make ik fk Switcher ++#

    ikfkSwitcher = makeController(selectedIKLast, shape='cube', addName='_FK_switch', scale=1.1)
    addCustomAttribute(ikfkSwitcher)
    cmds.addAttr(ikfkSwitcher, ln='IKFK', nn="IKFK", at="float", maxValue=1, minValue=0)
    cmds.setAttr(ikfkSwitcher[0]+'.IKFK', e=1, keyable=1)

    controllerColor(ikfkSwitcher, 'white')
    IKFKswitchREV = cmds.createNode('reverse', n='IKFKswitchREV')
    cmds.connectAttr('{0}.IKFK'.format(ikfkSwitcher[0]), '{0}.inputX'.format(IKFKswitchREV))

    #* ik - fk visibility 
    cmds.connectAttr('{0}.outputX'.format(IKFKswitchREV), '{0}.visibility'.format(sideIKGRP))
    cmds.connectAttr('{0}.outputX'.format(IKFKswitchREV), '{0}.visibility'.format(selectedIKFirst))
    cmds.connectAttr('{0}.IKFK'.format(ikfkSwitcher[0]), '{0}.visibility'.format(sideFKGRP))
    cmds.connectAttr('{0}.IKFK'.format(ikfkSwitcher[0]), '{0}.visibility'.format(selectedFKFirst))

    #* ik connections
    cmds.connectAttr(IKFKswitchREV+'.outputX', ribbonCtrlPos1+'_parentConstraint1.'+selectedIKFirst+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', lockCtrlPos+'_parentConstraint1.'+selectedIKMiddle+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', ribbonCtrlPos5+'_parentConstraint1.'+selectedIKLast+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', rollElbowGRP+'_parentConstraint1.'+selectedIKMiddle+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', wristRootGRP+'_orientConstraint1.'+ikWristLoc[0]+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', wristRootGRP+'_pointConstraint1.'+selectedIKLast+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', lowJNTsGRP+'_parentConstraint1.'+selectedIKMiddle+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', wristTwistJNTGRP+'_pointConstraint1.'+selectedIKLast+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', lowTwistikHandleGRP+'_parentConstraint1.'+wristIKsubCtrl[0]+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', upTwistJNTGRP+'_pointConstraint1.'+selectedIKFirst+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', upTwistikHandleGRP+'_pointConstraint1.'+selectedIKMiddle+'W0')
    cmds.connectAttr(IKFKswitchREV+'.outputX', upTwistRotGRP+'_parentConstraint1.'+selectedIKFirst+'W0')

    #* fk connections 
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', rollElbowGRP+'_parentConstraint1.'+selectedFKMiddle+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', ribbonCtrlPos1+'_parentConstraint1.'+selectedFKFirst+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', lockCtrlPos+'_parentConstraint1.'+selectedFKMiddle+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', ribbonCtrlPos5+'_parentConstraint1.'+selectedFKLast+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', wristRootGRP+'_orientConstraint1.'+fkWristLoc[0]+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', wristRootGRP+'_pointConstraint1.'+selectedFKLast+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', lowJNTsGRP+'_parentConstraint1.'+selectedFKMiddle+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', wristTwistJNTGRP+'_pointConstraint1.'+selectedFKLast+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', lowTwistikHandleGRP+'_parentConstraint1.'+wristFKctrl[0]+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', upTwistJNTGRP+'_pointConstraint1.'+selectedFKFirst+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', upTwistikHandleGRP+'_pointConstraint1.'+selectedFKMiddle+'W1')
    cmds.connectAttr(ikfkSwitcher[0]+'.IKFK', upTwistRotGRP+'_parentConstraint1.'+selectedFKFirst+'W1')





    #++ IK stretch SetUp ++#

    lenCRV = cmds.curve(d=1, 
            p=[cmds.xform(selectedIKFirst, query=True, t=True, ws=True), cmds.xform(selectedIKMiddle, query=True, t=True, ws=True), cmds.xform(selectedIKLast, query=True, t=True, ws=True)], 
            k=(0, 1, 2), n=selectedName1+'_arcLength_curve')


    cmds.select(clear=True)
    cmds.select(selectedIKFirst, r=True)
    cmds.select(selectedIKMiddle, selectedIKLast, add=True)
    cmds.select(lenCRV, add=True)
    arcLenSkinCluster = cmds.skinCluster(tsb=True, dr=4.0)
    cmds.skinPercent(arcLenSkinCluster[0], lenCRV+'.cv[0]', transformValue=[(selectedIKFirst, 1)])
    cmds.skinPercent(arcLenSkinCluster[0], lenCRV+'.cv[1]', transformValue=[(selectedIKMiddle, 1)])
    cmds.skinPercent(arcLenSkinCluster[0], lenCRV+'.cv[2]', transformValue=[(selectedIKLast, 1)])

    arcLen = cmds.arclen(lenCRV)
    distanceNode = cmds.createNode('distanceBetween', n=selectedIKFirst+'_DIST')
    cmds.connectAttr(shoulderIKCtrl[0]+'.worldMatrix', distanceNode+'.inMatrix1')
    cmds.connectAttr(wristIKsubCtrl[0]+'.worldMatrix', distanceNode+'.inMatrix2')

    distanceMD = cmds.createNode('multiplyDivide', n='stretchIK_Dist_MD')
    cmds.setAttr(distanceMD+'.operation', 2)
    cmds.connectAttr(distanceNode+'.distance', distanceMD+'.input1X')

    distanceCOND = cmds.createNode('condition', n='stretchIK_Dist_COND')
    cmds.setAttr(distanceCOND+'.operation', 2)
    cmds.connectAttr(distanceMD+'.outputX', distanceCOND+'.firstTerm')
    cmds.connectAttr(distanceMD+'.outputX', distanceCOND+'.colorIfTrueR')
    cmds.setAttr(distanceCOND+'.secondTerm', arcLen)
    cmds.setAttr(distanceCOND+'.colorIfFalseR', arcLen)

    distanceMD2 = cmds.createNode('multiplyDivide', n='stretchIK_Dist_MD2')
    cmds.setAttr(distanceMD2+'.operation', 2)
    cmds.setAttr(distanceMD2+'.input2X', arcLen)
    cmds.delete(lenCRV)


    #* Add ik stretch OnOff Attribute to ik wrist Controller 
    addCustomAttribute(wristIKmainCtrl)
    cmds.addAttr(wristIKmainCtrl[0], ln='Stretch_On_Off', nn="Stretch_On_Off", at="float", maxValue=1, minValue=0, defaultValue=0)
    cmds.addAttr(wristIKmainCtrl[0], ln='Up_Stretch', nn="Up_Stretch", at="float", minValue=0, defaultValue=1)
    cmds.addAttr(wristIKmainCtrl[0], ln='Low_Stretch', nn="Low_Stretch", at="float", minValue=0, defaultValue=1)
    cmds.setAttr(wristIKmainCtrl[0]+'.Stretch_On_Off', e=1, keyable=1)
    cmds.setAttr(wristIKmainCtrl[0]+'.Up_Stretch', e=1, keyable=1)
    cmds.setAttr(wristIKmainCtrl[0]+'.Low_Stretch', e=1, keyable=1)

    stretchBLND = cmds.createNode('blendColors', n='stretchIK_BLND')

    cmds.connectAttr(distanceCOND+'.outColorR', stretchBLND+'.color1R')
    cmds.setAttr(stretchBLND+'.color2R', arcLen)

    cmds.connectAttr(stretchBLND+'.outputR', distanceMD2+'.input1X')
    cmds.connectAttr(wristIKmainCtrl[0]+'.Stretch_On_Off', stretchBLND+'.blender')

    stretchUpMD = cmds.createNode('multiplyDivide', n='stretch_IK_Up_MD')
    stretchLowMD = cmds.createNode('multiplyDivide', n='stretch_IK_Low_MD')
    cmds.setAttr(stretchUpMD+'.operation', 1)
    cmds.setAttr(stretchLowMD+'.operation', 1)

    cmds.connectAttr(wristIKmainCtrl[0]+'.Up_Stretch', stretchUpMD+'.input1X')
    cmds.connectAttr(wristIKmainCtrl[0]+'.Low_Stretch', stretchLowMD+'.input1X')

    cmds.connectAttr(distanceMD2+'.outputX', stretchUpMD+'.input2X')
    cmds.connectAttr(distanceMD2+'.outputX', stretchLowMD+'.input2X')


    #* Now Connects to joint's scaleX
    cmds.connectAttr(stretchUpMD+'.outputX', selectedIKFirst+'.scaleX')
    cmds.connectAttr(stretchLowMD+'.outputX', selectedIKMiddle+'.scaleX')


    #* Add poleVector Twist Attribute
    addCustomAttribute(wristIKmainCtrl)
    cmds.addAttr(wristIKmainCtrl[0], ln='Twist', nn="Twist", at="float", defaultValue=0)
    cmds.setAttr(wristIKmainCtrl[0]+'.Twist', e=1, keyable=1)
    cmds.connectAttr(wristIKmainCtrl[0]+'.Twist', rpIKHandle[0]+'.twist')



    #++ later classify ++#

    if cmds.objExists('ctrl_GRP') is False:
        ctrlGRP = cmds.group(empty=True, w=True, n='ctrl_GRP')
        cmds.parent(ctrlGRP, globalGRP)
    else:
        ctrlGRP = cmds.ls('ctrl_GRP')[0]

    bendRootGRP = cmds.group(empty=True, w=True, n=sideGRPName+'_bend_root_GRP')
    sidectrlGRP = cmds.group(empty=True, w=True, n=sideGRPName+'_ctrl_GRP')
    sideTwistIKhandleGRP = cmds.group(empty=True, w=True, n=sideGRPName+'_twist_ik_handle_GRP')

    if cmds.objExists('twist_ik_handle_GRP') is False:
        twistIKhandleGRP = cmds.group(empty=True, w=True, n='twist_ik_handle_GRP')
        cmds.parent(twistIKhandleGRP, extras)
    else:
        twistIKhandleGRP = cmds.ls('twist_ik_handle_GRP')[0]


    if cmds.objExists('twist_ik_handle_GRP') is False:
        twistIKhandleGRP = cmds.group(empty=True, w=True, n='twist_ik_handle_GRP')
        cmds.parent(twistIKhandleGRP, extras)
    else:
        twistIKhandleGRP = cmds.ls('twist_ik_handle_GRP')[0]

    cmds.parent(sideGRPName+'_spik_GRP', 'spik_GRP')

    cmds.parent(lockGRP, lockCtrl)
    cmds.parent(ribbonCtrlPos5, ribbonCtrlPos1, bendRootGRP)
    cmds.parent(bendRootGRP, sideBendctrlGRP)

    cmds.parent(sideIKGRP, sideFKGRP, getRoot(nodType='transform', sel=ikfkSwitcher), sidectrlGRP)
    cmds.parent(sideBendctrlGRP, sidectrlGRP)
    cmds.parent(lockCtrlPos, sidectrlGRP)

    cmds.parent(sidectrlGRP, ctrlGRP)


    cmds.parent(upTwistikHandleGRP, sideTwistIKhandleGRP)
    cmds.parent(lowTwistikHandleGRP, sideTwistIKhandleGRP)
    cmds.parent(sideTwistIKhandleGRP, twistIKhandleGRP)




    #++ Do finger SetUp if finger exists ++#
    for i in cmds.listRelatives(wristRootJNT, children=True):
        if 'finger' == i.split('_')[0]:
            print('fingerGRP Found')
            fingerSetUp(side, sidectrlGRP)
def main():
	facecluster=[]
	dupobject=[]
	#return null if no target object specified
	if maya.textScrollList(targetObjBox,q=True,si=True)==None:
		return
	selectface=processFaceSelection()
	#if not select face, return null
	if selectface==None:
		return
	if maya.radioButtonGrp(snapModeButton,q=True,sl=True)==2:
		duplicateMode=True
		grp_dupObj=maya.group(n='grp_dup_transform',em=True)
	else:
		duplicateMode=False
	targetObj=maya.textScrollList(targetObjBox,q=True,si=True)[0]
	objectname=selectface[0].split('.')[0]
	#print objectname
	for com in selectface:
		#print com
		if duplicateMode==True:
			dup_targetObj=maya.duplicate(targetObj,n='dup_'+targetObj)
			maya.parent(dup_targetObj,grp_dupObj)
		dup_object=maya.duplicate(objectname,n='dup_'+objectname)
		dupobject.append(dup_object[0])
		#print dupobject			
		raw_data=maya.polyInfo(com,fv=True)[0]
		#print raw_data
		#data processing
		raw_verindex=raw_data.split(':')[1]
		#print raw_verindex
		verindex=[]  
		ver_all=raw_verindex.split(' ')
		#print ver_all
		for ver in ver_all:
			if ver != ''and ver != '\n':
				verindex.append(ver)
		#print verindex
		for ver in verindex:
			#print objectname
			cluster_temp=maya.cluster(objectname+'.vtx[{0}]'.format(ver),en=True,rel=True)
			if duplicateMode==True:
				maya.pointConstraint(cluster_temp,dup_targetObj,o=(0,0,0))
			else:			
				maya.pointConstraint(cluster_temp,targetObj,o=(0,0,0))
			facecluster.append(cluster_temp)
		#print facecluster
		maya.polyChipOff(dup_object[0]+'.'+com.split('.')[1],kft=True,dup=True,off=0,ch=True)
		grp_obj=maya.polySeparate(dup_object,o=True,n='seperate_'+dup_object[0])
		if duplicateMode==True:
			maya.normalConstraint(grp_obj[1],dup_targetObj,aim=(0,1,0),u=(1,0,0),wut='vector')
		else:
			maya.normalConstraint(grp_obj[1],targetObj,aim=(0,1,0),u=(1,0,0),wut='vector')


	#print T_channel_keyable
	#print R_channel_keyable
	if T_channel_keyable:
		maya.setKeyframe(targetObj,at='translataeX')
		maya.setKeyframe(targetObj,at='translateY')
		maya.setKeyframe(targetObj,at='translateZ')
		maya.delete(targetObj+'_pointConstraint*')
	  
	if R_channel_keyable:
		maya.setKeyframe(targetObj,at='rotateX')
		maya.setKeyframe(targetObj,at='rotateY')
		maya.setKeyframe(targetObj,at='rotateZ')	
		maya.delete(targetObj+'_normalConstraint*')
	#print facecluster
	for cluster in facecluster:
		#not sure here which to delete??
		maya.delete(cluster)
	for dupObj in dupobject:
		maya.delete(dupObj)
Exemplo n.º 44
0
def rivet(vtx, surf, outGeo='', loc=0):

    # Get geo
    geo = cmds.listRelatives(surf, p=1)[0]

    # Get vertex ID
    vtxId = vtx.split('[')[1]
    vtxId = vtxId.split(']')[0]

    # Get adjacent edge
    edges1 = cmds.polyInfo(vtx, vertexToEdge=1)[0]
    edges1 = edges1.split(':')[1]
    edges1 = edges1.split(' ')
    edges = []
    for i in edges1:
        if i:
            if '\n' not in i:
                edges.append(int(i))

    # Create a live curve on edge
    cme = cmds.createNode('curveFromMeshEdge',
                          n='{}_edge_{}_cry'.format(surf, edges[1]))
    cmds.setAttr('{}.edgeIndex[0]'.format(cme), edges[1])
    if outGeo:
        cmds.connectAttr(outGeo, '{}.inputMesh'.format(cme))
    else:
        cmds.connectAttr('{}.worldMesh'.format(surf),
                         '{}.inputMesh'.format(cme))

    # Create a curve info node for edge curve
    poc = cmds.createNode('pointOnCurveInfo',
                          n='{}_e{}_v{} _poc'.format(surf, edges[1], vtxId))
    cmds.setAttr('{}.turnOnPercentage'.format(poc), 1)
    cmds.connectAttr('{}.outputCurve'.format(cme), '{}.inputCurve'.format(poc))

    # Create rivet
    if loc == 1:
        riv = cmds.spaceLocator(n='{}_RIV'.format(geo))[0]
    else:
        riv = cmds.createNode('transform', n='{}_RIV'.format(geo))
    cmds.connectAttr('{}.result.position'.format(poc),
                     '{}.translate'.format(riv))

    # Check if at the correct end of the curve
    chk1 = cmds.xform(riv, q=1, ws=1, t=1)
    chk2 = cmds.xform(vtx, q=1, ws=1, t=1)
    if chk1 != chk2:
        cmds.setAttr('{}.parameter'.format(poc), 1)

    # Create a normal constraint to orient
    cnst = cmds.normalConstraint(surf,
                                 riv,
                                 n='{}_nrmlCnst'.format(riv),
                                 aim=[0, 1, 0],
                                 u=[1, 0, 0])[0]
    if outGeo:
        con = cmds.listConnections('{}.target[0].targetGeometry'.format(cnst),
                                   d=0,
                                   p=1)[0]
        cmds.disconnectAttr(con, '{}.target[0].targetGeometry'.format(cnst))
        cmds.connectAttr(outGeo, '{}.target[0].targetGeometry'.format(cnst))
    cmds.connectAttr('{}.tangent'.format(poc), '{}.worldUpVector'.format(cnst))
    cmds.setAttr('{}.hiddenInOutliner'.format(cnst), 1)

    return riv
Exemplo n.º 45
0
def surfaceConstrainedCtrl(	surface,
							ctrlPt,
							ctrlType,
							ctrlPosition	= [0,0,0],
							ctrlRotate		= [0,0,0],
							ctrlScale		= 1.0,
							method			= 'geometryConstraint',
							upVector		= [0,1,0],
							upType			= 'vector',
							upObject		= None,
							rayOrigin		= None,
							allowOffset		= False,
							addCurveComp	= False,
							prefix			= None ):
	'''
	Create a control object that is constrained to the surface of a specified geometry shape
	@param surface: Geometry to attach the control to.
	@type surface: str
	@param ctrlPt: Control position.
	@type ctrlPt: list or tuple
	@param ctrlType: Control shape type.
	@type ctrlType: str
	@param ctrlScale: Control shape scale.
	@type ctrlScale: float
	@param method: Surface constraint method. Accepted values are "geometryConstraint" and "rayIntersect".
	@type method: str
	@param upVector: Normal constraint upVector.
	@type upVector: list or tuple
	@param upType: Normal constraint upVector type. Valid types are "scene", "object", "objectrotation", "vector", or "none".
	@type upType: str
	@param upObject: Normal constraint upVector object.
	@type upObject: str
	@param rayOrigin: Ray origin locator.
	@type rayOrigin: str
	@param allowOffset: Allow the constraint to pull away form the guide surface.
	@type allowOffset: bool
	@param addCurveComp: Add curvature compensation attributes that will adjust reference transform orientation based on control translation.
	@type addCurveComp: bool
	@param prefix: Name prefix for control and created nodes.
	@type prefix: str
	'''
	# ==========
	# - Checks -
	# ==========

	# Surface
	if not mc.objExists(surface):
		raise Exception('Surface "'+surface+'" does not exist!')

	# Method
	methodList = ['geometryConstraint','rayIntersect']
	if not methodList.count(method):
		raise Exception('Invalid constraint method "'+method+'"!')

	# Ray Origin
	if not rayOrigin: rayOrigin = ''
	if method == 'rayIntersect' and not mc.objExists(rayOrigin):
		raise Exception('Ray origin transform "'+rayOrigin+'" does not exist!')

	# UpVector Object
	if (upType == 'object' or upType == 'objectrotation') and not mc.objExists(upObject):
		raise Exception('UpVector transform "'+upObject+'" does not exist!')

	# ==================
	# - Create Control -
	# ==================

	ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()
	ctrl = ctrlBuilder.create(	ctrlType,
								prefix+'_ctrl',
								translate	= ctrlPosition,
								rotate		= ctrlRotate,
								scale		= ctrlScale )

	ctrlGrp = mc.group(em=True,n=prefix+'_ctrlGrp')
	ctrl_mvCancelGrp = mc.group(em=True,n=prefix+'_moveCancel_grp')
	mc.parent(ctrl_mvCancelGrp,ctrlGrp)
	mc.parent(ctrl,ctrl_mvCancelGrp)

	# Control Xform Group
	ctrlGrpXform = mc.group(em=True,n=prefix+'_ctrlGrpXform')

	# =======================================
	# - Build Reference Transform Hierarchy -
	# =======================================

	ctrlLocalTrans = mc.spaceLocator(n=prefix+'_localTrans_loc')[0]
	ctrlLocalTransGrp = mc.group(ctrlLocalTrans,n=prefix+'_localTrans_grp')
	ctrlReferenceGrp = mc.group(ctrlLocalTransGrp,n=prefix+'_reference_grp')

	mc.setAttr(ctrlLocalTrans+'.localScale',0.05,0.05,0.05)

	# Curvature compensation
	if addCurveComp:
		mc.addAttr(ctrlLocalTrans,ln='curvatureX',dv=0.0,k=True)
		mc.addAttr(ctrlLocalTrans,ln='curvatureY',dv=0.0,k=True)
		curveCompNode = mc.createNode('multiplyDivide',n=prefix+'_curvature_multiplyDivide')
		mc.connectAttr(ctrlLocalTrans+'.translateX',curveCompNode+'.input1X',f=True)
		mc.connectAttr(ctrlLocalTrans+'.translateY',curveCompNode+'.input1Y',f=True)
		mc.connectAttr(ctrlLocalTrans+'.curvatureX',curveCompNode+'.input2X',f=True)
		mc.connectAttr(ctrlLocalTrans+'.curvatureY',curveCompNode+'.input2Y',f=True)
		mc.connectAttr(curveCompNode+'.outputX',ctrlLocalTransGrp+'.rotateY',f=True)
		mc.connectAttr(curveCompNode+'.outputY',ctrlLocalTransGrp+'.rotateX',f=True)

	# =======================
	# - Position Transforms -
	# =======================

	for c in [ctrlGrpXform,ctrlReferenceGrp]:
		mc.move(ctrlPt[0],ctrlPt[1],ctrlPt[2],c)

	# ============================
	# - Build Surface Constraint -
	# ============================

	if method == 'geometryConstraint':
		constrainToSurface_geometryConstraint(surface,ctrlLocalTrans,ctrlGrpXform,prefix)
	elif method == 'rayIntersect':
		constrainToSurface_rayIntersect(surface,ctrlLocalTrans,ctrlGrpXform,rayOrigin,allowOffset,prefix)

	# Normal Constraint
	if upObject:
		normCon = mc.normalConstraint(surface,ctrlGrpXform,aim=[0,0,1],u=upVector,wut=upType,wuo=upObject,n=prefix+'_normalConstraint')[0]
	else:
		normCon = mc.normalConstraint(surface,ctrlGrpXform,aim=[0,0,1],u=upVector,wut=upType,n=prefix+'_normalConstraint')[0]

	# Orient Control Reference
	mc.setAttr(ctrlReferenceGrp+'.r',*mc.getAttr(ctrlGrpXform+'.r')[0])

	# ============================
	# - Build Connection Network -
	# ============================

	attrList = ['tx','ty','tz','rx','ry','rz','sx','sy','sz']

	# CtrlXform -> CtrlLocalTrans
	for at in ['tx','ty']: mc.connectAttr(ctrl+'.'+at,ctrlLocalTrans+'.'+at,f=True)

	# CtrlGrpXform -> CtrlGrp
	for at in attrList: mc.connectAttr(ctrlGrpXform+'.'+at,ctrlGrp+'.'+at,f=True)

	# Translate Negation
	localTransNeg = mc.createNode('multiplyDivide',n=prefix+'_moveCancel_multiplyDivide')
	mc.connectAttr(ctrl+'.t',localTransNeg+'.input1',f=True)
	mc.setAttr(localTransNeg+'.input2',-1,-1,-1)
	mc.connectAttr(localTransNeg+'.outputX',ctrl_mvCancelGrp+'.tx',f=True)
	mc.connectAttr(localTransNeg+'.outputY',ctrl_mvCancelGrp+'.ty',f=True)
	mc.connectAttr(localTransNeg+'.outputZ',ctrl_mvCancelGrp+'.tz',f=True)
	# Allow Offset - Cancel translateZ negation
	if allowOffset: mc.setAttr(localTransNeg+'.input2Z',0)

	# =================
	# - Return Result -
	# =================

	result = {}
	result['ctrl'] = ctrl
	result['moveCancel'] = ctrl_mvCancelGrp
	result['ctrlGrp'] = ctrlGrp
	result['ctrlGrpXform'] = ctrlGrpXform
	result['ctrlLocalTrans'] = ctrlLocalTrans
	result['ctrlLocalTransGrp'] = ctrlLocalTransGrp
	result['ctrlReferenceGrp'] = ctrlReferenceGrp
	result['localTransNeg'] = localTransNeg
	result['normalConstraint'] = normCon

	return result
Exemplo n.º 46
0
def surfaceConstrainedCtrl(surface,
                           ctrlPt,
                           ctrlType,
                           ctrlPosition=[0, 0, 0],
                           ctrlRotate=[0, 0, 0],
                           ctrlScale=1.0,
                           method='geometryConstraint',
                           upVector=[0, 1, 0],
                           upType='vector',
                           upObject=None,
                           rayOrigin=None,
                           allowOffset=False,
                           addCurveComp=False,
                           prefix=None):
    """
    Create a control object that is constrained to the surface of a specified geometry shape
    @param ctrlPosition:
    @param ctrlRotate:
    @param surface: Geometry to attach the control to.
    @type surface: str
    @param ctrlPt: Control position.
    @type ctrlPt: list or tuple
    @param ctrlType: Control shape type.
    @type ctrlType: str
    @param ctrlScale: Control shape scale.
    @type ctrlScale: float
    @param method: Surface constraint method. Accepted values are "geometryConstraint" and "rayIntersect".
    @type method: str
    @param upVector: Normal constraint upVector.
    @type upVector: list or tuple
    @param upType: Normal constraint upVector type. Valid types are "scene", "object", "objectrotation", "vector", or "none".
    @type upType: str
    @param upObject: Normal constraint upVector object.
    @type upObject: str
    @param rayOrigin: Ray origin locator.
    @type rayOrigin: str
    @param allowOffset: Allow the constraint to pull away form the guide surface.
    @type allowOffset: bool
    @param addCurveComp: Add curvature compensation attributes that will adjust reference transform orientation based on control translation.
    @type addCurveComp: bool
    @param prefix: Name prefix for control and created nodes.
    @type prefix: str
    """
    # ==========
    # - Checks -
    # ==========

    # Surface
    if not cmds.objExists(surface):
        raise Exception('Surface "' + surface + '" does not exist!')

    # Method
    methodList = ['geometryConstraint', 'rayIntersect']
    if not methodList.count(method):
        raise Exception('Invalid constraint method "' + method + '"!')

    # Ray Origin
    if not rayOrigin: rayOrigin = ''
    if method == 'rayIntersect' and not cmds.objExists(rayOrigin):
        raise Exception('Ray origin transform "' + rayOrigin + '" does not exist!')

    # UpVector Object
    if (upType == 'object' or upType == 'objectrotation') and not cmds.objExists(upObject):
        raise Exception('UpVector transform "' + upObject + '" does not exist!')

    # ==================
    # - Create Control -
    # ==================

    ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()
    ctrl = ctrlBuilder.create(ctrlType,
                              prefix + '_ctrl',
                              translate=ctrlPosition,
                              rotate=ctrlRotate,
                              scale=ctrlScale)

    ctrlGrp = cmds.group(em=True, n=prefix + '_ctrlGrp')
    ctrl_mvCancelGrp = cmds.group(em=True, n=prefix + '_moveCancel_grp')
    cmds.parent(ctrl_mvCancelGrp, ctrlGrp)
    cmds.parent(ctrl, ctrl_mvCancelGrp)

    # Control Xform Group
    ctrlGrpXform = cmds.group(em=True, n=prefix + '_ctrlGrpXform')

    # =======================================
    # - Build Reference Transform Hierarchy -
    # =======================================

    ctrlLocalTrans = cmds.spaceLocator(n=prefix + '_localTrans_loc')[0]
    ctrlLocalTransGrp = cmds.group(ctrlLocalTrans, n=prefix + '_localTrans_grp')
    ctrlReferenceGrp = cmds.group(ctrlLocalTransGrp, n=prefix + '_reference_grp')

    cmds.setAttr(ctrlLocalTrans + '.localScale', 0.05, 0.05, 0.05)

    # Curvature compensation
    if addCurveComp:
        cmds.addAttr(ctrlLocalTrans, ln='curvatureX', dv=0.0, k=True)
        cmds.addAttr(ctrlLocalTrans, ln='curvatureY', dv=0.0, k=True)
        curveCompNode = cmds.createNode('multiplyDivide', n=prefix + '_curvature_multiplyDivide')
        cmds.connectAttr(ctrlLocalTrans + '.translateX', curveCompNode + '.input1X', f=True)
        cmds.connectAttr(ctrlLocalTrans + '.translateY', curveCompNode + '.input1Y', f=True)
        cmds.connectAttr(ctrlLocalTrans + '.curvatureX', curveCompNode + '.input2X', f=True)
        cmds.connectAttr(ctrlLocalTrans + '.curvatureY', curveCompNode + '.input2Y', f=True)
        cmds.connectAttr(curveCompNode + '.outputX', ctrlLocalTransGrp + '.rotateY', f=True)
        cmds.connectAttr(curveCompNode + '.outputY', ctrlLocalTransGrp + '.rotateX', f=True)

    # =======================
    # - Position Transforms -
    # =======================

    for c in [ctrlGrpXform, ctrlReferenceGrp]:
        cmds.move(ctrlPt[0], ctrlPt[1], ctrlPt[2], c)

    # ============================
    # - Build Surface Constraint -
    # ============================

    if method == 'geometryConstraint':
        constrainToSurface_geometryConstraint(surface, ctrlLocalTrans, ctrlGrpXform, prefix)
    elif method == 'rayIntersect':
        constrainToSurface_rayIntersect(surface, ctrlLocalTrans, ctrlGrpXform, rayOrigin, allowOffset, prefix)

    # Normal Constraint
    if upObject:
        norcmdson = cmds.normalConstraint(surface, ctrlGrpXform, aim=[0, 0, 1], u=upVector, wut=upType, wuo=upObject,
                                      n=prefix + '_normalConstraint')[0]
    else:
        norcmdson = cmds.normalConstraint(surface, ctrlGrpXform, aim=[0, 0, 1], u=upVector, wut=upType,
                                      n=prefix + '_normalConstraint')[0]

    # Orient Control Reference
    cmds.setAttr(ctrlReferenceGrp + '.r', *cmds.getAttr(ctrlGrpXform + '.r')[0])

    # ============================
    # - Build Connection Network -
    # ============================

    attrList = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']

    # CtrlXform -> CtrlLocalTrans
    for at in ['tx', 'ty']: cmds.connectAttr(ctrl + '.' + at, ctrlLocalTrans + '.' + at, f=True)

    # CtrlGrpXform -> CtrlGrp
    for at in attrList: cmds.connectAttr(ctrlGrpXform + '.' + at, ctrlGrp + '.' + at, f=True)

    # Translate Negation
    localTransNeg = cmds.createNode('multiplyDivide', n=prefix + '_moveCancel_multiplyDivide')
    cmds.connectAttr(ctrl + '.t', localTransNeg + '.input1', f=True)
    cmds.setAttr(localTransNeg + '.input2', -1, -1, -1)
    cmds.connectAttr(localTransNeg + '.outputX', ctrl_mvCancelGrp + '.tx', f=True)
    cmds.connectAttr(localTransNeg + '.outputY', ctrl_mvCancelGrp + '.ty', f=True)
    cmds.connectAttr(localTransNeg + '.outputZ', ctrl_mvCancelGrp + '.tz', f=True)
    # Allow Offset - Cancel translateZ negation
    if allowOffset: cmds.setAttr(localTransNeg + '.input2Z', 0)

    # =================
    # - Return Result -
    # =================

    result = {}
    result['ctrl'] = ctrl
    result['moveCancel'] = ctrl_mvCancelGrp
    result['ctrlGrp'] = ctrlGrp
    result['ctrlGrpXform'] = ctrlGrpXform
    result['ctrlLocalTrans'] = ctrlLocalTrans
    result['ctrlLocalTransGrp'] = ctrlLocalTransGrp
    result['ctrlReferenceGrp'] = ctrlReferenceGrp
    result['localTransNeg'] = localTransNeg
    result['normalConstraint'] = norcmdson

    return result
Exemplo n.º 47
0
def PlacementTool():
	cmds.undoInfo(openChunk=True)
	Start = True
	if cmds.objExists('__Placement_Tool__'): 
		cmds.makeLive(none=True)
		if cmds.objExists('__Placement_Tool_c__'): cmds.delete('__Placement_Tool_c__')
		if cmds.objExists('__Placement_Tool_f__'): cmds.delete('__Placement_Tool_f__')
		if cmds.objExists('__Placement_Tool_g__'): cmds.delete('__Placement_Tool_g__')
		if cmds.objExists('__Placement_Tool__'): cmds.delete('__Placement_Tool__')
		cmds.xform(rp=(osPivot[0],osPivot[1],osPivot[2]),os=1)
		Start = False
		PT_START_UI()
	if Start:
		global osPivot
		osPivot=cmds.xform(q=1,rp=1,os=1)
		global wsPivot
		wsPivot=cmds.xform(q=1,rp=1,ws=1)
		cmds.setToolTo('moveSuperContext')
		sel=cmds.ls(sl=1,l=1)
		cmds.InvertSelection()
		cmds.select(cmds.ls(sl=1,v=1))
		cmds.select(cmds.filterExpand(sm=12))
		selAll=cmds.ls(sl=1)
		cmds.duplicate()
		cmds.group(name=('__Placement_Tool_g__'))
		cmds.CombinePolygons()
		cmds.hyperShade(assign='lambert1')
		cmds.polyMapDel()
		cmds.DeleteHistory()
		cmds.rename('__Placement_Tool__')
		cmds.hide()
		# Move Pivot
		cmds.select(sel)
		for i in sel :
		    pos = cmds.xform(i,q=1,ws=1,piv=1)
		    dup = cmds.duplicate(i,rr=1,po=1)
		    for attr in ['tx','ty','tz','rx','ry','rz','sx','sy','sz'] :
		        if cmds.getAttr(dup[0]+'.'+attr,lock=True):cmds.setAttr(dup[0]+'.'+attr,lock=False)
		    shapeNode = cmds.ls(cmds.listRelatives(i,c=1,f=1),l=1,s=1)
		    for s in shapeNode :
		        cmds.parent(s,dup[0],add=1,s=1)
		    if cmds.listRelatives(dup[0],p=1) :
		        cmds.parent(dup[0],w=1)
		    cmds.setAttr(dup[0]+'.r',0,0,0,type="double3")              
		    bb=cmds.xform(dup[0],q=1,bb=1,ws=1)
		    cp=cmds.objectCenter(dup[0])
		    xpos=cp[0];ypos=bb[1];zpos = cp[2]
		    loc=cmds.spaceLocator()
		    cmds.xform(loc[0],ws=1,t=(xpos,ypos,zpos))
		    cmds.parent(loc[0],dup[0])
		    cmds.delete(cmds.parentConstraint(i,dup[0]))
		    pivPos=cmds.xform(loc[0],q=1,ws=1,t=1)
		    cmds.xform(i,ws=1,piv=(pivPos[0],pivPos[1],pivPos[2]))
		    cmds.delete(dup[0],loc[0])
		cmds.select(sel,r=1)
		cmds.select('__Placement_Tool__',r=1);cmds.select(sel,add=1)
		cmds.normalConstraint(worldUpType="none",aimVector=(0, 1, 0),upVector=(0, 1, 0),weight=1,name='__Placement_Tool_c__')
		cmds.select('__Placement_Tool__',r=1);cmds.makeLive()
		cmds.select(selAll)
		cmds.createDisplayLayer(name="__Placement_Tool_f__",number=1,nr=1)
		import maya.mel as mel
		mel.eval('layerEditorLayerButtonTypeChange("__Placement_Tool_f__")')
		mel.eval('layerEditorLayerButtonTypeChange("__Placement_Tool_f__")')
		cmds.select(sel)
		PT_STOP_UI()
	cmds.undoInfo(closeChunk=True)
Exemplo n.º 48
0
    def scatter_action(self):
        rot = {}
        scale = {}
        sMin = {}
        scaleMinCheck = self.uiList['scaleMin_check'].isChecked()
        for dir in ['x', 'y', 'z']:
            tValue = str(self.uiList[(dir + 'Rot_input')].text())
            rot[dir] = 0 if tValue == "" else float(tValue)
            tValue = str(self.uiList[(dir + 'Scale_input')].text())
            scale[dir] = 1 if tValue == "" else float(tValue)
            tValue = str(self.uiList[(dir + 'ScaleMin_input')].text())
            sMin[dir] = 0 if tValue == "" or not scaleMinCheck else float(
                tValue)

        pos = self.memoData["posList"]
        geoCnt = len(self.memoData['geoList'])
        # step 2: keep clear of distance of object size, clear too close point
        distanceFilterCheck = self.uiList[
            'pointDistanceFilter_chek'].isChecked()
        validPointIdList = range(len(self.memoData["posList"]))
        if distanceFilterCheck:
            distVal = str(self.uiList['minDist_input'].text())
            distVal = 0 if distVal == "" else float(distVal)
            if distVal == 0:
                validPointIdList = self.filterPositionBy_bbox()
            else:
                validPointIdList = self.filterPositionBy_distance(distVal)
        #print validPointIdList
        # step 3: loop through each valid point, and create object
        scatterGrp = 'ScatterUI_dupGrp'
        if not cmds.objExists(scatterGrp):
            scatterGrp = cmds.group(n=scatterGrp, em=1)

        instanceCheck = self.uiList['instanceCheck_check'].isChecked()
        cnt = len(validPointIdList)
        for i in validPointIdList:
            each_pos = pos[i]
            newGeo = ""
            # random geo from geoList
            random.seed(i + geoCnt)
            geoId = random.randint(0, geoCnt - 1)
            geo = self.memoData['geoList'][geoId]

            if instanceCheck:
                newGeo = cmds.instance(geo)[0]
            else:
                newGeo = cmds.duplicate(geo)[0]
            cmds.parent(newGeo, scatterGrp)
            random.seed(i)
            rot_x = (random.random() - 0.5) * 2 * rot['x']
            random.seed(i + cnt * 1)
            rot_y = (random.random() - 0.5) * 2 * rot['y']
            random.seed(i + cnt * 2)
            rot_z = (random.random() - 0.5) * 2 * rot['z']

            random.seed(i + cnt * 3)
            s_x = random.uniform(sMin['x'],
                                 scale['x']) if scale['x'] != 0 else 1
            s_y = s_x
            s_z = s_x
            if not self.uiList['scaleLink_check'].isChecked():
                random.seed(i + cnt * 4)
                s_y = random.uniform(sMin['y'],
                                     scale['y']) if scale['y'] != 0 else 1
                random.seed(i + cnt * 5)
                s_z = random.uniform(sMin['z'],
                                     scale['z']) if scale['z'] != 0 else 1

            cmds.xform(newGeo, t=each_pos)
            if self.uiList['alignNormal_check'].isChecked():
                link = cmds.normalConstraint(
                    self.memoData['surface'],
                    newGeo,
                    aimVector=(0, 1, 0),
                    upVector=(0, 0, 1),
                    worldUpType="object",
                    worldUpObject=self.memoData['surface'])[0]
                cmds.delete(link)
            if self.uiList['rot_check'].isChecked():
                cmds.xform(newGeo, r=1, ro=(rot_x, rot_y, rot_z))
            if self.uiList['scale_check'].isChecked():
                cmds.xform(newGeo, r=1, s=(s_x, s_y, s_z))
Exemplo n.º 49
0
def buildLinearPoints(curve,
                      numCtrl,
                      useDistance=False,
                      guideSrf=None,
                      orient=False,
                      prefix=None,
                      suffix=None):
    '''
	Create locators along curve and project to mesh using geometry and normal constraints.
	'''
    # ==========
    # - Checks -
    # ==========

    if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(curve)
    if not suffix: suffix = 'jnt'

    # Build Controls
    ctrls = glTools.tools.createAlongCurve.create(curve,
                                                  'locator',
                                                  objCount=numCtrl,
                                                  parent=False,
                                                  useDistance=useDistance,
                                                  minPercent=0.0,
                                                  maxPercent=1.0,
                                                  spacing=1.0,
                                                  prefix=prefix,
                                                  suffix=suffix)

    # Attach Controls
    for ctrl in ctrls:

        mc.select(ctrl)
        jnt = mc.joint()

        attach = glTools.utils.attach.attachToCurve(curve,
                                                    ctrl,
                                                    useClosestPoint=True,
                                                    uAttr='param',
                                                    prefix=prefix)

        # Constrain to Guide
        if guideSrf:

            # Constrain Position
            geomConst = mc.geometryConstraint(guideSrf, ctrl)[0]

            # Constrain Orient
            if orient:
                normConst = mc.normalConstraint(guideSrf,
                                                ctrl,
                                                aimVector=(0, 0, 1),
                                                upVector=(-1, 0, 0),
                                                worldUpType='vector')[0]

                mc.connectAttr(attach[0] + '.tangent',
                               normConst + '.worldUpVector',
                               f=True)

    # Return Result
    return ctrls
Exemplo n.º 50
0
def surfaceConstraint(obj,surface,point=True,orient=True,normalAxis='x',upAxis='y',upMode='',upVector=(0,1,0),upObject='',pointMode=0,prefix=''):
	'''
	@param obj: Target object that the surface constrained transform will goal to.
	@type obj: str
	@param surface: Surface to constrain to
	@type surface: str
	@param point: Constrain point (translate)
	@type point: bool
	@param orient: Constrain orient (rotate)
	@type orient: bool
	@param normalAxis: Constrained transform axis to align with surface normal 
	@type normalAxis: str
	@param upAxis: Constrained transform axis to align with defined upVector
	@type upAxis: str
	@param upMode: Constraint upVector mode. Valid values are 'scene', 'object', 'objectrotation', 'vector' or 'none'. 
	@type upMode: str
	@param upVector: Constraint upVector. 
	@type upVector: list or tuple
	@param upObject: Constraint upVector object. Only needed for 'object' or 'objectrotation' upVector modes.
	@type upObject: str
	@param pointMode: Point (translate) constraint mode. 0 = geometryConstraint, 1 = boundaryConstraint.
	@type pointMode: int
	@param prefix: Name prefix for newly created nodes
	@type prefix: str
	'''
	# Build axis dictionary
	axisDict = {'x':(1,0,0),'y':(0,1,0),'z':(0,0,1),'-x':(-1,0,0),'-y':(0,-1,0),'-z':(0,0,-1)}
		
	# ==========
	# - Checks -
	# ==========
	
	if not mc.objExists(obj):
		raise Exception('Object "'+obj+'" does not exist!')
	
	if not mc.objExists(surface):
		raise Exception('Surface "'+surface+'" does not exist!')
	
	if not axisDict.keys().count(normalAxis):
		raise Exception('Invalid normal axis specified "'+normalAxis+'"!')
	
	if not axisDict.keys().count(upAxis):
		raise Exception('Invalid up axis specified "'+upAxis+'"!')
	
	if ((upMode == 'object') or (upMode == 'objectrotation')) and not mc.objExists(upObject):
		raise Exception('Invalid up object specified "'+upObject+'"!')
	
	# ===============================
	# - Create Constraint Transform -
	# ===============================
	
	surfConnNode = mc.createNode('transform',n=prefix+'_surfConn_grp')
	
	# ================================
	# - Constraint point (translate) -
	# ================================
	
	if point:
		
		if pointMode == 0:
			
			# Geometry Constraint
			pntConn = mc.pointConstraint(obj,surfConnNode,n=prefix+'_pointConstraint')
			geoConn = mc.geometryConstraint(surface,surfConnNode,n=prefix+'_geometryConstraint')
			
		else:
			
			# =======================
			# - Boundary Constraint -
			# =======================
			
			# World Position (vectorProduct)
			vecProduct = mc.createNode('vectorProduct',n=prefix+'_worldPos_vectorProduct')
			mc.setAttr(vecProduct+'.operation',4) # Point Matrix Product
			mc.connectAttr(obj+'.worldMatrix',vecProduct+'.matrix',f=True)
			
			# Closest Point On Surface
			cposNode = mc.createNode('closestPointOnSurface',n=prefix+'_surfacePos_closestPointOnSurface')
			mc.connectAttr(surface+'.worldSpace[0]',cposNode+'.inputSurface',f=True)
			mc.connectAttr(vecProduct+'.output',cposNode+'.inPoint',f=True)
			
			# Point On Surface Info
			posiNode = mc.createNode('pointOnSurfaceInfo',n=prefix+'_surfacePt_pointOnSurfaceInfo')
			mc.connectAttr(surface+'.worldSpace[0]',cposNode+'.inputSurface',f=True)
			mc.connectAttr(cposNode+'.parameterU',posiNode+'.parameterU',f=True)
			mc.connectAttr(cposNode+'.parameterV',posiNode+'.parameterV',f=True)
			
			# Calculate Offset
			offsetNode = mc.createNode('plusMinusAverage',n=prefix+'_surfaceOffset_plusMinusAverage')
			mc.setAttr(offsetNode+'.operation',2) # Subtract
			mc.connectAttr(vecProduct+'.output',offsetNode+'.input3D[0]',f=True)
			mc.connectAttr(cposNode+'.position',offsetNode+'.input3D[1]',f=True)
			
			# Offset * Normal (dotProduct)
			dotProduct = mc.createNode('vectorProduct',n=prefix+'_dotProduct_vectorProduct')
			mc.setAttr(dotProduct+'.operation',1) # Dot Product
			mc.connectAttr(offsetNode+'.ouput3D',dotProduct+'.input1',f=True)
			mc.connectAttr(posiNode+'.normal',dotProduct+'.input2',f=True)
			
			# Boundary Condition
			condition = mc.createNode('condition',n=prefix+'_condition')
			mc.setAttr(condition+'.operation',2) # Greater Than
			mc.connectAttr(dotProduct+'.outputX',condition+'.firstTerm',f=True)
			mc.connectAttr(vecProduct+'.output',condition+'.colorIfTrue',f=True)
			mc.connectAttr(cposNode+'.position',condition+'.colorIfFalse',f=True)
			
			# Connect to transform
			mc.connectAttr(condition+'.outColor',surfConnNode+'.t',f=True)
	
	else:
		
		# Point Constraint
		pntConn = mc.pointConstraint(obj,surfConnNode,n=prefix+'_pointConstraint')
	
	# =============================
	# - Constrain Orient (rotate) -
	# =============================
	
	if orient:
		
		# Normal Constraint
		normConn = mc.normalConstraint(surface,surfConnNode,aim=axisDict[normalAxis],u=axisDict[upAxis],wut=upMode,wu=upVector,wuo=upObject,n=prefix+'_normalConstraint')
	
	else:
		
		# Orient Constraint
		oriConn = mc.normalConstraint(obj,surfConnNode,n=prefix+'_orientConstraint')
	
	# =================
	# - Return Result -
	# =================
	
	return surfConnNode
Exemplo n.º 51
0
def completeAntenna(num_jnt,num_ctr,hairSystem,sliding,length,twist):
  lenComplist = len(completeList)
  for i in range(lenComplist):
     del completeList[0]
  num_crv = len(MakeAtna_returnV) 
  method = ''
  createJntLst = []
    
  #------------------ Get Hair System Type
  hairSys_on = 0
  if hairSystem == 'New':
      hairSys_on = 1
  elif hairSystem == '':
      hairSys_on = 0
  else:
      hairSys_on = -1
      
  for i in cmds.ls(type='hairSystem'):
      if hairSystem == i or hairSystem == cmds.listRelatives(i,p=1)[0]:
          hairSys_on = 2


  if hairSys_on == -1:
    cmds.warning("'%s'는 존제하지 않는 Object입니다." % hairSystem)
  else:      
    
    for i in MakeAtna_returnV: #------choose method
        if len(i) == 6:
            cmds.delete(i[5])#----delete expression
            method = 'avp'
        else:
            method = 'cv'

    getPosShp = 0.0
    if method == 'avp':
       print MakeAtna_returnV[0][0][1], len(MakeAtna_returnV[0][1])
       getPosShp = cmds.getAttr(MakeAtna_returnV[0][0][1]+'.posShp')/len(MakeAtna_returnV[0][1])
       print getPosShp
    
    for i in MakeAtna_returnV:
        aim = i[4][0]
        up = i[4][1]
        mainName = i[1][0].partition('_')[0]
        #--------Set controler joint initial setting 
        for j in i[1]:   
            cmds.setAttr(j+'.tx',l=0)
            cmds.setAttr(j+'.ty',l=0)
            cmds.setAttr(j+'.tz',l=0)
            cmds.setAttr(j+'.rx',l=0)
            cmds.setAttr(j+'.ry',l=0)
            cmds.setAttr(j+'.rz',l=0)
            cmds.setAttr(j+'.dla',0)

            if method == 'avp':
                cmds.deleteAttr(j,at='ip')
            cmds.parent(j,w=1)
            
        for j in i[2]: 
            cmds.delete(j)  #----------------- Delete null group
        
        #----------Set constrainted orient to current orientation    
        for j in range(len(i[1])-1): 
            tempLoc = cmds.spaceLocator()[0]
            tempOri = cmds.orientConstraint(i[1][j],tempLoc)
            cmds.delete(tempOri)
            tempAim = cmds.aimConstraint(i[1][j+1],i[1][j],aim=aim,u=up,wu=up,wut='objectrotation',wuo=tempLoc)
            cmds.delete(tempAim,tempLoc)
            cmds.parent(i[1][j+1],i[1][j])
        
        ##-------- BindCurve And JointCurve Set
        attachJointCurve ='' 
        bindCurve =''
        posShp = 0.0
        conJoint = i[1]
        if method == 'avp':
            dupleObj = cmds.duplicate(i[0][1],n=mainName+'_bindCurve')[0]
            cmds.deleteAttr(dupleObj+'.posShp')
            posShp = cmds.getAttr(i[0][1]+'.posShp')
            attachJointCurve = cmds.rebuildCurve( dupleObj, n=mainName+'_jntAtCurve', ch=1, rpo=0, rt=0 ,end=0, kr=0, kcp=1, kep=0, kt=0, s=0, d=3, tol=0.01 )[0]
            cmds.delete(i[0][0],i[0][1],i[0][2])
            bindCurve = dupleObj
        else:
            dupleObj = cmds.duplicate(i[0][0],n=mainName+'_bindCurve')[0]
            spans = cmds.getAttr(cmds.listRelatives(dupleObj,s=1)[0]+'.spans')
            attachJointCurve = cmds.rebuildCurve( dupleObj, n=mainName+'_jntAtCurve', ch=1, rpo=0, rt=0 ,end=1, kr=0, kcp=0, kep=0, kt=0,s=spans*3, tol=0.01 )[0]
            cmds.delete(i[0][1],i[0][0])
            bindCurve = dupleObj
            
        #--------------- Create Normal Base for Normal Constraint       
        normalBase = cmds.polyPlane(w=1,h=1,sx=1,sy=1,n=mainName+'_normalBase')[0]
        for j in range(1,len(i[1])-1):
            cmds.polyExtrudeEdge(normalBase+'.e['+str(j*3)+']',lty=1)
        cmds.DeleteHistory(normalBase)
        
        def inr(a):
            return (a+1)%3
        def inrb(a):
            return (a+2)%3
        
        axisElse = [0,0,0]  #--------- Get Third Axis
        
        for j in range(3):
            if aim[j] == 1 and up[inr(j)] == 1:
                axisElse[inrb(j)] = 1;
            if aim[j] == 1 and up[inr(j)] == 0:
                axisElse[inr(j)] = -1;
            if aim[j] == -1 and up[inr(j)] == 0:
                axisElse[inr(j)] = 1;
            if aim[j] == -1 and up[inr(j)] == 1:
                axisElse[inrb(j)] = -1;
            print j,inr(j),inrb(j)
        print 'aim     :',aim
        print 'up      :',up
        print 'axisElse:',axisElse

        for j in range(len(i[1])):
            tmLoc = cmds.spaceLocator()
            cmds.parent(tmLoc,conJoint[j])
            cmds.move(axisElse[0],axisElse[1],axisElse[2],tmLoc,ls=1)
            locPos = cmds.xform(tmLoc,q=1,ws=1,piv=1)
            cmds.move(locPos[0],locPos[1],locPos[2],normalBase+'.vtx['+str(j*2+1)+']',ws=1)
            cmds.move(-axisElse[0],-axisElse[1],-axisElse[2],tmLoc,ls=1)
            locPos = cmds.xform(tmLoc,q=1,ws=1,piv=1)
            cmds.move(locPos[0],locPos[1],locPos[2],normalBase+'.vtx['+str(j*2)+']',ws=1)
            cmds.delete(tmLoc)
       
        bindObj = []
        bindObj.append(conJoint[0])
        bindObj.append(normalBase)
        cmds.skinCluster(bindObj)
        bindObj = []
        bindObj.append(conJoint[0])
        bindObj.append(bindCurve)
        cmds.skinCluster(bindObj)
        cmds.setAttr(bindCurve+'.v', 0)
        
        cmds.select(attachJointCurve)
        startHair = ''
        currentHair = ''
        restHair = ''
        if hairSys_on != 0:
          if hairSys_on == 1:
            beforeHair = cmds.ls(type='hairSystem')      
            createHair('')
            afterHair = cmds.ls(type='hairSystem')
            for k in beforeHair:
                afterHair.remove(k)
            hairSystem = afterHair[0]
            hairSys_on = 2
          elif hairSys_on == 2:
            createHair(hairSystem)
          cmds.select(attachJointCurve); import maya.mel as mel ;mel.eval('setSelectedHairCurves "start" "rest"')
          cmds.select(attachJointCurve); mel.eval('convertHairSelection "currentCurves"'); currentHair = cmds.ls(sl=1)[0]
          mel.eval('convertHairSelection "restCurves"'); restHair = cmds.ls(sl=1)[0]
          mel.eval('convertHairSelection "startCurves"'); startHair = cmds.ls(sl=1)[0]; attachJointCurve = currentHair
          mel.eval('displayHairCurves "all" 1'); blendShape1 = cmds.blendShape(startHair,restHair,tc=0)[0]
          cmds.setAttr(blendShape1+'.'+startHair,1)
          
        #---------------- Create Current Joint    
        
        jntPntL = []; jntPntChildL = []; subLocL = []; jntL = []; jntGL = []
        infoL = []; pntInfoL = []; pntRotL = []
        if hairSys_on == 0:
          for j in range(num_jnt):
            cmds.select(d=1)
            jnt = cmds.joint(rad = 2, n=mainName+'_cuJoint'+str(j))
            cmds.setAttr(jnt+'.dla',1)
            cmds.addAttr(jnt,ln='infoPos',sn='ip',at='double',min=0,max=num_jnt-1,dv=j)
            cmds.setAttr(jnt+'.ip',e=1,k=1)
            jntG = cmds.group(jnt,n=jnt+'_p')
            info = cmds.createNode('pointOnCurveInfo', n=mainName+'_info'+str(j))
            subLoc = cmds.spaceLocator(n=mainName+'_subLoc'+str(j))[0]
            cmds.scale(.1,.1,.1,subLoc)
            subLocL.append(subLoc); jntL.append(jnt); jntGL.append(jntG); infoL.append(info)

            cmds.connectAttr(attachJointCurve+'.worldSpace[0]', info+'.inputCurve')
            cmds.pointConstraint(subLoc,jntG)
            normalCon = cmds.normalConstraint(normalBase,jntG,aim=up,u=aim,wut='vector')[0]
            cmds.connectAttr(info+'.tangent',normalCon+'.wu')
            cmds.connectAttr(info+'.position',subLoc+'.translate')
            prRt = 0; sRt = 0; editP = 0
            if posShp >= 0:
                sRt = posShp/num_jnt + 1
                editP = (j/float(num_jnt-1))**sRt
            else:
                sRt = 1-posShp/num_jnt
                editP = 1-abs(j/float(num_jnt-1)-1)**sRt
            import maya.mel as mel
            prRt = mel.eval( 'linstep(0,1,%s)' % editP ) * (num_jnt-1)
            cmds.setAttr(info+'.parameter', prRt/(num_jnt-1))
        else:
          for j in range(num_jnt):
            cmds.select(d=1)
            jnt = cmds.joint(rad = 2, n=mainName+'_cuJoint'+str(j))
            cmds.setAttr(jnt+'.dla',1)
            cmds.addAttr(jnt,ln='infoPos',sn='ip',at='double',min=0,max=num_jnt-1,dv=j)
            cmds.setAttr(jnt+'.ip',e=1,k=1)
            jntG = cmds.group(jnt,n=jnt+'_p')
            info = cmds.createNode('pointOnCurveInfo', n=mainName+'_info'+str(j))
            pntInfo = cmds.createNode('pointOnCurveInfo', n=mainName+'_pntInfo'+str(j))
            cmds.setAttr(info+'.top', 1)
            subLoc = cmds.spaceLocator(n=mainName+'_subLoc'+str(j))[0]; cmds.scale(.1,.1,.1,subLoc)
            jntPntChild = cmds.spaceLocator(n=mainName+'_pntChild'+str(j))[0]
            jntPnt = cmds.group(n=mainName+'_jntPnt'+str(j));
            pntRot= cmds.createNode('plusMinusAverage', n=mainName+'_pntRot'+str(j))
            cmds.connectAttr(jntPntChild+'.rotate', pntRot+'.input3D[0]')
            subLocL.append(subLoc); jntL.append(jnt); jntGL.append(jntG); infoL.append(info)
            jntPntChildL.append(jntPntChild); jntPntL.append(jntPnt); pntInfoL.append(pntInfo); pntRotL.append(pntRot)

            cmds.connectAttr(startHair+'.worldSpace[0]', pntInfo+'.inputCurve')
            cmds.connectAttr(attachJointCurve+'.worldSpace[0]', info+'.inputCurve')
            cmds.pointConstraint(subLoc,jntG)
            normalCon = cmds.normalConstraint(normalBase,jntPntChild,aim=up,u=aim,wut='vector')[0]
            cmds.connectAttr(pntInfo+'.tangent',normalCon+'.wu')
            cmds.connectAttr(info+'.position',subLoc+'.translate')
            cmds.connectAttr(pntInfo+'.position', jntPnt+'.translate')
            prRt = 0; sRt = 0; editP = 0
            if posShp >= 0:
                sRt = posShp/num_jnt + 1
                editP = (j/float(num_jnt-1))**sRt
            else:
                sRt = 1-posShp/num_jnt
                editP = 1-abs(j/float(num_jnt-1)-1)**sRt
            import maya.mel as mel
            prRt = mel.eval( 'linstep(0,1,%s)' % editP ) * (num_jnt-1)
            cmds.setAttr(info+'.parameter', prRt/(num_jnt-1))
            cmds.setAttr(pntInfo+'.parameter', prRt/(num_jnt-1))
            
          normalCon = cmds.normalConstraint(normalBase,jntGL[0],aim=up,u=aim,wut='vector')[0]
          jntPntNormalCon = cmds.normalConstraint(normalBase,jntPntL[0],aim=up,u=aim,wut='vector')[0]
          cmds.connectAttr(infoL[0]+'.tangent',normalCon+'.wu')
          cmds.connectAttr(pntInfoL[0]+'.tangent',jntPntNormalCon+'.wu')
          for j in range(1,num_jnt):
            cmds.tangentConstraint(attachJointCurve,jntGL[j],aim=aim,u=up,wu=up,wut='objectrotation',wuo=jntGL[j-1])
            cmds.tangentConstraint(startHair,jntPntL[j],aim=aim,u=up,wu=up,wut='objectrotation',wuo=jntPntL[j-1])
            
       
        if len(completeList) < len(jntL)*num_crv: completeList.extend(jntL) #------------- Out joint list
        
        #--------------- Grouping
        subLocG = cmds.group(subLocL,n=subLocL[0])
        deformGrp = cmds.group(attachJointCurve,bindCurve,normalBase,subLocG, n=mainName+'_deformGrp')
        cmds.setAttr(deformGrp+'.v', 0 )
        transformGrp = cmds.group(em=1, n=mainName+'_trGrp')
        parentCon = cmds.parentConstraint(conJoint[0],transformGrp )[0]
        cmds.delete(parentCon)
        cmds.parent(jntGL,conJoint[0],transformGrp)
          #------------ Grouping in hairSystem
        if hairSys_on != 0:
          print hairSystem
          jntPntG = cmds.group(jntPntL, n=mainName+'_jntPntG')
          cmds.parent(jntPntG,deformGrp)
        
        #-------------- Attribute Setting
        conJointFirst = conJoint[0]
        conJointSecond = conJoint[1]; cmds.setAttr(conJointSecond+'.template', 1)
        conJointFirst_sliding = conJointFirst + '.sliding'
        conJointFirst_length = conJointFirst + '.scale_length'
        
        if sliding == 1:
         cmds.addAttr(conJointFirst,ln='sliding',at='double')
         cmds.setAttr(conJointFirst_sliding,e=1,k=1)
        if length == 1:
         cmds.addAttr(conJointFirst,ln='scale_length',at='double',min=0,max=num_jnt,dv=num_jnt)
         cmds.setAttr(conJointFirst_length,e=1,k=1)
        
        #----------- Set Expression String   
        exString = 'float $ip[];\n\n'
        for k in range(num_jnt):
            exString += '$ip[%s] = %s/%s;\n' % (k, jntL[k]+'.infoPos',num_jnt-1)
        exString += '\n'
         
        if length == 1:
         exString += 'float $numJnt = %s;\n' % num_jnt
         exString += 'float $length = %s/%s;\n\n' % (conJointFirst_length, num_jnt)
        
        if sliding == 1:
         exString += 'float $ep[];\n'
         exString += 'float $sliding = %s;\n' % conJointFirst_sliding
         exString += 'float $sRate;\n\n'
         exString += 'if($sliding >= 0)\n{\n'
         exString += '$sRate=$sliding/%s+1;\n' % num_jnt
         for k in range(num_jnt):
             exString += '$ep[%s] = pow($ip[%s],$sRate);\n' % (k,k)
         exString += '}\nelse\n{\n'
         exString += '$sRate= 1 - $sliding/%s;\n' % num_jnt
         for k in range(num_jnt):
             exString += '$ep[%s] = 1-pow(1-$ip[%s],$sRate);\n' % (k,k)
         exString += '}\n\n'
         
        if length == 1 and sliding == 1:
         for k in range(num_jnt):
             exString += '%s.parameter = linstep(0,1,$ep[%s])*$length;\n' % (infoL[k], k)
        elif length == 1:
         for k in range(num_jnt):
             exString += '%s.parameter = $ip[%s]*$length;\n' % (infoL[k], k)
        elif sliding == 1:
         for k in range(num_jnt):
             exString += '%s.parameter = linstep(0,1,$ep[%s]);\n' % (infoL[k], k)
        else:
         for k in range(num_jnt):
             exString += '%s.parameter = $ip[%s];\n' % (infoL[k], k)
            
        cmds.expression(s=exString,n=mainName+'_ex') #--------- expression
        
        #-------------- Twist Attr Adding
        
        if hairSys_on != 0:
         if twist == 0:
           for j in range(num_jnt):
             cmds.connectAttr(pntRotL[j]+'.output3D', jntL[j]+'.jo')
             
        if twist == 1:
         cmds.addAttr(conJointFirst,ln='twist',at='double')
         cmds.setAttr(conJointFirst+'.twist',e=1,k=1)
         for j in range(num_jnt):
             cmds.addAttr(jntL[j],ln='twistDetail',at='double',dv=j/float(num_jnt-1)*10)
             cmds.setAttr(jntL[j]+'.twistDetail',e=1,k=1)
             twistMult = cmds.createNode('multiplyDivide',n= jntL[j]+'_twistMult')
             cmds.connectAttr(conJointFirst+'.twist', twistMult+'.input1X')
             cmds.connectAttr(jntL[j]+'.twistDetail', twistMult+'.input2X')
             rAxis = '.jo'
             if aim[0] == 1 or aim[0] == -1:rAxis += 'x'
             if aim[1] == 1 or aim[1] == -1:rAxis += 'y'
             if aim[2] == 1 or aim[2] == -1:rAxis += 'z'
             
             if hairSys_on == 0:
              cmds.connectAttr(twistMult+'.outputX', jntL[j]+rAxis)
             else:
              cmds.connectAttr(twistMult+'.outputX', pntRotL[j]+'.input3D[1].input3D%s' % (rAxis.replace('.jo','')) )
              cmds.connectAttr(pntRotL[j]+'.output3D', jntL[j]+'.jo')

        #-------------- Add Controler 
        ctrer = []; ctrGG = []; ctrSubLocG = []; getPosShp = ''
          
        curveSh = cmds.listRelatives(bindCurve,s=1)[0]
        exString_in =''
        for j in range(num_ctr):
            ctrer.append( cmds.circle(n=mainName+'_ctr'+str(j),normal=aim)[0] )
            cmds.addAttr( ctrer[j], ln='rollS', at='double', min=0,max=num_jnt,dv= num_jnt/2.0)
            cmds.setAttr( ctrer[j]+'.rollS', e=1,k=1)
            cmds.addAttr( ctrer[j], ln='rollE', at='double', min=0,max=num_jnt,dv=j*num_jnt/float(num_ctr))
            cmds.setAttr( ctrer[j]+'.rollE', e=1,k=1)
            ctrG = cmds.group( ctrer[j], n = mainName+'ctrG'+str(j) )
            info = cmds.createNode('pointOnCurveInfo', n=bindCurve+'_info'+str(j))
            cmds.setAttr(info+'.top',1)
            cmds.connectAttr( curveSh+'.worldSpace[0]', info+'.inputCurve')
            cmds.connectAttr( info+'.position', ctrG+'.translate')
            mult = cmds.createNode( 'multiplyDivide', n= mainName+'_ctr_posMult'+str(j) )
            cmds.connectAttr( ctrer[j]+'.rollE', mult+'.input1X')
            cmds.setAttr( mult+'.input2X', 1.0/len(conJoint) )
            cmds.connectAttr( mult+'.outputX',info+'.parameter' )
            subLoc = cmds.spaceLocator( n=mainName+'_ctr_subLoc'+str(j) )[0]
            cmds.connectAttr( info+'.position', subLoc+'.translate' )
            cmds.pointConstraint( subLoc, ctrG )
            normalCon = cmds.normalConstraint( normalBase,ctrG,aim=up,u=aim,wut='vector' )[0]
            cmds.connectAttr( info+'.tangent', normalCon+'.wu')
            
            ctrGG.append(ctrG); ctrSubLocG.append(subLoc)
        if len(ctrGG) != 0: cmds.parent(ctrGG,transformGrp)
        if len(ctrSubLocG) != 0: cmds.parent(ctrSubLocG,deformGrp)
        
        exString  = ''
        rotDirection = ''
        
        for j in range(3):
            if aim[j] == -1:
                rotDirection = '-1*'
            
        for j in range(len(ctrer)):
            exString += 'float $rollE%s = %s.rollE;\n' % (j, ctrer[j])
            exString += 'float $rollS%s = %s.rollS + $rollE%s;\n' % (j, ctrer[j], j)
            exString += 'int $irolE%s = $rollE%s;\n' % (j,j)
            exString += 'int $irolS%s = $rollS%s;\n' % (j,j)
            exString += 'float $rolev%s = $rollE%s - $irolE%s;\n' % (j,j,j)
            exString += 'float $rolsv%s = $rollS%s - $irolS%s;\n\n' % (j,j,j)
            exString += 'float $rx%s = %s%s.rotateX;\n' % (j, rotDirection, ctrer[j])
            exString += 'float $ry%s = %s%s.rotateY;\n' % (j, rotDirection, ctrer[j])
            exString += 'float $rz%s = %s%s.rotateZ;\n\n' % (j, rotDirection, ctrer[j])
            exString += 'float $outRate%s[];\n\n' % j
            exString += 'int $num_jnt%s = %s;\n\n' % (j,len(conJoint))
            exString += 'for($i = 0; $i < $num_jnt%s; $i++)\n{\n' % j
            exString += ' if($rollE%s > $i)\n   $outRate%s[$i] = 0;' % (j,j)
            exString += ' if($rollE%s > $i && $rollE%s < $i+1)\n   $outRate%s[$i] = 1-$rolev%s;\n' % (j,j,j,j)
            exString += ' if($rollE%s <= $i)\n   $outRate%s[$i] = 1;\n\n' % (j,j)
            exString += ' if($rollS%s > $i)\n   $outRate%s[$i] *= 1;\n' % (j,j)
            exString += ' if($rollS%s > $i && $rollS%s < $i+1)\n   $outRate%s[$i] *= $rolsv%s;\n' % (j,j,j,j)
            exString += ' if($rollS%s <= $i)\n   $outRate%s[$i] *= 0;\n}\n\n' % (j,j)
        
        rotList = ['rx','ry','rz']
        
        for rot in rotList:
          for j in range(len(conJoint)):
            ra = rot.replace('r','ra')
            exString += '%s.%s = ' % (conJoint[j],ra)
            for k in range(len(ctrer)):
              if k == len(ctrer)-1:
               exString += '%s*$outRate%s[%s]*$%s%s;\n' % (aim[0]+aim[1]+aim[2],k,j,rot,k)
              else:
               exString += '%s*$outRate%s[%s]*$%s%s+' % (aim[0]+aim[1]+aim[2],k,j,rot,k)
          exString+= '\n'
        
        if len(ctrer) != 0: cmds.expression(s=exString, name = mainName+'_ctrEx')
  cmds.select(cl=1)
Exemplo n.º 52
0
def alignToUV(targetObj="none", sourceObj="none", sourceU=0.0, sourceV=0.0, mainAxis="+z", secAxis="+x", UorV="v"):
	"""
	inputs should be 1. targetObj 2. sourceObj 3. sourceU 4. sourceV 5. mainAxis(lowerCase, + or -, i.e."-x" 8. secAxis (lowcase, + or -) 7, UorV ("u" or "v" for the direction along surface for the sec axis)
"""

	axisDict = {"+x":(1,0,0), "+y":(0,1,0), "+z":(0,0,1), "-x":(-1,0,0), "-y":(0,-1,0), "-z":(0,0,-1)}

	#Does this create a new node? no To create a node, use the flag "ch=True". That creates a pointOnSurface node
	pos = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, position=True)
	posVec = om.MVector(pos[0], pos[1], pos[2])
	cmds.xform(targetObj, ws=True, t=pos)

	#get tangent in the right direction (u or v), use this as up vector for normal constraint
	#oooorrrrrr be fancy and create a matrix for the axes to use from normal and tans
	tanV = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tv=True)
	tanU = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, tu=True)
	norm = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, nn=True)

	#decide where up axis is on normal constraint, u or v tangent
	if UorV == "v":
		wup = tanV
	elif UorV == "u":
		wup = tanU

	#create normal constraint
	nc = cmds.normalConstraint(sourceObj, targetObj, aimVector=axisDict[mainAxis], upVector=axisDict[secAxis], worldUpVector=(wup))
	cmds.delete(nc) #delete constraint

	#-------check that targetObj is a nurbsSurface (later figure out if it's a mesh or surface)

	# pos = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, position=True)
	# vPos = om.MVector(pos[0], pos[1], pos[2])

	# tanV = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, tv=True)
	# vTanV = om.MVector(tanV[0], tanV[1], tanV[2])

	# tanU = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, tu=True)
	# vTanU = om.MVector(tanU[0], tanU[1], tanU[2])

	# norm = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, nn=True)
	# vNorm = om.MVector(norm[0], norm[1], norm[2])

	# mat4x4 = om.MMatrix()

	# matSetRow(mat4x4, 0, vTanU)
	# matSetRow(mat4x4, 1, vNorm)
	# matSetRow(mat4x4, 2, vTanV)
	# matSetRow(mat4x4, 3, vPos)
	# matSetCell(mat4x4, 0, 3, 0)
	# matSetCell(mat4x4, 1, 3, 0)
	# matSetCell(mat4x4, 2, 3, 0)
	# matSetCell(mat4x4, 3, 3, 1)

	# mTrans = om.MTransformationMatrix(mat4x4)
	# mEuler = mTrans.eulerRotation()
	# mTranslate = mTrans.getTranslation("kWorld") #need to get MDagPath object for this

	# print "translation = %f, %f, %f"%(mTranslate
	# 	[0], mTranslate[1], mTranslate[2])

	# print "%f %f %f" % (radsToDegrees(mEuler[0]),
	# radsToDegrees(mEuler[1]), radsToDegrees(mEuler[2]))
Exemplo n.º 53
0
                            #attributes.doSetAttr(nameBuffer,'localScaleZ',(self.f_meshArea*.025))

                            if self.v_posOffset is not None and self.v_posOffset and nameBuffer and self.str_offsetMode and self._createMode not in ['follicle']:
                                mi_obj = cgmMeta.cgmObject(nameBuffer)
                                mc.move (pos[0],pos[1],pos[2], mi_obj.mNode,ws=True)	
                                if self.str_offsetMode =='vector':
                                    mi_hitLoc = cgmMeta.cgmObject(mc.spaceLocator(n='hitLoc')[0])
                                    mc.move (self.startPoint[0],self.startPoint[1],self.startPoint[2], mi_hitLoc.mNode,ws=True)				
                                    constBuffer = mc.aimConstraint(mi_hitLoc.mNode,mi_obj.mNode,
                                                                   aimVector=[0,0,1],
                                                                   upVector=[0,1,0],
                                                                   worldUpType = 'scene')
                                    mi_hitLoc.delete()
                                else:
                                    constBuffer = mc.normalConstraint(m,mi_obj.mNode,
                                                                      aimVector=[0,0,1],
                                                                      upVector=[0,1,0],
                                                                      worldUpType = 'scene')
                                try:mc.delete(constBuffer)
                                except:pass
                                try:mc.move(self.v_posOffset[0],self.v_posOffset[1],self.v_posOffset[2], [mi_obj.mNode], r=True, rpr = True, os = True, wd = True)
                                except StandardError,error:log.error("%s >>> Failed to move! | self.v_posOffset: %s | mi_obj: %s | error: %s"%(_str_funcName,self.v_posOffset,mi_obj,error))				
                                self._posBuffer[i] = mi_obj.getPosition()  
                                if not self.b_orientSnap:
                                    mi_obj.rotate = [0,0,0]
                                #mi_tmpLoc.delete()			    

                            break                              

                    if self.l_toCreate:#Name it
                        nameBuffer = mc.rename(nameBuffer,self.l_toCreate[len(self.l_return)])
Exemplo n.º 54
0
def constrainToSurface(surface, objects):
    for obj in objects:
        cmds.geometryConstraint( surface, obj )
        cmds.normalConstraint( surface, obj, aim=(0, 1, 0) )
Exemplo n.º 55
0
def addJntsOnSurfIntersection(surf1, surf2, jntsNum):
    '''
    Places jnts along intersection curve between surf1 and surf2
    naming convention based on surf1
    '''

    # intersect surfaces
    crvGrp, intNode = mc.intersect(surf1,
                                   surf2,
                                   fs=True,
                                   ch=True,
                                   o=True,
                                   cos=False)[:2]
    intNode = mc.rename(intNode, surf1 + '_ints')
    crvGrp = mc.rename(crvGrp, surf1 + '_ints_crv_grp')
    crv = mc.listRelatives(crvGrp, c=True)[0]
    crv = mc.rename(crv, surf1 + '_ints_crv')

    # rebuild curve to jntNum spans
    rbdCrv, rbdNode = mc.rebuildCurve(crv,
                                      ch=True,
                                      o=True,
                                      rpo=False,
                                      spans=jntsNum,
                                      rt=0,
                                      kr=2,
                                      n=crv + '_rbd_crv')
    rbdNode = mc.rename(rbdNode, crv + '_rbd')

    # offset curve to control size of eye hole
    offsetCrv, offsetNode = mc.offsetCurve(rbdCrv,
                                           ch=True,
                                           distance=0,
                                           o=True,
                                           ugn=0,
                                           n=crv + '_offset_crv')
    offsetNode = mc.rename(offsetNode, crv + '_offset')

    locs = []
    locName = '_'.join(surf1.split('_')[:2])
    # attach locators to intersection curve
    for locId in range(jntsNum):
        loc = mc.spaceLocator(n=locName + '_loc_%d' % locId)[0]
        rt.attachToMotionPath(offsetCrv, locId, loc, fm=False)
        mc.setAttr(loc + '.localScale', 0.05, 0.05, 0.05)
        locs.append(loc)

    # normal constraint to surf1
    for loc in locs:
        mc.normalConstraint(surf2, loc, aim=(1, 0, 0))

    jnts = []
    # add joints under locators
    for loc in locs:
        mc.select(cl=True)
        jnt = mc.joint(n=loc.replace('_loc_', '_jnt_'))
        rt.parentSnap(jnt, loc)
        mc.setAttr(jnt + '.jointOrient', 0, 0, 0)
        jnts.append(jnt)

    # groups
    grp = mc.group(crvGrp,
                   offsetCrv,
                   rbdCrv,
                   locs,
                   n=surf1 + '_intersect_loc_grp')

    # create offset attribute
    mc.addAttr(grp, ln='collideOffset', at='double', dv=0, k=True)
    offsetPlug = cn.create_multDoubleLinear(grp + '.collideOffset', -1)
    mc.connectAttr(offsetPlug, offsetNode + '.distance', f=True)

    # connect debug
    rt.connectVisibilityToggle(offsetCrv, grp, 'offsetCrv', False)
    rt.connectVisibilityToggle(rbdCrv, grp, 'rebuildCrv', False)
    rt.connectVisibilityToggle(crvGrp, grp, 'intersectCrv', False)
    rt.connectVisibilityToggle(locs, grp, 'crvLocs', False)
    rt.connectVisibilityToggle(jnts, grp, 'crvJnts', False)
Exemplo n.º 56
0
def alignToUV(targetObj="none",
              sourceObj="none",
              sourceU=0.0,
              sourceV=0.0,
              mainAxis="+z",
              secAxis="+x",
              UorV="v"):
    """
	inputs should be 1. targetObj 2. sourceObj 3. sourceU 4. sourceV 5. mainAxis(lowerCase, + or -, i.e."-x" 8. secAxis (lowcase, + or -) 7, UorV ("u" or "v" for the direction along surface for the sec axis)
"""

    axisDict = {
        "+x": (1, 0, 0),
        "+y": (0, 1, 0),
        "+z": (0, 0, 1),
        "-x": (-1, 0, 0),
        "-y": (0, -1, 0),
        "-z": (0, 0, -1)
    }

    #Does this create a new node? no To create a node, use the flag "ch=True". That creates a pointOnSurface node
    pos = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, position=True)
    posVec = om.MVector(pos[0], pos[1], pos[2])
    cmds.xform(targetObj, ws=True, t=pos)

    #get tangent in the right direction (u or v), use this as up vector for normal constraint
    #oooorrrrrr be fancy and create a matrix for the axes to use from normal and tans
    tanV = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tv=True)
    tanU = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, tu=True)
    norm = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, nn=True)

    #decide where up axis is on normal constraint, u or v tangent
    if UorV == "v":
        wup = tanV
    elif UorV == "u":
        wup = tanU

    #create normal constraint
    nc = cmds.normalConstraint(sourceObj,
                               targetObj,
                               aimVector=axisDict[mainAxis],
                               upVector=axisDict[secAxis],
                               worldUpVector=(wup))
    cmds.delete(nc)  #delete constraint

    #-------check that targetObj is a nurbsSurface (later figure out if it's a mesh or surface)

    # pos = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, position=True)
    # vPos = om.MVector(pos[0], pos[1], pos[2])

    # tanV = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, tv=True)
    # vTanV = om.MVector(tanV[0], tanV[1], tanV[2])

    # tanU = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, tu=True)
    # vTanU = om.MVector(tanU[0], tanU[1], tanU[2])

    # norm = cmds.pointOnSurface(targetObj, u=sourceU, v=sourceV, nn=True)
    # vNorm = om.MVector(norm[0], norm[1], norm[2])

    # mat4x4 = om.MMatrix()

    # matSetRow(mat4x4, 0, vTanU)
    # matSetRow(mat4x4, 1, vNorm)
    # matSetRow(mat4x4, 2, vTanV)
    # matSetRow(mat4x4, 3, vPos)
    # matSetCell(mat4x4, 0, 3, 0)
    # matSetCell(mat4x4, 1, 3, 0)
    # matSetCell(mat4x4, 2, 3, 0)
    # matSetCell(mat4x4, 3, 3, 1)

    # mTrans = om.MTransformationMatrix(mat4x4)
    # mEuler = mTrans.eulerRotation()
    # mTranslate = mTrans.getTranslation("kWorld") #need to get MDagPath object for this

    # print "translation = %f, %f, %f"%(mTranslate
    # 	[0], mTranslate[1], mTranslate[2])

    # print "%f %f %f" % (radsToDegrees(mEuler[0]),
    # radsToDegrees(mEuler[1]), radsToDegrees(mEuler[2]))
Exemplo n.º 57
0
    def generateComponents(self, src, componentType):
        """Generate objects at specified components"""

        check = mc.checkBox("%sCheck" % componentType, query=True, value=True)
        objType = mc.optionMenuGrp("%sItems" % componentType,
                                   query=True,
                                   value=True)
        instObj = mc.textField("%sInstObj" % componentType,
                               query=True,
                               text=True)
        orient = mc.checkBox("orient", query=True, value=True)
        keepOrig = mc.checkBox("keepOrig", query=True, value=True)
        radius = mc.floatSliderGrp("rad", query=True, value=True)
        divs = mc.intSliderGrp("div", query=True, value=True)

        if check:

            # Count the number of components (vertices, edges or faces)
            count = eval("mc.polyEvaluate(src, %s=True)" % componentType)
            #print "%s: %d" %(componentType, count)

            # Initialise progress bar and start clock
            mc.progressBar(self.gMainProgressBar,
                           edit=True,
                           beginProgress=True,
                           isInterruptable=True,
                           maxValue=count)  # Initialise progress bar
            startTime = time.time()

            # Create objects to instance (if applicable)
            if objType == "Sphere":
                obj = mc.polySphere(name="pSphere",
                                    radius=radius,
                                    subdivisionsX=divs,
                                    subdivisionsY=divs)
                mc.polySoftEdge(obj, angle=180, constructionHistory=False)
            elif objType == "Cylinder":
                obj = mc.polyCylinder(name="pCylinder",
                                      radius=radius,
                                      height=1,
                                      subdivisionsX=divs,
                                      subdivisionsY=1,
                                      subdivisionsZ=0)
                mc.polySoftEdge(obj, angle=90, constructionHistory=False)
                mc.xform(obj, t=[0, 0.5, 0], piv=[0, -0.5, 0])
                mc.makeIdentity(apply=True)
            elif objType == "Instance of...":
                obj = instObj

            statusMsg = "Creating %s for %d %s..." % (
                gps.pluralise(objType), count, gps.pluralise(componentType))

            # Loop through all the source object's components
            for i in range(count):

                # Progress bar
                if mc.progressBar(self.gMainProgressBar,
                                  query=True,
                                  isCancelled=True
                                  ):  # Cancel operation if esc key pressed
                    mc.progressBar(self.gMainProgressBar,
                                   edit=True,
                                   endProgress=True)  # Complete progress bar
                    gps.resetSelection(selLs)
                    mc.warning(
                        "Operation cancelled when partially completed. You may wish to undo."
                    )
                    return False
                else:
                    mc.progressBar(self.gMainProgressBar,
                                   edit=True,
                                   step=1,
                                   status=statusMsg)  # Increment progress bar

                if componentType == "vertex":
                    vtx = "%s.vtx[%d]" % (src, i)
                    pos = mc.pointPosition(vtx, world=True)
                elif componentType == "edge":
                    edge = mc.polyInfo("%s.e[%d]" % (src, i),
                                       edgeToVertex=True)
                    vtxs = edge[0].split()
                    vtx = "%s.vtx[%d]" % (src, int(vtxs[2]))
                    pos = mc.pointPosition(vtx, world=True)
                    vtx2 = "%s.vtx[%d]" % (src, int(vtxs[3]))
                    pos2 = mc.pointPosition(vtx2, world=True)
                elif componentType == "face":
                    edge = mc.polyInfo("%s.f[%d]" % (src, i),
                                       edgeToVertex=True)

                if objType == "Locator":
                    loc = mc.spaceLocator()
                elif objType == "Empty Group":
                    loc = mc.group(empty=True)
                else:
                    loc = mc.instance(obj)

                mc.xform(loc, a=True, t=pos)

                if orient:
                    if componentType == "vertex":
                        con = mc.normalConstraint(src,
                                                  loc,
                                                  weight=1,
                                                  aimVector=[0, 1, 0],
                                                  upVector=[0, 1, 0],
                                                  worldUpType="vector",
                                                  worldUpVector=[0, 1, 0])
                        mc.delete(con)
                    elif componentType == "edge":
                        edgeLen = gps.distanceBetween(pos, pos2)
                        mc.xform(loc, s=[1, edgeLen, 1])
                        loc2 = mc.spaceLocator()
                        mc.xform(loc2, t=pos2)
                        con = mc.aimConstraint(loc2,
                                               loc,
                                               weight=1,
                                               aimVector=[0, 1, 0],
                                               upVector=[0, 1, 0],
                                               worldUpType="vector",
                                               worldUpVector=[0, 1, 0])
                        mc.delete(con, loc2)

            if not keepOrig:
                mc.delete(obj)

            # Complete progress bar and print completion message
            mc.progressBar(self.gMainProgressBar, edit=True,
                           endProgress=True)  # Complete progress bar
            totalTime = time.time() - startTime
            print "Created %d %s in %f seconds.\n" % (
                count, gps.pluralise(objType), totalTime)
            return True