Esempio n. 1
0
def ResetSkinCluster(*args, **kwargs):
    selection = cmds.ls(sl=True)

    for obj in selection:
        skinCluster = mel.eval('findRelatedSkinCluster ' + obj)

        if not skinCluster:
            return

        nInf = len(
            cmds.listConnections('%s.matrix' % skinCluster, destination=False))

        for idx in range(nInf):
            slotNJoint = cmds.listConnections('%s.matrix[ %d ]' %
                                              (skinCluster, idx),
                                              destination=False)

            if slotNJoint is not None:
                matrixAsStr = cmds.getAttr('%s.worldInverseMatrix' %
                                           slotNJoint[0])
                cmds.setAttr('%s.bindPreMatrix[ %d ]' % (skinCluster, idx),
                             matrixAsStr,
                             type="matrix")

                for dPose in cmds.listConnections(
                        skinCluster, d=False, type='dagPose') or []:
                    cmds.dagPose(slotNJoint[0], reset=True, n=dPose)
Esempio n. 2
0
	def getAxis(self):
		if self.axis!=0:
			return self.axis
		if "opposite" in self.__dict__:
		
			if 'bindPose' not in self.__dict__:
				self.bindPose= mc.dagPose(self.Muscle,q=True,bp=True)[0]
			if 'root' not in self.__dict__:
				self.root=mc.dagPose( self.bindPose, q=True, m=True )[0]
			
			offset=mc.xform(self.root,q=True,rp=True,ws=True)
			
			center=mc.objectCenter(self.muscleShape)
			opposite=mc.objectCenter(self.opposite.muscleShape)
			
			greatestDistance=-1
			axisID=-1
			
			for i in range(0,3):
				distance=abs((center[i]-offset[i])-(opposite[i]-offset[i]))
				if(distance>greatestDistance):
					   greatestDistance=distance
					   axisID=i
					   
			self.axis=axisID+1
			
			return self.axis
		else:
			return 0
Esempio n. 3
0
def addInfluences(skinCluster, influences):
    """
    Add influences to the skin cluster. Expects full path influences. Will
    try to reach the bind pose before attached the new influences to the skin
    cluster.

    :param str skinCluster:
    :param list influences:
    """
    # get existing influences
    existing = cmds.skinCluster(skinCluster, query=True, influence=True)
    existing = cmds.ls(existing, l=True)
    
    # try restoring dagpose
    try:    cmds.dagPose(existing, restore=True, g=True, bindPose=True)
    except: cmds.warning("Unable to reach dagPose!")
    
    # add influences
    for influence in influences:
        if not influence in existing:
            cmds.skinCluster(
                skinCluster, 
                edit=True, 
                addInfluence=influence, 
                weight=0.0
            )
Esempio n. 4
0
def resetSkinCluster(skin):
    '''
    Bakes the current pose of the skeleton into the skinCluster - ie whatever
    the current pose is becomes the bindpose
    '''
    #nInf = len( cmds.listConnections( '%s.matrix' % skin, destination=False ) )
    Inf = cmds.skinCluster(skin, q=True, inf=True)
    nInf = len(Inf)
    slotNJoint = []

    for n in range(nInf):
        x = '%s.matrix[ %d ]' % (skin, n)

        jnt = cmds.listConnections(x, destination=False)

        if jnt is not None:
            slotNJoint = jnt[0]
            matrixAsStr = ' '.join(
                map(str, cmds.getAttr('%s.worldInverseMatrix' % slotNJoint)))
            melStr = 'setAttr -type "matrix" %s.bindPreMatrix[ %d ] %s' % (
                skin, n, matrixAsStr)
            maya.mel.eval(melStr)
            newPose = cmds.listConnections(skin, d=False, type='dagPose')

            if newPose is not None:
                for dPose in newPose:
                    cmds.dagPose(slotNJoint, reset=True, n=dPose)
	def saveJoint(self, jointName, parentIndex):
		
		#print jointName
		thisJoint = NewJoint()
		mc.currentTime(mc.playbackOptions(q=True, ast=True))
		selList = MSelectionList() 
		selList.add(jointName)
		mc.select(jointName)
		mypose = mc.dagPose( q=True, bindPose=True )
		mc.dagPose( mypose[0] , restore=True )
		mDagPath = MDagPath() 
		selList.getDagPath(0, mDagPath)
		transformFunc = MFnTransform(mDagPath)
		mTransformMtx = transformFunc.transformation()
		jointRotq = mTransformMtx.rotation()
		jointRote = mTransformMtx.eulerRotation()
		scaleUtil = MScriptUtil()
		scaleUtil.createFromList([0,0,0],3)
		scaleVec = scaleUtil.asDoublePtr()
		mTransformMtx.getScale(scaleVec,MSpace.kWorld)
		jointScale = [_round8(MScriptUtil.getDoubleArrayItem(scaleVec,i)) for i in range(0,3)]
		absJointPos = mc.xform(jointName,q=1,ws=1,rp=1)
		if parentIndex != -1:
			parentJointPos = mc.xform(self.bones[parentIndex].name,q=1,ws=1,rp=1)
		else:
			parentJointPos = [0,0,0]
		jointPos = [absJointPos[0]-parentJointPos[0],absJointPos[1]-parentJointPos[1],absJointPos[2]-parentJointPos[2]]
		thisJoint.parent = parentIndex
		thisJoint.name = jointName
		thisJoint.pos = [_round8(jointPos[0]),_round8(jointPos[1]),_round8(jointPos[2])]
		thisJoint.scl = jointScale
		thisJoint.rotq = [_round8(jointRotq.x), _round8(jointRotq.y), _round8(jointRotq.z), _round8(jointRotq.w)]
		thisJoint.rot = [_round8(jointRote.x), _round8(jointRote.y), _round8(jointRote.z)]
		#print thisJoint.pos
		self.bones.append(thisJoint)
 def createCopyAndBlendShape(
     self,
     obj,
     descrip='_FORDEFORMER',
     suf='_NBS'
 ):  #crea el duplicado y luego lo adiere al original mediante un blendshape
     if not cmds.objExists(str(obj) + descrip):
         if self.existNode(
                 obj,
                 'skinCluster'):  #Solo si tiene un skin hace el bindPose
             #Coloco el objeto a copiar en el origen
             bindPose = cmds.dagPose(str(obj), q=True, bindPose=True)[0]
             cmds.dagPose(bindPose, restore=True)
         #Duplica el objeto para trabajarlo
         copy = cmds.duplicate(obj, n=obj + descrip)[0]
         nbs = str(obj) + suf
         #Crea blendshape si no existe lo agrega
         if cmds.objExists(str(obj) + suf):
             try:
                 waithBsh = cmds.blendShape(obj + suf, q=True, wc=True)
                 nbs = cmds.blendShape(
                     obj + suf,
                     edit=True,
                     target=[obj, waithBsh + 1,
                             str(copy), 1.0])[0]
             except:
                 pass
         else:
             nbs = cmds.blendShape([copy, obj], n=obj + suf)[0]
         return copy, nbs
     else:
         cmds.warning('Ya existe el deformador ' + obj + descrip)
Esempio n. 7
0
 def bindPoseFn(self):
     if self.currentSkin:
         bp = cmds.listConnections(self.currentSkin + '.bindPose', s=1)
         if len(bp) > 0: cmds.dagPose(bp[0], r=1)
         else: cmds.warning('Multiple bind poses detected: ' + str(bp))
     else:
         cmds.warning(
             'No skin cluster loaded or mesh with skin cluster selected.')
    def saveJoint(self, jointName, parentIndex):

        #print jointName
        thisJoint = NewJoint()
        mc.currentTime(mc.playbackOptions(q=True, ast=True))
        selList = MSelectionList()
        selList.add(jointName)
        mc.select(jointName)
        mypose = mc.dagPose(q=True, bindPose=True)
        mc.dagPose(mypose[0], restore=True)
        mDagPath = MDagPath()
        selList.getDagPath(0, mDagPath)
        transformFunc = MFnTransform(mDagPath)
        mTransformMtx = transformFunc.transformation()
        jointRotq = mTransformMtx.rotation()
        jointRote = mTransformMtx.eulerRotation()
        scaleUtil = MScriptUtil()
        scaleUtil.createFromList([0, 0, 0], 3)
        scaleVec = scaleUtil.asDoublePtr()
        mTransformMtx.getScale(scaleVec, MSpace.kWorld)
        jointScale = [
            _round8(MScriptUtil.getDoubleArrayItem(scaleVec, i))
            for i in range(0, 3)
        ]
        absJointPos = mc.xform(jointName, q=1, ws=1, rp=1)
        if parentIndex != -1:
            parentJointPos = mc.xform(self.bones[parentIndex].name,
                                      q=1,
                                      ws=1,
                                      rp=1)
        else:
            parentJointPos = [0, 0, 0]
        jointPos = [
            absJointPos[0] - parentJointPos[0],
            absJointPos[1] - parentJointPos[1],
            absJointPos[2] - parentJointPos[2]
        ]
        thisJoint.parent = parentIndex
        thisJoint.name = jointName
        thisJoint.pos = [
            _round8(jointPos[0]),
            _round8(jointPos[1]),
            _round8(jointPos[2])
        ]
        thisJoint.scl = jointScale
        thisJoint.rotq = [
            _round8(jointRotq.x),
            _round8(jointRotq.y),
            _round8(jointRotq.z),
            _round8(jointRotq.w)
        ]
        thisJoint.rot = [
            _round8(jointRote.x),
            _round8(jointRote.y),
            _round8(jointRote.z)
        ]
        #print thisJoint.pos
        self.bones.append(thisJoint)
Esempio n. 9
0
	def build(self, agentOptions):
		MayaAgent.MayaAgent.build(self, agentOptions)
		
		self._buildCharacterSet()
		self._applyActions()
		
		if self._zeroPose:
			mc.dagPose( self._zeroPose, restore=True )
			
		self.setupDisplayLayers()
Esempio n. 10
0
    def build(self, agentOptions):
        MayaAgent.MayaAgent.build(self, agentOptions)

        self._buildCharacterSet()
        self._applyActions()

        if self._zeroPose:
            mc.dagPose(self._zeroPose, restore=True)

        self.setupDisplayLayers()
Esempio n. 11
0
def restore_dag_pose(influences=()):
    """
    restores the dag pose from the influences given.
    :param influences: <list> the influence objects to acting on the skin cluster.
    :return: <bool> True for success. <bool> False for failure.
    """
    try:
        cmds.dagPose(influences, restore=True, g=True, bindPose=True)
    except RuntimeError:
        return False
    return True
Esempio n. 12
0
	def _applyActions(self):
		# The rotation order needed to build the skeleton does not apply
		# to the animation - it is assumed to be xyz
		#
		for mayaJoint in self.mayaJoints.values():
			mc.setAttr("%s.rotateOrder" % mayaJoint.name, MayaAgent.kRotateOrder2Enum['xyz'])

		for action in self.agentSpec().actions.values():
	 		mc.dagPose(self._zeroPose, restore=True)
	 		self._applyOffsets()
	 		mayaAction = MayaAction( self, action )
	 		self.actions[action.name] = mayaAction
	 		mayaAction.build()
Esempio n. 13
0
    def _applyActions(self):
        # The rotation order needed to build the skeleton does not apply
        # to the animation - it is assumed to be xyz
        #
        for mayaJoint in self.mayaJoints.values():
            mc.setAttr("%s.rotateOrder" % mayaJoint.name,
                       MayaAgent.kRotateOrder2Enum['xyz'])

        for action in self.agentSpec().actions.values():
            mc.dagPose(self._zeroPose, restore=True)
            self._applyOffsets()
            mayaAction = MayaAction(self, action)
            self.actions[action.name] = mayaAction
            mayaAction.build()
Esempio n. 14
0
def main():

    sel = mc.ls(sl=True)

    for each in sel:
        shapes = mc.listRelatives(each, shapes=True)

        for shape in shapes:
            #get skin cluster
            history = mc.listHistory(shape,
                                     groupLevels=True,
                                     pruneDagObjects=True)
            skins = mc.ls(history, type='skinCluster')

            for skin in skins:
                joints = mc.skinCluster(skin, query=True, influence=True)

                mc.setAttr(skin + '.envelope', 0)
                mc.skinCluster(skin, edit=True, unbindKeepHistory=True)

                #delete bindPose
                dagPose = mc.dagPose(each, query=True, bindPose=True)
                if dagPose:
                    mc.delete(dagPose)
                dagPose = mc.listConnections(skin + '.bindPose',
                                             d=False,
                                             type='dagPose')
                if dagPose:
                    mc.delete(dagPose)

                mc.skinCluster(joints, shape, toSelectedBones=True)
                mc.setAttr(skin + '.envelope', 1)
    if sel:
        mc.select(sel)
    def testSkelMissingJointFromDagPose(self):
        """
        Check that dagPoses that don't contain all desired joints issue an
        appropriate warning
        """
        mayaFile = os.path.join(self.inputPath, "UsdExportSkeletonTest", "UsdExportSkeletonBindPoseMissingJoints.ma")
        cmds.file(mayaFile, force=True, open=True)

        usdFile = os.path.abspath('UsdExportBindPoseMissingJointsTest.usda')

        joints = cmds.listRelatives('joint_grp', allDescendents=True, type='joint')
        bindMembers = cmds.dagPose('dagPose1', q=1, members=1)
        nonBindJoints = [j for j in joints if j not in bindMembers]
        self.assertEqual(nonBindJoints, [u'joint4'])

        delegate = UsdUtils.CoalescingDiagnosticDelegate()

        cmds.select('joint_grp')
        cmds.mayaUSDExport(mergeTransformAndShape=True, file=usdFile, shadingMode='none',
                           exportSkels='auto', selection=True)

        messages = delegate.TakeUncoalescedDiagnostics()
        warnings = [x.commentary for x in messages if x.diagnosticCode == Tf.TF_DIAGNOSTIC_WARNING_TYPE]
        missingJointWarnings = [x for x in warnings if 'is not a member of dagPose' in x]
        self.assertEqual(len(missingJointWarnings), 1)
        self.assertIn("Node 'joint4' is not a member of dagPose 'dagPose1'",
                      missingJointWarnings[0])
Esempio n. 16
0
    def _setBindPose(self):
        # The bind pose is stored in frame 1
        if not self.agentSpec().bindPoseData:
            return

        for jointSim in self.agentSpec().bindPoseData.joints():
            mayaJoint = self.mayaJoint(jointSim.name())

            # AMC describes object space transformations
            #
            mc.move(jointSim.sample("tx", jointSim.startFrame()),
                    jointSim.sample("ty", jointSim.startFrame()),
                    jointSim.sample("tz", jointSim.startFrame()),
                    mayaJoint.name,
                    objectSpace=True,
                    relative=True)
            mc.xform(mayaJoint.name,
                     rotation=(jointSim.sample("rx", jointSim.startFrame()),
                               jointSim.sample("ry", jointSim.startFrame()),
                               jointSim.sample("rz", jointSim.startFrame())),
                     objectSpace=True,
                     relative=True)

        self._bindPose = mc.dagPose(self.rootJoint.name,
                                    save=True,
                                    bindPose=True,
                                    name=(self.name() + "Bind"))
Esempio n. 17
0
def goToDagPose(*args,**keywords):
	
	bindPose=False
	
	shortNames={'bp':'bindPose'}

	for k in keywords:
		if k in locals():
			exec(k+'=keywords[k]')
		if k in shortNames:
			exec(shortNames[k]+'=keywords[k]')

	sel=[]
	if len(args)==0:
		sel=mc.ls(sl=True)
		
	for a in args:
		if isIterable(a):
			sel.extend(a)
		else:
			sel.append(a)

	if len(iterable(mc.ls(sel,type='dagPose')))==0 or bindPose:
		sel=removeDuplicates(mc.dagPose(mc.listConnections(mc.ls(mc.listHistory(sel)),type='transform'),q=True,bp=True))
		
	if len(sel)==0: return

	mel.eval('DisableAll')
		
	success=True
	err=True
	
	for i in range(0,10):
		try: 
			mc.dagPose(sel[0],r=True)
			err=False
			break
		except:
			err=True
			
	mel.eval('EnableAll')
		
	if err and len(iterable(mc.dagPose(q=True,ap=True))):
		success=False

	if success: return sel[0]
	else: return
 def gotoBindPose(self):
     try:
         joints = mc.ls(type='joint')
         topJoints = []
         for thisjoint in joints:
             while mc.listRelatives(thisjoint, p=True):
                 parent = mc.listRelatives(thisjoint, p=True)
                 thisjoint = parent[0]
             topJoints.append(thisjoint)
         topJoints = set(topJoints)
         for topJoint in topJoints:
             mc.select(topJoint)
             mypose = mc.dagPose(q=True, bindPose=True)
             mc.dagPose(mypose[0], restore=True)
             mc.select(cl=True)
     except:
         print 'cannot go to bind pose'
Esempio n. 19
0
 def resetSkinPose(self):
     for obj in cmds.ls(sl=1):
         clusterName = mel.eval('findRelatedSkinCluster("%s")' % obj)
         if not clusterName:
             return
         sk_matrix = clusterName + '.matrix'
         mx_num = cmds.getAttr(sk_matrix, mi=1)
         infs = cmds.listConnections(sk_matrix, s=1, d=0, scn=1)
         if not infs:
             return
         for n in mx_num:
             inf = cmds.listConnections('%s[%d]' % (sk_matrix, n), s=1, d=0, scn=1)
             if not inf:
                 continue
             matrix = cmds.getAttr('%s.worldInverseMatrix[0]' % inf[0])
             cmds.setAttr('%s.pm[%d]' % (clusterName, n), matrix, typ='matrix')
             cmds.dagPose(inf[0], rs=1, n=cmds.listConnections('%s.bp' % clusterName, s=1, d=0, scn=1)[0])
Esempio n. 20
0
	def goToPose(self,*args,**keywords):
		
		if not 'bp' in keywords:
			bp=False
		
		success=False
		err=False
		
		mel.eval("DisableAll")
				
		if(len(args)>0):
			for pose in args:
				if(mc.nodeType(pose)=='dagPose'):
					for i in range(0,10): #( glitch workaround )
						err=False
						try:
							mc.dagPose(pose,r=True)
							err=False
						except:
							err=True
		else:
			if(bp==True or len(keywords)>0):
				for i in range(0,10): #( glitch workaround )
					err=False
					try:
						mc.dagPose(self.root,r=True,bp=True)
						err=False
					except:
						err=True
			if(len(keywords)>0):
				for j in keywords:
					if(mc.objExists(j)):
						for i in range(0,10):
							try:
								mc.setAttr(j,keywords[j])
								err=False
							except:
								err=True
					else:
						err=True
				
		mel.eval("EnableAll")
		
		if(err==False): success=True
		
		return success
	def gotoBindPose(self):
		try:
			joints = mc.ls(type='joint')
			topJoints = []
			for thisjoint in joints:
				while mc.listRelatives(thisjoint, p=True):
					parent = mc.listRelatives(thisjoint, p=True)
					thisjoint = parent[0]
				topJoints.append(thisjoint)
			topJoints = set(topJoints)
			for topJoint in topJoints:
				mc.select(topJoint)
				mypose = mc.dagPose( q=True, bindPose=True )
				mc.dagPose( mypose[0] , restore=True )	
				mc.select(cl=True)
		except:
			print 'cannot go to bind pose'
Esempio n. 22
0
	def addAutoFlex(self,mirror=True,pose={},**keywords):
		"Adds an auto-flex pose from the current pose or a dictionary of attribute/value pairs."
				
		self.bindPose= mc.dagPose(self.Muscle,q=True,bp=True)[0]
		self.root=mc.dagPose(self.bindPose, q=True, m=True )[0]
		startPose=mc.dagPose(self.root,s=True)#store current pose
		
		plug=mel.eval('zenFirstOpenPlug("'+self.Handle+'.zenAutoFlex")')
		verified=False
		attributes={}
		poses=[]
		success=True
				
		offBindPoseJointCount=0
		dp=mc.dagPose(self.bindPose,q=True,ap=True)
		if isIterable(dp):
			offBindPoseJointCount=len(dp)
		
		if(offBindPoseJointCount>0 and len(pose)==0): #create an auto-flex pose from the current position
			command='rigZenMuscleAddAutoFlex("'+self.Handle+'",'+str(int(mirror))+')'
			plug=mel.eval(command)
		elif(len(pose)>0):
			success=self.goToPose(**pose)
			if(success):
				try:
					plug=mel.eval('rigZenMuscleAddAutoFlex("'+self.Handle+'",'+str(int(mirror)*self.getAxis())+')')
				except:
					success=False#raise Warning('Could not add auto flex pose for '+self.Muscle)
			
		if success:
			for k in keywords:
				attr='zenAutoFlex['+str(plug)+'].'+str(k)
				conn=mc.listConnections((self.Handle+'.'+attr),s=True,d=False,p=True)
				if isIterable(conn) and len(conn)>0 and mc.ls(conn[0],o=True)[0]==mc.ls((self.Handle+'.'+attr),o=True)[0]:
					attr=conn[0].split('.')[-1]
				attributes[str(attr)]=keywords[k]
			self.setAttributes(**attributes)
			success=self.goToPose(startPose)		
		else:
			self.goToPose(startPose)

		mc.delete(startPose)
		
		return success
Esempio n. 23
0
def GotoBindPose(*args):
    joints = cmds.ls(type='joint')
    rootJoints = []

    for j in joints:
        while cmds.listRelatives(j, p=True):
            parent = cmds.listRelatives(j, p=True)
            j = parent[0]
        rootJoints.append(j)

    rootJoints = set(rootJoints)

    for rootJoint in rootJoints:
        cmds.select(rootJoint)
        bindpose = cmds.dagPose(q=True, bindPose=True)
        cmds.dagPose(bindpose[0], restore=True)
        cmds.select(cl=True)

    return
Esempio n. 24
0
def revertJointToBindPose(*args):
    selected = getSelected()
    if selected:
        conn = cmds.listConnections('{}.bindPose'.format(selected[0]))
        root = getJointRoot(selected[0])
        allJoints = [root] + getAllJointChildren(root)
        jointData = {}

        for joint in allJoints:
            jointData[joint] = getJointAttributes(joint)

        cmds.dagPose(conn, restore=True)

        skip = ['radius', 'type', 'side']

        for joint, jointDict in jointData.items():
            for attr, value in jointDict.items():
                if joint not in selected:
                    if attr not in skip:
                        cmds.setAttr('{}.{}'.format(joint, attr), value)
    return
Esempio n. 25
0
    def deactivate_move_joints_mode(self):
        for module in self.rig_modules:
            for joint in module.deform_joints:
                plugs = cmds.listConnections(joint + ".worldInverseMatrix[0]",
                                             type="skinCluster",
                                             plugs=True)
                if not plugs:
                    continue
                for plug in plugs:
                    regex = re.match("(.*)\.bindPreMatrix\[([0-9]*)\]", plug)
                    node, index = regex.groups()
                    cmds.disconnectAttr(
                        joint + ".worldInverseMatrix[0]",
                        node + ".bindPreMatrix[{}]".format(index),
                    )
                    mat = cmds.getAttr(joint + ".worldInverseMatrix[0]")
                    cmds.setAttr(node + ".bindPreMatrix[{}]".format(index),
                                 mat,
                                 type="matrix")

                bind_poses = cmds.dagPose(joint, bindPose=True, q=True)
                for bind_pose in bind_poses:
                    cmds.dagPose(joint, reset=True, n=bind_pose)
Esempio n. 26
0
def getBindPoses(*args):
	
	sel=[]
	if len(args)==0:
		sel=iterable(mc.ls(sl=True))
		
	for a in args:
		sel.extend(iterable(a))
		
	if len(sel)==0: return
	
	trs=iterable(mc.listConnections(iterable(mc.ls(mc.listHistory(sel))),type='transform'))+sel

	return removeDuplicates(mc.dagPose(trs,q=True,bp=True))
def copy_proxy_to_skin(src_mesh=None, dst_mesh=None):
    """Copy skinning information from source (proxy) to destination mesh

    :param src_mesh: Source mesh
    :param dst_mesh: Destination Mesh
    :return: New skinCluster
    """

    # Test for selection
    if not src_mesh or not dst_mesh:
        meshes = cmds.ls(sl=1)
        if len(meshes) == 2:
            src_mesh = meshes[0]
            dst_mesh = meshes[1]
        else:
            raise RuntimeError("You need to have TWO meshes selected!")

    # Get source skinCluster
    src_skin = cmds.ls(cmds.listHistory(src_mesh), type='skinCluster')
    if not src_skin:
        raise RuntimeError("{} does not have a skinCluster".format(src_skin))

    # Check destination skinCluster
    dst_skin = cmds.ls(cmds.listHistory(dst_mesh), type='skinCluster')

    # Save current pose
    influence_list = cmds.skinCluster(src_skin, q=True, wi=True)
    cur_pose = cmds.dagPose(influence_list, save=True, name='skinToPose')

    # Go to bind pose before copying weights
    bind_pose = cmds.dagPose(influence_list, q=True, bindPose=True)
    if bind_pose:
        cmds.dagPose(bind_pose[0], restore=True)

    # Build destination skinCluster
    if not dst_skin:
        dst_prefix = dst_mesh.split(':')[-1]
        src_influence_list = cmds.skinCluster(src_skin[0], q=True, inf=True)
        dst_skin = cmds.skinCluster(src_influence_list,
                                    dst_mesh,
                                    toSelectedBones=True,
                                    rui=False,
                                    n=dst_prefix + '_skinCluster')

    # Copy skin weights
    cmds.copySkinWeights(sourceSkin=str(src_skin[0]),
                         destinationSkin=str(dst_skin[0]),
                         surfaceAssociation='closestPoint',
                         influenceAssociation='name',
                         noMirror=True)

    cmds.dagPose(cur_pose, restore=True)
    cmds.delete(cur_pose)
    cmds.select(cl=1)

    # Return result
    return dst_skin
Esempio n. 28
0
def create_skeleton_bind_pose(asset_name, skeleton_top_node):
    """Creates a single skeleton bind pose for rig in scene

    create_skeleton_bind_pose('Kayah', 'skeleton')
    """
    # Delete existing dagPoses
    dag_poses = cmds.ls(type='dagPose')
    if dag_poses: cmds.delete(dag_poses)

    # Add new bind pose
    jnts = cmds.listRelatives(skeleton_top_node, ad=True, type='joint')
    if jnts:
        cmds.select(jnts)
        bind_pose = cmds.dagPose(name='{}_bindPose'.format(asset_name),
                                 bindPose=True,
                                 save=True)
        return bind_pose
def cleanupBindPoseForSlaveJoints(slaveJoints=[], slaveRoot=None):
    bindPoseNodes = set()
    for slaveJoint in slaveJoints:
        if cmds.objExists(slaveJoint):
            curBindPoseNodes = cmds.listConnections(slaveJoint, t='dagPose')

            if curBindPoseNodes:
                for curBindPoseNode in curBindPoseNodes:
                    bindPoseNodes.add(curBindPoseNode)

    for bindPoseNode in bindPoseNodes:
        if cmds.objExists(bindPoseNode):
            print('Remove old bind pose node: ' + bindPoseNode)
            cmds.delete(bindPoseNode)

    if slaveRoot:
        res = cmds.dagPose(slaveRoot, save=True, name='bindPose')
        print('New bind pose node created: ' + res)
Esempio n. 30
0
    def addDagPose(self, obj, *args):
        
        # weightedInfluence で 0 以外のウェイトを持つインフルエンスオブジェクト
        # (ジョイント/トランスフォーム)の文字列を取得
        try:
            self.allInfluences = cmds.skinCluster(q = True, weightedInfluence = True)

        except Exception:
            # オブジェクトタイプをチェック
            self.typeCheck(obj)
            print( u" Info: Current selecting object is not a deformer. ")	

        if(len(relatives) == 0):
            print( u" Info:" + obj + " has not exists in current object.")
            return 1

        else:
            dagpose = cmds.dagPose(obj, bp = True, save = True)
            cmds.textScrollList(self.textScllist, e = True , append = dagpose)
            self.dagPoseNodes.append(dagpose)  
Esempio n. 31
0
    def build(self, options):
        self._buildSkeleton()

        if options.loadGeometry:
            self._buildGeometry(options.skinType, options.loadMaterials,
                                options.materialType)

        # Make sure the agent scale doesn't also scale the translate values of
        # the sim data. We have to freeze the transform here since we won't
        # be allowed to after binding the skin
        #
        self._freezeAgentScale()

        if options.loadPrimitives:
            self._buildPrimitives(options.instancePrimitives)

        if options.loadGeometry:
            self._setBindPose()
            self._bindSkin(options.skinType)

        # Has to happen after skin is bound
        self._scaleJoints()
        self._zeroPose = mc.dagPose(self.rootJoint.name,
                                    save=True,
                                    name=(self.name() + "Zero"))

        agentGroup = self.agentGroup()
        mc.addAttr(agentGroup, longName='msvCdlFile', dataType='string')
        mc.setAttr("%s.msvCdlFile" % agentGroup,
                   self._agent.agentSpec.cdlFile,
                   type='string')
        mc.addAttr(agentGroup, longName='msvBindPoseFile', dataType='string')
        mc.setAttr("%s.msvBindPoseFile" % agentGroup,
                   self._agent.agentSpec.bindPoseFile,
                   type='string')
        mc.addAttr(agentGroup, longName='msvAgentType', dataType='string')
        mc.setAttr("%s.msvAgentType" % agentGroup,
                   self._agent.agentSpec.agentType,
                   type='string')
        mc.addAttr(agentGroup, longName='msvScaleVar', dataType='string')
        mc.setAttr("%s.msvScaleVar" % agentGroup,
                   self._agent.agentSpec.scaleVar,
                   type='string')
        for (key, value) in self._agent.agentSpec.leftovers.items():
            attrName = 'msv%sLeftovers' % key
            mc.addAttr(agentGroup, longName=attrName, dataType='string')
            mc.setAttr("%s.%s" % (agentGroup, attrName), value, type='string')
        cdlStructure = " ".join(self._agent.agentSpec.cdlStructure)
        mc.addAttr(agentGroup, longName="msvCdlStructure", dataType='string')
        mc.setAttr("%s.msvCdlStructure" % agentGroup,
                   cdlStructure,
                   type='string')

        # Add the variable descriptions to a multi-compound attribute
        mc.addAttr(agentGroup,
                   longName='msvVariables',
                   attributeType='compound',
                   numberOfChildren=5,
                   multi=True)
        mc.addAttr(agentGroup,
                   longName='msvVarName',
                   dataType='string',
                   parent='msvVariables')
        mc.addAttr(agentGroup,
                   longName='msvVarDefault',
                   attributeType='float',
                   parent='msvVariables')
        mc.addAttr(agentGroup,
                   longName='msvVarMin',
                   attributeType='float',
                   parent='msvVariables')
        mc.addAttr(agentGroup,
                   longName='msvVarMax',
                   attributeType='float',
                   parent='msvVariables')
        mc.addAttr(agentGroup,
                   longName='msvVarExpression',
                   dataType='string',
                   parent='msvVariables')
        values = [
            '"%s"' % v.name for v in self._agent.agentSpec.variables.values()
        ]
        MayaUtil.setMultiAttr("%s.msvVariables" % agentGroup, values,
                              "msvVarName", "string")
        values = [v.default for v in self._agent.agentSpec.variables.values()]
        MayaUtil.setMultiAttr("%s.msvVariables" % agentGroup, values,
                              "msvVarDefault")
        values = [v.min for v in self._agent.agentSpec.variables.values()]
        MayaUtil.setMultiAttr("%s.msvVariables" % agentGroup, values,
                              "msvVarMin")
        values = [v.max for v in self._agent.agentSpec.variables.values()]
        MayaUtil.setMultiAttr("%s.msvVariables" % agentGroup, values,
                              "msvVarMax")
        values = [
            '"%s"' % v.expression
            for v in self._agent.agentSpec.variables.values()
        ]
        MayaUtil.setMultiAttr("%s.msvVariables" % agentGroup, values,
                              "msvVarExpression", "string")
Esempio n. 32
0
def dagPose(*args, **kwargs):
    res = cmds.dagPose(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    return res
Esempio n. 33
0
	def create(self):

		worldMatrixNode=mc.createNode('fourByFourMatrix')
		wm=\
		[
			[1,0,0,0],
			[0,1,0,0],
			[0,0,1,0],
			[0,0,0,1]
		]
		for a in range(0,4):
			for b in range(0,4):
				mc.setAttr( worldMatrixNode+'.in'+str(a)+str(b), wm[a][b] )

		self.worldMatrix=worldMatrixNode+'.o'

		wsMatrices=[]

		cleanup=[]

		lattices=[]
		uvPos=[]
		antipodes=[]

		cpos=mc.createNode('closestPointOnSurface')

		if 'surfaceAttr' not in self.__dict__ or len(self.surfaceAttr)==0 and len(self.edges)>0:
			mc.select(self.edges)
			rebuildNode,surfaceNodeTr=mel.eval('zenLoftBetweenEdgeLoopPathRings(2)')[:2]
			self.surfaceAttr=rebuildNode+'.outputSurface'

			children=mc.listRelatives(surfaceNodeTr,c=True,s=True,ni=True,type='nurbsSurface')
			if isIterable(children) and len(children)>0:
				self.uSpans=mc.getAttr(children[0]+'.spansU')
				self.vSpans=mc.getAttr(children[0]+'.spansV')

			mc.disconnectAttr(self.surfaceAttr,surfaceNodeTr+'.create')
			mc.delete(surfaceNodeTr)


		if self.uSpans<0 or self.vSpans<0:
			tempTr=mc.createNode('transform')
			tempCurve=mc.createNode('nurbsCurve',p=tempTr)
			mc.connectAttr(self.surfaceAttr,tempCurve+'.create')
			self.uSpans=mc.getAttr(tempCurve+'.spansU')
			self.vSpans=mc.getAttr(tempCurve+'.spansV')
			mc.disconnectAttr(self.surfaceAttr,tempCurve+'.create')
			mc.delete(tempTr)

		orderedTrs=[]
		orderedCtrls=[]

		if self.distribute not in ['u','v']: #calculate the axis of distribution
			if len(self.trs)!=0:
				mc.connectAttr(self.surfaceAttr,cpos+'.inputSurface')
				uMin=100
				vMin=100
				uMax=0
				vMax=0
				uPosList=[]
				vPosList=[]

				for i in range(0,self.number):

					orderedTrs.append('')
					orderedCtrls.append('')
					t=self.trs[i]

					if mc.objExists(t): # find the closest point
						if self.hasGeometry:
							center=mc.objectCenter(t)
							mc.setAttr(cpos+'.ip',*center)
							posCenter,uCenter,vCenter=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

						rp=mc.xform(t,ws=True,q=True,rp=True)
						mc.setAttr(cpos+'.ip',*rp)
						posRP,uRP,vRP=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

						# see which is closer - object center or rotate pivot
						if self.hasGeometry:
							distCenter=distanceBetween(posCenter,center)
							distRP=distanceBetween(posRP,rp)

						if self.hasGeometry==False or abs(distCenter)>abs(distRP) :
							uPosList.append(uRP)
							vPosList.append(vRP)
							if uRP<uMin: uMin=uRP
							if uRP>uMax: uMax=uRP
							if vRP<vMin: vMin=vRP
							if vRP>vMax: vMax=vRP
						else:
							uPosList.append(uCenter)
							vPosList.append(vCenter)
							if uCenter<uMin: uMin=uCenter
							if uCenter>uMax: uMax=uCenter
							if vCenter<vMin: vMin=vCenter
							if vCenter>vMax: vMax=vCenter

			cfsi=mc.createNode('curveFromSurfaceIso')

			mc.connectAttr(self.surfaceAttr,cfsi+'.is')
			mc.setAttr(cfsi+'.idr',0)
			mc.setAttr(cfsi+'.iv',.5)
			mc.setAttr(cfsi+'.r',True)
			mc.setAttr(cfsi+'.rv',True)

			if len(self.trs)!=0:
				mc.setAttr(cfsi+'.min',uMin)
				mc.setAttr(cfsi+'.max',uMax)

			ci=mc.createNode('curveInfo')
			mc.connectAttr(cfsi+'.oc',ci+'.ic')
			uLength=mc.getAttr(ci+'.al')

			mc.setAttr(cfsi+'.idr',1)

			if len(self.trs)!=0:
				mc.setAttr(cfsi+'.min',vMin)
				mc.setAttr(cfsi+'.max',vMax)

			vLength=mc.getAttr(ci+'.al')

			mc.delete(cfsi,ci)

			if uLength>vLength:
				self.distribute='u'

				if len(self.trs)!=0:
					searchList=uPosList
					orderedList=uPosList[:]
					orderedList.sort()
			else:
				self.distribute='v'

				if len(self.trs)!=0:
					searchList=vPosList
					orderedList=vPosList[:]
					orderedList.sort()

			reverseTrs=False

			orderIDList=[]
			for n in range(0,self.number):
				s=searchList[n]
				for i in range(0,self.number):
					if s==orderedList[i] and i not in orderIDList:
						orderIDList.append(i)
						orderedTrs[i]=self.trs[n]
						orderedCtrls[i]=self.ctrls[n]
						if n==0 and i>len(self.trs)/2:
							reverseTrs=True
						break

			if reverseTrs:
				orderedTrs.reverse()
				self.trs=orderedTrs
				orderedCtrls.reverse()
				self.ctrls=orderedCtrls
			else:
				self.trs=orderedTrs
				self.ctrls=orderedCtrls

		if self.rebuild: # interactive rebuild, maintains even parameterization over the rivet surface, use with caution

			if self.distribute=='u':
				self.surfaceAttr=mel.eval('zenUniformSurfaceRebuild("'+self.surfaceAttr+'",'+str(self.uSpans*2)+',-1)')+'.outputSurface'
			else:
				self.surfaceAttr=mel.eval('zenUniformSurfaceRebuild("'+self.surfaceAttr+'",-1,'+str(self.vSpans*2)+')')+'.outputSurface'

		if not mc.isConnected(self.surfaceAttr,cpos+'.inputSurface'):
			mc.connectAttr(self.surfaceAttr,cpos+'.inputSurface',f=True)

		if self.taper=='distance' or self.createAimCurve or self.closestPoint=='geometry': # find the closest points ( and antipodes )

			for i in range(0,self.number):
				t=self.trs[i]
				cp=ClosestPoints(self.surfaceAttr,t)
				self.ClosestPoints.append(cp)

				if self.taper=='distance' or self.createAimCurve: # antipodes are used for lattice allignment and curve calculations
					antipodes.append(cp.getAntipodes(1))

		if self.taper!='none' or self.scale!='none': # measures scale with scaling

			cfsiLength=mc.createNode('curveFromSurfaceIso')
			ciLength=mc.createNode('curveInfo')
			lengthMultiplierNode=mc.createNode('multDoubleLinear')

			mc.setAttr(cfsiLength+'.relative',True)
			mc.setAttr(cfsiLength+'.relativeValue',True)

			if self.distribute=='u':
				mc.setAttr(cfsiLength+'.isoparmDirection',0)
			else:
				mc.setAttr(cfsiLength+'.isoparmDirection',1)

			mc.setAttr(cfsiLength+'.minValue',0)
			mc.setAttr(cfsiLength+'.maxValue',1)

			mc.setAttr(cfsiLength+".isoparmValue",.5)

			mc.connectAttr(self.surfaceAttr,cfsiLength+'.inputSurface')

			if mc.objExists(self.spaceTr):

				lengthCurve=mc.createNode('nurbsCurve',p=self.spaceTr)
				lengthCurveTG=mc.createNode('transformGeometry')

				mc.connectAttr(self.spaceTr+'.worldMatrix[0]',lengthCurveTG+'.txf')
				mc.connectAttr(cfsiLength+'.outputCurve',lengthCurveTG+'.ig')
				mc.connectAttr(lengthCurveTG+'.og',lengthCurve+'.create')
				mc.connectAttr(lengthCurve+'.worldSpace',ciLength+'.inputCurve')
				mc.setAttr(lengthCurve+'.intermediateObject',True)

				cleanup.extend([lengthCurveTG,cfsiLength])

			else:

				mc.connectAttr(cfsiLength+'.outputCurve',ciLength+'.inputCurve')

			mc.connectAttr(ciLength+'.al',lengthMultiplierNode+'.i1')
			mc.setAttr(lengthMultiplierNode+'.i2',1.0/float(mc.getAttr(ciLength+'.al')))

			lengthMultiplier=lengthMultiplierNode+'.o'


		uvPos=[]
		closestDistanceToCenter=Decimal('infinity')
		centerMostRivetID=0
		closestDistancesToCenter=[Decimal('infinity'),Decimal('infinity')]
		centerMostRivetIDs=[0,0]

		uvMultipliers=[]
		aimGroups=[]

		for i in range(0,self.number):

			pTrs=mc.listRelatives(self.trs[i],p=True)
			parentTr=''
			if len(iterable(pTrs))>0:
				parentTr=pTrs[0]

			t=self.trs[i]
			c=self.ctrls[i]
			r=mc.createNode('transform',n='Rivet#')

			wsMatrices.append(mc.xform(t,q=True,ws=True,m=True))

			if self.constraint: mc.setAttr(r+'.inheritsTransform',False)

			if not mc.objExists(c):
				c=t
				if not mc.objExists(t):
					c=r

			if not mc.objExists(c+'.zenRivet'):
				mc.addAttr(c,at='message',ln='zenRivet',sn='zriv')

			mc.connectAttr(r+'.message',c+'.zriv',f=True)

			if not mc.objExists(c+'.uPos'):
				mc.addAttr(c,k=True,at='double',ln='uPos',dv=50)
			if not mc.objExists(c+'.vPos'):
				mc.addAttr(c,k=True,at='double',ln='vPos',dv=50)

			if self.closestPoint=='geometry':
				up,vp=self.ClosestPoints[i].uvs[0]
			else:
				if mc.objExists(t):
					if self.hasGeometry:
						center=mc.objectCenter(t)
						mc.setAttr(cpos+'.ip',*center)
						posCenter,uCenter,vCenter=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

					rp=mc.xform(t,ws=True,q=True,rp=True)
					mc.setAttr(cpos+'.ip',*rp)
					posRP,uRP,vRP=mc.getAttr(cpos+'.p')[0],mc.getAttr(cpos+'.u'),mc.getAttr(cpos+'.v')

					if self.hasGeometry:
						distCenter=distanceBetween(posCenter,center)
						distRP=distanceBetween(posRP,rp)

					if self.hasGeometry==False or abs(distCenter)>abs(distRP):
						up=uRP
						vp=vRP
					else:
						up=uCenter
						vp=vCenter

				elif len(distribute)>0:

					if self.distribute=='u':
						up=(i+1)/self.number
						vp=.5
					else:
						up=.5
						vp=(i+1)/self.number

			if up>float(self.uSpans)-.01: up=float(self.uSpans)-.01
			if vp>float(self.vSpans)-.01: vp=float(self.vSpans)-.01
			if up<.01: up=.01
			if vp<.01: vp=.01

			uvPos.append((up,vp))

			if up<.5 and self.distribute=='u' and Decimal(str(abs(.5-up)))<Decimal(str(closestDistancesToCenter[0])):
				closestDistancesToCenter[0]=abs(.5-up)
				centerMostRivetIDs[0]=i

			if up>.5 and self.distribute=='u' and Decimal(str(abs(.5-up)))<Decimal(str(closestDistancesToCenter[1])):
				closestDistancesToCenter[1]=abs(.5-up)
				centerMostRivetIDs[1]=i

			if up<.5 and self.distribute=='v' and Decimal(str(abs(.5-vp)))<Decimal(str(closestDistancesToCenter[0])):
				closestDistancesToCenter[0]=abs(.5-vp)
				centerMostRivetIDs[0]=i

			if up>.5 and self.distribute=='v' and Decimal(str(abs(.5-vp)))<Decimal(str(closestDistancesToCenter[1])):
				closestDistancesToCenter[1]=abs(.5-vp)
				centerMostRivetIDs[1]=i

			mc.setAttr(c+'.uPos',up*100)
			mc.setAttr(c+'.vPos',vp*100)

			posi=mc.createNode('pointOnSurfaceInfo')
			mc.setAttr((posi+".caching"),True)
			#mc.setAttr((posi+".top"),True)

			multiplyU=mc.createNode('multDoubleLinear')
			mc.connectAttr(c+".uPos",multiplyU+".i1")
			mc.setAttr(multiplyU+'.i2',.01)
			multiplyV=mc.createNode('multDoubleLinear')
			mc.connectAttr(c+".vPos",multiplyV+".i1")
			mc.setAttr(multiplyV+'.i2',.01)

			uvMultipliers.append([multiplyU,multiplyV])

			mc.connectAttr(self.surfaceAttr,posi+".inputSurface");
			mc.connectAttr(multiplyU+".o",posi+".parameterU")
			mc.connectAttr(multiplyV+".o",posi+".parameterV")

			dm=mc.createNode('decomposeMatrix')
			mc.setAttr(dm+'.caching',True)
			fbfm=mc.createNode('fourByFourMatrix')
			mc.setAttr(fbfm+'.caching',True)

			mc.connectAttr(posi+'.nnx',fbfm+'.in00')
			mc.connectAttr(posi+'.nny',fbfm+'.in01')
			mc.connectAttr(posi+'.nnz',fbfm+'.in02')
			mc.connectAttr(posi+'.nux',fbfm+'.in10')
			mc.connectAttr(posi+'.nuy',fbfm+'.in11')
			mc.connectAttr(posi+'.nuz',fbfm+'.in12')
			mc.connectAttr(posi+'.nvx',fbfm+'.in20')
			mc.connectAttr(posi+'.nvy',fbfm+'.in21')
			mc.connectAttr(posi+'.nvz',fbfm+'.in22')
			mc.connectAttr(posi+'.px',fbfm+'.in30')
			mc.connectAttr(posi+'.py',fbfm+'.in31')
			mc.connectAttr(posi+'.pz',fbfm+'.in32')

			if self.constraint:# and not self.parent:
				mc.connectAttr(fbfm+'.output',dm+'.inputMatrix')
			else:
				multMatrix=mc.createNode('multMatrix')
				mc.connectAttr(r+'.parentInverseMatrix',multMatrix+'.i[1]')
				mc.connectAttr(fbfm+'.output',multMatrix+'.i[0]')
				mc.connectAttr(multMatrix+'.o',dm+'.inputMatrix')

			mc.connectAttr(dm+'.outputTranslate',r+'.t')
			mc.connectAttr(dm+'.outputRotate',r+'.r')

			if t!=r:

				if self.createAimCurve:
					aimGroup=mc.createNode('transform',n='rivetAimGrp#')
					mc.parent(aimGroup,t,r=True)
					mc.parent(aimGroup,r)
					if self.keepPivot or self.closestPoint=='pivot':
						mc.xform(aimGroup,ws=True,piv=mc.xform(t,q=True,ws=True,rp=True))
					else:
						mc.xform(aimGroup,ws=True,piv=self.ClosestPoints[i][1])
					self.aimGroups.append(aimGroup)

				if self.constraint:

					if self.parent: # parent and constraint == ParentSpace

						self.parentSpaces.append(ParentSpace(t,r))
						pc=self.parentSpaces[i].parentConstraint

						sc=self.parentSpaces[i].scaleConstraint

						skip=['x']
						if\
						(
							(self.distribute=='v' and 'length' in self.scaleDirection) or
							(self.distribute=='u' and 'width' in self.scaleDirection) or
							t in self.skipScaleObjects
						):
							skip.append('y')
						if\
						(
							(self.distribute=='u' and 'length' in self.scaleDirection) or
							(self.distribute=='v' and 'width' in self.scaleDirection) or
							t in self.skipScaleObjects
						):
							skip.append('z')

						mc.scaleConstraint(sc,e=True,sk=skip)

						if t in self.skipRotateObjects:
							mc.parentConstraint(pc,e=True,sr=('x','y','z'))
						if t in self.skipTranslateObjects:
							mc.parentConstraint(pc,e=True,st=('x','y','z'))

					else: #just constraint

						if t in self.skipRotateObjects:
							pc=mc.parentConstraint(r,t,sr=('x','y','z'),mo=True)[0]#
						if t in self.skipTranslateObjects:
							pc=mc.parentConstraint(r,t,st=('x','y','z'),mo=self.mo)[0]
						if t not in self.skipRotateObjects and t not in self.skipTranslateObjects:
							pc=mc.parentConstraint(r,t,mo=self.mo)[0]



					pcTargets=mc.parentConstraint(pc,q=True,tl=True)

					pcIDs=[]

					nsc=listNodeConnections(r,pc,s=False,d=True)

					for n in range(0,len(nsc)):
						if len(nsc[n])==2 and mc.objExists(nsc[n][-1]):
							pcID=getIDs(nsc[n][-1])
							if isinstance(pcID,int):
								pcIDs.append(pcID)

					pcIDs=removeDuplicates(pcIDs)

					for pcID in pcIDs:
						mc.connectAttr(self.worldMatrix,pc+'.tg['+str(pcID)+'].tpm',f=True)
						mc.connectAttr(dm+'.outputTranslate',pc+'.tg['+str(pcID)+'].tt',f=True)
						mc.connectAttr(dm+'.outputRotate',pc+'.tg['+str(pcID)+'].tr',f=True)

					cleanup.append(r)

					if self.parent:

						scTargets=mc.scaleConstraint(sc,q=True,tl=True)

						scIDs=[]

						nsc=listNodeConnections(r,sc,s=False,d=True)

						for n in range(0,len(nsc)):
							if len(nsc[n])==2 and mc.objExists(nsc[n][-1]):
								scIDs.append(getIDs(nsc[n][-1]))

						scIDs=removeDuplicates(scIDs)

						scMD=mc.createNode('multiplyDivide')
						mc.setAttr(scMD+'.i1',1,1,1)
						mc.setAttr(scMD+'.i2',1,1,1)

						for scID in scIDs:

							mc.connectAttr(self.worldMatrix,sc+'.tg['+str(scID)+'].tpm',f=True)
							#mc.connectAttr(scMD+'.o',sc+'.tg['+str(scID)+'].ts',f=True)
							mc.connectAttr(scMD+'.ox',sc+'.tg['+str(scID)+'].tsx',f=True)
							mc.connectAttr(scMD+'.oy',sc+'.tg['+str(scID)+'].tsy',f=True)
							mc.connectAttr(scMD+'.oz',sc+'.tg['+str(scID)+'].tsz',f=True)

						r=self.parentSpaces[i][0]
						#xfm=mc.xform(r,q=True,ws=True,m=True)
						#mc.setAttr(r+'.inheritsTransform',False)
						#mc.xform(r,m=xfm)
						#mc.connectAttr(self.surfaceMatrix,multMatrix+'.i[1]',f=True)#self.parentSpaces[i][0]+'.parentInverseMatrix'

				elif self.createAimCurve:
					mc.parent(t,w=True)
					mc.setAttr(t+'.inheritsTransform',False)
					mc.parent(t,r,r=True)
				else:
					mc.parent(t,r)

				if mc.objExists(parentTr) and (self.parent or self.createAimCurve) and not self.constraint:

					if not (parentTr in iterable(mc.listRelatives(r,p=True))):

						if mc.getAttr(r+'.inheritsTransform')==True:
							mc.parent(r,parentTr,r=True)
						else:
							mc.parent(r,parentTr)

					if mc.getAttr(r+'.inheritsTransform')==False:

						dm=mc.createNode('decomposeMatrix')
						mc.connectAttr(parentTr+'.worldMatrix',dm+'.inputMatrix')
						mc.connectAttr(dm+'.os',t+'.s',f=True)

			if self.taper!='none' or self.scale!='none':

				cfsiU=mc.createNode('curveFromSurfaceIso')

				mc.setAttr(cfsiU+'.relative',True)
				mc.setAttr(cfsiU+'.relativeValue',True)
				mc.setAttr(cfsiU+'.isoparmDirection',0)
				mc.setAttr(cfsiU+'.minValue',0)
				mc.setAttr(cfsiU+'.maxValue',1)

				mc.connectAttr(multiplyV+".o",cfsiU+".isoparmValue")
				mc.connectAttr(self.surfaceAttr,cfsiU+'.inputSurface')

				cfsiV=mc.createNode('curveFromSurfaceIso')

				mc.setAttr(cfsiV+'.relative',True)
				mc.setAttr(cfsiV+'.relativeValue',True)
				mc.setAttr(cfsiV+'.isoparmDirection',1)
				mc.setAttr(cfsiV+'.minValue',0)
				mc.setAttr(cfsiV+'.maxValue',1)

				mc.connectAttr(multiplyV+".o",cfsiV+".isoparmValue")
				mc.connectAttr(self.surfaceAttr,cfsiV+'.inputSurface')

				subtractNode=mc.createNode('addDoubleLinear')
				mc.setAttr(subtractNode+'.i1',-(1/(self.number*2)))
				addNode=mc.createNode('addDoubleLinear')
				mc.setAttr(addNode+'.i1',1/(self.number*2))
				addSubClampNode=mc.createNode('clamp')
				mc.setAttr(addSubClampNode+'.min',0,0,0)
				mc.setAttr(addSubClampNode+'.max',1,1,1)
				mc.connectAttr(subtractNode+'.o',addSubClampNode+'.inputR')
				mc.connectAttr(addNode+'.o',addSubClampNode+'.inputG')

				if self.distribute=='u':
					mc.connectAttr(multiplyU+".o",subtractNode+".i2")
					mc.connectAttr(multiplyU+".o",addNode+".i2")
					mc.connectAttr(addSubClampNode+'.outputR',cfsiU+'.minValue')
					mc.connectAttr(addSubClampNode+'.outputG',cfsiU+'.maxValue')
				else:
					mc.connectAttr(multiplyV+".o",subtractNode+".i2")
					mc.connectAttr(multiplyV+".o",addNode+".i2")
					mc.connectAttr(addSubClampNode+'.outputR',cfsiV+'.minValue')
					mc.connectAttr(addSubClampNode+'.outputG',cfsiV+'.maxValue')

				ciU=mc.createNode('curveInfo')
				mc.connectAttr(cfsiU+'.outputCurve',ciU+'.inputCurve')

				ciV=mc.createNode('curveInfo')
				mc.connectAttr(cfsiV+'.outputCurve',ciV+'.inputCurve')

				mdlU=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciU+'.al',mdlU+'.i1')
				mc.setAttr(mdlU+'.i2',1/float(mc.getAttr(ciU+'.al')))

				mdlV=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciV+'.al',mdlV+'.i1')
				mc.setAttr(mdlV+'.i2',1/float(mc.getAttr(ciV+'.al')))

				if not mc.objExists(c+'.minScaleWidth'): mc.addAttr(c,ln='minScaleWidth',at='double',k=True,min=0,dv=self.minScaleWidth)
				if not mc.objExists(c+'.maxScaleWidth'): mc.addAttr(c,ln='maxScaleWidth',at='double',k=True,min=0,dv=self.maxScaleWidth)
				if not mc.objExists(c+'.minScaleLength'): mc.addAttr(c,ln='minScaleLength',at='double',k=True,min=0,dv=self.minScaleLength)
				if not mc.objExists(c+'.maxScaleLength'): mc.addAttr(c,ln='maxScaleLength',at='double',k=True,min=0,dv=self.maxScaleLength)

				clampNode=mc.createNode('clamp')

				minScaleLengthNode=mc.createNode('multDoubleLinear')
				maxScaleLengthNode=mc.createNode('multDoubleLinear')
				minScaleWidthNode=mc.createNode('multDoubleLinear')
				maxScaleWidthNode=mc.createNode('multDoubleLinear')

				mc.connectAttr(c+'.minScaleLength',minScaleLengthNode+'.i1')
				mc.connectAttr(lengthMultiplier,minScaleLengthNode+'.i2')

				mc.connectAttr(c+'.maxScaleLength',maxScaleLengthNode+'.i1')
				mc.connectAttr(lengthMultiplier,maxScaleLengthNode+'.i2')

				mc.connectAttr(c+'.minScaleWidth',minScaleWidthNode+'.i1')
				mc.connectAttr(lengthMultiplier,minScaleWidthNode+'.i2')

				mc.connectAttr(c+'.maxScaleWidth',maxScaleWidthNode+'.i1')
				mc.connectAttr(lengthMultiplier,maxScaleWidthNode+'.i2')

				if self.distribute=='u':
					mc.connectAttr(minScaleLengthNode+'.o',clampNode+'.minR')
					mc.connectAttr(maxScaleLengthNode+'.o',clampNode+'.maxR')
					mc.connectAttr(minScaleWidthNode+'.o',clampNode+'.minG')
					mc.connectAttr(maxScaleWidthNode+'.o',clampNode+'.maxG')
				else:
					mc.connectAttr(minScaleWidthNode+'.o',clampNode+'.minR')
					mc.connectAttr(maxScaleWidthNode+'.o',clampNode+'.maxR')
					mc.connectAttr(minScaleLengthNode+'.o',clampNode+'.minG')
					mc.connectAttr(maxScaleLengthNode+'.o',clampNode+'.maxG')

				mc.connectAttr(mdlU+'.o',clampNode+'.ipr')
				mc.connectAttr(mdlV+'.o',clampNode+'.ipg')

				if self.scale=='relative' and self.parent:#or len(self.scaleDirection)<2:#

					if\
					(
						(self.distribute=='u' and 'length' in self.scaleDirection) or
						(self.distribute=='v' and 'width' in self.scaleDirection)
					):
						if self.constraint:
							mc.connectAttr(clampNode+'.opr',scMD+'.i1y')
						else:
							mc.connectAttr(clampNode+'.opr',r+'.sy',f=True)
					if\
					(
						(self.distribute=='v' and 'length' in self.scaleDirection) or
						(self.distribute=='u' and 'width' in self.scaleDirection)
					):
						if self.constraint:
							mc.connectAttr(clampNode+'.opg',scMD+'.i1z')
						else:
							mc.connectAttr(clampNode+'.opg',r+'.sz',f=True)


				elif self.taper!='none' and self.parent:

					#self.autoFlexGroups

					mc.setAttr(t+'.sx',lock=True)
					mc.setAttr(t+'.sy',lock=True)
					mc.setAttr(t+'.sz',lock=True)
					mc.setAttr(t+'.tx',lock=True)
					mc.setAttr(t+'.ty',lock=True)
					mc.setAttr(t+'.tz',lock=True)
					mc.setAttr(t+'.rx',lock=True)
					mc.setAttr(t+'.ry',lock=True)
					mc.setAttr(t+'.rz',lock=True)

					aimTr=mc.createNode('transform',p=t)
					mc.xform(aimTr,ws=True,t=antipodes[i])

					#mc.setAttr(db+'.p1',*self.ClosestPoints[i][0])
					#mc.setAttr(db+'.p2',*antipodes[i])
					axisLength=distanceBetween(self.ClosestPoints[i][0],antipodes[i])#mc.getAttr(db+'.d')

					ffd,lattice,latticeBase=mc.lattice(t,divisions=(2,2,2),objectCentered=True,ol=1)
					latticeLowEndPoints=mc.ls(lattice+'.pt[0:1][0:0][0:1]',fl=True)
					latticeHighEndPoints=mc.ls(lattice+'.pt[0:1][1:1][0:1]',fl=True)

					mc.parent(latticeBase,lattice)

					mc.setAttr(lattice+'.sy',axisLength)

					lattices.append([ffd,lattice,latticeBase])

					mc.parent(lattice,t)
					mc.xform(lattice,ws=True,a=True,t=mc.xform(r,q=True,ws=True,a=True,rp=True))
					mc.xform(lattice,os=True,a=True,ro=(0,0,0))
					mc.move(0,axisLength/2,0,lattice,r=True,os=True,wd=True)

					xSum,ySum,zSum=0,0,0
					for p in latticeLowEndPoints:
						px,py,pz=mc.pointPosition(p,w=True)
						xSum+=px
						ySum+=py
						zSum+=pz

					mc.xform(lattice,ws=True,piv=(xSum/len(latticeLowEndPoints),ySum/len(latticeLowEndPoints),zSum/len(latticeLowEndPoints)))
					mc.xform(latticeBase,ws=True,piv=(xSum/len(latticeLowEndPoints),ySum/len(latticeLowEndPoints),zSum/len(latticeLowEndPoints)))

					ac=mc.aimConstraint(aimTr,lattice,aim=(0,1,0),wut='objectrotation',wuo=r,u=(0,0,1),mo=False)
					mc.delete(ac)

					ac=mc.aimConstraint(aimTr,aimGroup,aim=(0,1,0),wut='objectrotation',wuo=r,u=(0,0,1),mo=False)
					mc.delete(ac,aimTr)

					lowEndCluster,lowEndClusterHandle=mc.cluster(latticeLowEndPoints)[:2]
					highEndCluster,highEndClusterHandle=mc.cluster(latticeHighEndPoints)[:2]

					lowEndClusterHandleShape=mc.listRelatives(lowEndClusterHandle,c=True)[0]
					highEndClusterHandleShape=mc.listRelatives(highEndClusterHandle,c=True)[0]

					#mc.parent(highEndClusterHandle,t)

					if mc.isConnected(lowEndClusterHandleShape+'.clusterTransforms[0]',lowEndCluster+'.clusterXforms'):
						mc.disconnectAttr(lowEndClusterHandleShape+'.clusterTransforms[0]',lowEndCluster+'.clusterXforms')
					if mc.isConnected(highEndClusterHandleShape+'.clusterTransforms[0]',highEndCluster+'.clusterXforms'):
						mc.disconnectAttr(highEndClusterHandleShape+'.clusterTransforms[0]',highEndCluster+'.clusterXforms')

					self.autoFlexGroups.append\
					(
						(
							mc.createNode('transform',n='rivetBaseAutoFlex#',p=r),
							mc.createNode('transform',n='rivetEndAutoFlex#',p=aimGroup)
						)
					)

					self.handles.append\
					(
						(
							mc.createNode('transform',n='rivetBaseCtrl#',p=self.autoFlexGroups[i][0]),
							mc.createNode('transform',n='rivetEndCtrl#',p=self.autoFlexGroups[i][1])
						)
					)

					self.handleShapes.append\
					(
						(
							mc.createNode('locator',p=self.handles[i][0]),
							mc.createNode('locator',p=self.handles[i][1])
						)
					)

					mc.setAttr(self.handleShapes[i][0]+'.los',.5,.5,.5)
					mc.setAttr(self.handleShapes[i][1]+'.los',.5,.5,.5)

					mc.xform(self.autoFlexGroups[i][0],ws=True,a=True,t=mc.xform(t,q=True,ws=True,rp=True))
					mc.xform(self.autoFlexGroups[i][0],ws=True,a=True,piv=mc.xform(t,q=True,ws=True,rp=True))

					for bp in self.bindPoses: mc.dagPose((self.handles[i][0],self.handles[i][1]),a=True,n=bp)

					mc.xform(self.autoFlexGroups[i][1],ws=True,t=antipodes[i])

					mc.hide(lattice)

					mc.connectAttr(self.handles[i][0]+'.worldInverseMatrix[0]',lowEndCluster+'.bindPreMatrix',f=True)
					mc.disconnectAttr(self.handles[i][0]+'.worldInverseMatrix[0]',lowEndCluster+'.bindPreMatrix')

					mc.connectAttr(self.handles[i][0]+'.worldMatrix[0]',lowEndCluster+'.matrix',f=True)

					mc.connectAttr(self.handles[i][1]+'.worldInverseMatrix[0]',highEndCluster+'.bindPreMatrix',f=True)
					mc.disconnectAttr(self.handles[i][1]+'.worldInverseMatrix[0]',highEndCluster+'.bindPreMatrix')

					mc.connectAttr(self.handles[i][1]+'.worldMatrix[0]',highEndCluster+'.matrix',f=True)

					aimGroups.append(aimGroup)

					if self.distribute=='u':
						mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][0]+'.sy')
					else:
						mc.connectAttr(clampNode+'.opg',self.autoFlexGroups[i][0]+'.sz')

					mc.delete([lowEndClusterHandle,highEndClusterHandle])

				self.rivets.append(r)

		if self.createAimCurve and self.parent:

			pmm=mc.createNode('pointMatrixMult')
			arcPoints=[]
			ids=[0,centerMostRivetIDs[0],centerMostRivetIDs[1],-1]

			for id in ids:

				measureTr=mc.createNode('transform')
				aimTr=mc.createNode('transform',p=self.trs[id])
				mc.parent(measureTr,self.trs[id])

				mc.xform(aimTr,ws=True,t=antipodes[id])
				mc.xform(measureTr,ws=True,t=mc.xform(self.rivets[id],q=True,ws=True,a=True,rp=True))
				#mc.xform(measureTr,os=True,a=True,ro=(0,0,0),s=(1,1,1))

				ac=mc.aimConstraint(aimTr,measureTr,aim=(0,1,0),wut='objectrotation',wuo=self.rivets[id],u=(0,0,1),mo=False)
				mc.delete(ac,aimTr)

				mc.connectAttr(measureTr+'.worldInverseMatrix',pmm+'.inMatrix',f=True)

				maxYID=-1
				maxY=0.0
				yVal=0.0

				for i in range(0,self.number):

					mc.setAttr(pmm+'.ip',*antipodes[i])
					yVal=mc.getAttr(pmm+'.oy')
					if yVal>maxY:
						maxY=yVal
						maxYID=i

				mc.setAttr(pmm+'.ip',*antipodes[maxYID])

				oy=mc.getAttr(pmm+'.oy')

				mc.setAttr(pmm+'.ip',*antipodes[id])

				ox=mc.getAttr(pmm+'.ox')
				oz=mc.getAttr(pmm+'.oz')

				mc.connectAttr(measureTr+'.worldMatrix',pmm+'.inMatrix',f=True)
				mc.setAttr(pmm+'.ip',ox,oy,oz)

				ap=mc.getAttr(pmm+'.o')[0]

				arcPoints.append(ap)

				mc.disconnectAttr(measureTr+'.worldMatrix',pmm+'.inMatrix')

				mc.delete(measureTr)

			mc.delete(pmm)

			arcCtrlArg=arcPoints
			arcCtrlKeys={'arcWeight':self.arcWeight,'p':self.parents,'sp':self.softParents}

			for k in arcCtrlKeys:
				if type(arcCtrlKeys[k]).__name__=='NoneType':
					del(arcCtrlKeys[k])

			self.ArcCtrl=ArcCtrl(*arcCtrlArg,**arcCtrlKeys)

			mc.addAttr(self.ArcCtrl[0],at='bool',ln='showHandles',k=True,dv=False)
			mc.setAttr(self.ArcCtrl[0]+'.showHandles',k=False,cb=True)
			mc.setAttr(self.ArcCtrl[0]+'.v',k=False,cb=True)
			mc.setAttr(self.ArcCtrl[1]+'.v',k=False,cb=True)

			for h in self.handles:
				mc.connectAttr(self.ArcCtrl[0]+'.showHandles',h[0]+'.v')
				mc.connectAttr(self.ArcCtrl[0]+'.showHandles',h[1]+'.v')

			for bp in self.bindPoses: mc.dagPose(self.ArcCtrl,a=True,n=bp)

			cpoc=mc.createNode('closestPointOnCurve')
			mc.connectAttr(self.ArcCtrl.outputCurve,cpoc+'.inCurve')

			for i in range(0,self.number):

				aimTr=mc.createNode('transform')
				poci=mc.createNode('pointOnCurveInfo')
				dm=mc.createNode('decomposeMatrix')
				fbfm=mc.createNode('fourByFourMatrix')

				mc.connectAttr(poci+'.nnx',fbfm+'.in00')
				mc.connectAttr(poci+'.nny',fbfm+'.in01')
				mc.connectAttr(poci+'.nnz',fbfm+'.in02')
				mc.connectAttr(poci+'.ntx',fbfm+'.in10')
				mc.connectAttr(poci+'.nty',fbfm+'.in11')
				mc.connectAttr(poci+'.ntz',fbfm+'.in12')

				mc.connectAttr(self.ArcCtrl.outputNormal+'X',fbfm+'.in20')
				mc.connectAttr(self.ArcCtrl.outputNormal+'Y',fbfm+'.in21')
				mc.connectAttr(self.ArcCtrl.outputNormal+'Z',fbfm+'.in22')

				mc.connectAttr(poci+'.px',fbfm+'.in30')
				mc.connectAttr(poci+'.py',fbfm+'.in31')
				mc.connectAttr(poci+'.pz',fbfm+'.in32')

				mc.connectAttr(fbfm+'.output',dm+'.inputMatrix')
				mc.connectAttr(dm+'.outputTranslate',aimTr+'.t')
				mc.connectAttr(dm+'.outputRotate',aimTr+'.r')

				mc.setAttr(cpoc+'.ip',*antipodes[i])
				cpu=mc.getAttr(cpoc+'.u')
				mc.setAttr(poci+'.parameter',cpu)

				mc.connectAttr(self.ArcCtrl.outputCurve,poci+'.inputCurve')

				ac=mc.aimConstraint(aimTr,self.aimGroups[i],aim=(0,1,0),wut='objectrotation',wuo=aimTr,u=(0,0,1),mo=not(self.realign))[0]

				disconnectNodes(aimTr,ac)

				mc.connectAttr(fbfm+'.output',ac+'.worldUpMatrix',f=True)
				mc.connectAttr(dm+'.ot',ac+'.target[0].targetTranslate',f=True)

				mc.delete(aimTr)

				sc=mc.createNode('subCurve')

				mc.setAttr(sc+'.relative',True)
				mc.setAttr(sc+'.minValue',0)
				mc.setAttr(sc+'.maxValue',1)

				mc.connectAttr(self.ArcCtrl.outputCurve,sc+'.ic')

				if self.distribute=='u':
					uMultAttr=uvMultipliers[i][0]+".o"
				else:
					uMultAttr=uvMultipliers[i][1]+".o"

				#adjust for offset

				multOffsetCalc=mc.createNode('multDoubleLinear')
				mc.setAttr(multOffsetCalc+'.i1',1/mc.getAttr(uMultAttr))
				mc.connectAttr(uMultAttr,multOffsetCalc+'.i2')

				multOffset=mc.createNode('multDoubleLinear')
				mc.setAttr(multOffset+'.i1',cpu)
				mc.connectAttr(multOffsetCalc+'.o',multOffset+'.i2')

				mc.connectAttr(multOffset+'.o',poci+'.parameter',f=True)

				subtractNode=mc.createNode('addDoubleLinear')
				mc.setAttr(subtractNode+'.i1',-(1.0/(self.number*2)))
				addNode=mc.createNode('addDoubleLinear')
				mc.setAttr(addNode+'.i1',1.0/(self.number*2))
				addSubClampNode=mc.createNode('clamp')
				mc.setAttr(addSubClampNode+'.min',0,0,0)
				mc.setAttr(addSubClampNode+'.max',1,1,1)
				mc.connectAttr(subtractNode+'.o',addSubClampNode+'.inputR')
				mc.connectAttr(addNode+'.o',addSubClampNode+'.inputG')

				mc.connectAttr(multOffset+".o",subtractNode+".i2")
				mc.connectAttr(multOffset+".o",addNode+".i2")
				mc.connectAttr(addSubClampNode+'.outputR',sc+'.minValue')
				mc.connectAttr(addSubClampNode+'.outputG',sc+'.maxValue')

				ciU=mc.createNode('curveInfo')
				mc.connectAttr(sc+'.outputCurve',ciU+'.inputCurve')

				mdlU=mc.createNode('multDoubleLinear')
				mc.connectAttr(ciU+'.al',mdlU+'.i1')
				mc.setAttr(mdlU+'.i2',1/float(mc.getAttr(ciU+'.al')))

				clampNode=mc.createNode('clamp')

				if not mc.objExists(c+'.minScaleEnd'): mc.addAttr(self.ctrls[i],ln='minScaleEnd',at='double',k=True,min=0,max=1,dv=0)
				if not mc.objExists(c+'.maxScaleEnd'): mc.addAttr(self.ctrls[i],ln='maxScaleEnd',at='double',k=True,min=0,dv=1)

				mc.connectAttr(self.ctrls[i]+'.minScaleEnd',clampNode+'.minR')
				mc.connectAttr(self.ctrls[i]+'.maxScaleEnd',clampNode+'.maxR')

				mc.connectAttr(mdlU+'.o',clampNode+'.ipr')

				if self.distribute=='u':
					mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][1]+'.sz')
				else:
					mc.connectAttr(clampNode+'.opr',self.autoFlexGroups[i][1]+'.sy')

			mc.delete(cpoc)

		if self.parent:
			self[:]=self.rivets
		else:
			self[:]=self.trs
		#if self.mo:
		#	#for i in len(self.trs):
		#		#try: mc.xform(t,q=True,ws=True,m=wsMatrices[i]))
		#		#except: pass

		cleanup.append(cpos)

		for c in cleanup:
			if mc.objExists(c):
				disconnectNodes(c)
				mc.delete(c)

		if self.snapToSurface:
			if self.createAimCurve or self.taper:
				for i in range(0,self.number):
					mc.xform(self.handles[i][0],ws=True,t=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
					mc.xform(self.trs[i],ws=True,rp=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
			else:
				for i in range(0,self.number):
					mc.xform(self.trs[i],ws=True,t=mc.xform(self.rivets[i],q=True,ws=True,rp=True))
					mc.xform(self.trs[i],ws=True,ro=mc.xform(self.rivets[i],q=True,ws=True,ro=True))
Esempio n. 34
0
def createBindPose(root, name='skeletonPose0'):
    pose = cmds.dagPose(root, name=name, save=True)
    return pose
Esempio n. 35
0
	def create(self):

		mc.cycleCheck(e=False)

		if mc.objExists(self.parent):
			self.group=mc.createNode('transform',n=uniqueNames(self.name),p=self.parent)
		else:
			self.group=mc.createNode('transform',n=uniqueNames(self.name))

		self.jointParent=''
		if len(iterable(mc.listRelatives(self.joints[0],p=True)))>0:
			self.jointParent=mc.listRelatives(self.joints[0],p=True)[0]
		else:
			self.jointParent=mc.createNode('transform',n=uniqueNames(self.name+'CtrlJointGroup'))
			mc.parent(self.joints[0],self.jointParent)

		cMuscleObjects=[]

		# create control joints

		self.ctrlJoints=[]
		for j in self.joints:

			cj=mc.createNode('joint',p=j,n=uniqueNames(self.name+'CtrlJoint'))

			if len(self.ctrlJoints)==0:
				mc.parent(cj,self.group)
				if mc.objExists(self.jointParent):
					self.jointParent=mc.rename(ParentSpace(cj,self.jointParent)[0],self.name+'CtrlJoints')
				else:
					self.jointParent=mc.rename(ParentSpace(cj)[0],self.name+'CtrlJoints')
			else:
				mc.parent(cj,self.ctrlJoints[-1])

			mc.setAttr(cj+'.r',*mc.getAttr(j+'.r')[0])
			mc.setAttr(cj+'.jo',*mc.getAttr(j+'.jo')[0])
			self.originalRotations[cj+'.r']=list(mc.getAttr(cj+'.r')[0])

			mc.setAttr(j+'.r',0,0,0)
			mc.setAttr(cj+'.r',0,0,0)

			mc.setAttr(cj+'.s',1,1,1)
			mc.setAttr(cj+'.radius',mc.getAttr(j+'.radius')*1.5)#0)
			mc.setAttr(cj+'.ovc',10)
			mc.connectAttr(j+'.pa',cj+'.pa')

			if self.joints.index(j)<len(self.joints)-1:
				childList=removeAll\
				(
					iterable(mc.listRelatives(self.joints[self.joints.index(j)+1],c=True,ad=True))+[self.joints[self.joints.index(j)+1]],
					iterable(mc.listRelatives(j,c=True,ad=True))+[j]
				)

				chList=childList
				for c in chList:
					if mc.nodeType(c) not in ['transform','joint','cMuscleObject']:
						childList.remove(c)
					if mc.nodeType(c) in ['transform','joint']:
						for a in ['.t','.tx','.ty','.tz','.r','.rx','.ry','.rz']:
							if mc.connectionInfo(c+a,id=True) or mc.getAttr(c+a,l=True) or mc.getAttr(c+'.io'):
								childList.remove(c)
								break

				if j==self.joints[-2]:
					childList.append(self.joints[-1])

				for jc in childList:
					if mc.nodeType(jc)=='transform' or mc.nodeType(jc)=='joint':
						if jc in self.joints[:-1]:
							mc.parentConstraint(cj,jc,mo=True)
						else:
							mc.parentConstraint(cj,jc,sr=('x','y','z'),mo=True)
					elif 'cMuscle' in mc.nodeType(jc):
						cMuscleObjects.append(jc)

			else:
				mc.parentConstraint(cj,j,st=('x','y','z'),mo=True)

			self.ctrlJoints.append(cj)

		mc.hide(self.jointParent)
		mc.setAttr(self.ctrlJoints[1]+'.ssc',False)

		# create ik

		self.ikHandle,self.endEffector=mc.ikHandle(sol='ik2Bsolver',sj=self.ctrlJoints[0],ee=self.ctrlJoints[-1],n=uniqueNames(self.name+'Handle'))
		self.endEffector=mc.rename(self.endEffector,self.name+'Effector')
		mc.setAttr(self.ikHandle+'.snapEnable',False)
		mc.hide(self.ikHandle)
		mc.setAttr(self.ikHandle+'.ikBlend',0)

		for j in self.originalRotations:
			if isIterable(self.originalRotations[j]):
				mc.setAttr(j,*self.originalRotations[j])
			else:
				mc.setAttr(j,self.originalRotations[j])

		# look for twist joints

		if self.twist:
			skipAxis=removeAll(self.orientAxis,['x','y','z'])
			twistJoints=removeAll([self.joints[-2],self.joints[-1]],hierarchyBetween(self.joints[-2],self.joints[-1],type='joint'))
			for i in range(0,len(twistJoints)):
				tj=twistJoints[i]
				oc=mc.orientConstraint(self.ctrlJoints[-1],tj,sk=skipAxis,mo=True)
				if i>0:
					oc=mc.orientConstraint(self.ctrlJoints[-2],tj,sk=skipAxis,mo=True)
					wal=mc.orientConstraint(oc,q=True,wal=True)
					distToBend=distanceBetween(self.ctrlJoints[-2],tj)
					distToEnd=distanceBetween(self.ctrlJoints[-1],tj)
					mc.setAttr(oc+'.'+wal[-1],distToEnd/(distToBend+distToEnd))
					mc.setAttr(oc+'.'+wal[-2],distToBend/(distToBend+distToEnd))

		# make stretchy

		db=mc.createNode('distanceBetween')
		mc.connectAttr(self.ctrlJoints[0]+'.t',db+'.p1')

		pmm1=mc.createNode('pointMatrixMult')
		pmm2=mc.createNode('pointMatrixMult')

		mc.connectAttr(self.ikHandle+'.t',pmm1+'.ip')
		mc.connectAttr(self.ikHandle+'.pm[0]',pmm1+'.im')

		mc.connectAttr(pmm1+'.o',pmm2+'.ip')
		mc.connectAttr(self.ctrlJoints[0]+'.pim[0]',pmm2+'.im')

		mc.connectAttr(pmm2+'.o',db+'.p2')

		mdl=mc.createNode('multDoubleLinear')
		mc.connectAttr(db+'.d',mdl+'.i1')
		mc.setAttr(mdl+'.i2',1.0/mc.getAttr(db+'.d'))
		cn=mc.createNode('clamp')
		for i in range(0,3):
			c=['r','g','b'][i]
			a=['x','y','z'][i]
			mc.connectAttr(mdl+'.o',cn+'.ip'+c)
			mc.setAttr(cn+'.mn'+c,1)
			mc.connectAttr(mdl+'.o',cn+'.mx'+c)
			mc.connectAttr(cn+'.op'+c,self.ctrlJoints[0]+'.s'+a)

		for cmo in cMuscleObjects:
			mdlcm=mc.createNode('multDoubleLinear')
			mc.setAttr(mdlcm+'.i1',mc.getAttr(cmo+'.length'))
			mc.connectAttr(cn+'.op'+['r','g','b'][['x','y','z'].index(self.orientAxis)],mdlcm+'.i2')
			mc.connectAttr(mdlcm+'.o',cmo+'.length')


		# create control objects or set control object pivots

		poleOffset=distanceBetween(self.ctrlJoints[1],self.ctrlJoints[0])*2

		for i in range(0,len(self.controlObjects)-1):
			if mc.objExists(self.controlObjects[i]):
				mc.xform(self.controlObjects[i],ws=True,piv=mc.xform(self.ctrlJoints[-1],q=True,ws=True,rp=True))
			else:
				if 'r' not in self.handleOptions[i] and 'radius' not in self.handleOptions[i]:
					self.handleOptions[i]['r']=distanceBetween(self.ctrlJoints[-1],self.ctrlJoints[0])/4
				if 'name' not in self.handleOptions[i] and 'n' not in self.handleOptions[i]:
					self.handleOptions[i]['n']=self.joints[i]+'_ctrl'
				if 'x' not in self.handleOptions[i] and 'xform' not in self.handleOptions[i]:
					self.handleOptions[i]['xform']=self.joints[i]
				if 'aim' not in self.handleOptions[i] and 'a' not in self.handleOptions[i]:
					self.handleOptions[i]['aim']=self.aimVector
				self.handleOptions[i]['parent']=self.group
				self.handleOptions[-i]['pointTo']=self.joints[i]
				self.handleOptions[i]['aimAt']=self.joints[i]
				self.handles.append(Handle(**self.handleOptions[i]))
				self.controlObjects[i]=(self.handles[-1].transforms[-1])

		if not mc.objExists(self.controlObjects[-1]):
			if 'name' not in self.handleOptions[-1] and 'n' not in self.handleOptions[-1]:
				self.handleOptions[-1]['n']=self.joints[1]+'_aimCtrl'
			if 'x' not in self.handleOptions[-1] and 'xform' not in self.handleOptions[-1]:
				self.handleOptions[-1]['x']=self.ctrlJoints[1]
			if 'aim' not in self.handleOptions[i] and 'a' not in self.handleOptions[i]:
				self.handleOptions[i]['aim']=self.poleVector
			self.handleOptions[-1]['parent']=self.group
			self.handleOptions[-1]['pointTo']=self.joints[1]
			self.handleOptions[-1]['aimAt']=self.joints[1]
			self.handles.append(Handle(**self.handleOptions[-1]))
			self.controlObjects[-1]=(self.handles[-1].transforms[-1])
			mc.move\
			(
				poleOffset*(self.poleVector[0]),
				poleOffset*(self.poleVector[1]),
				poleOffset*(self.poleVector[2]),
				self.controlObjects[-1],
				r=True,os=True,wd=True
			)

		# add and set control attributes

		mc.setAttr(self.controlObjects[-1]+'.v',k=False)
		for attr in ['.sx','.sy','.sz']:
			mc.setAttr(self.controlObjects[-1]+attr,l=True,k=False,cb=False)
			mc.setAttr(self.ikHandle+attr,l=True,k=False,cb=False)
		for attr in ['.rx','.ry','.rz']:
			mc.setAttr(self.controlObjects[-1]+attr,k=False,cb=False)
		for attr in ['.tx','.ty','.tz']:
			mc.setAttr(self.group+attr,l=True,k=False,cb=False)
			mc.setAttr(self.controlObjects[0]+attr,l=True,k=False,cb=False)

		mc.setAttr(self.ikHandle+'.v',k=False,cb=False)

		for attr in ['.tx','.ty','.tz']:
			mc.setAttr(self.controlObjects[1]+attr,l=True,k=False,cb=False)

		if not mc.objExists(self.controlObjects[-2]+'.twist'):
			mc.addAttr(self.controlObjects[-2],at='doubleAngle',ln='twist',k=True)
		if not mc.objExists(self.controlObjects[-2]+'.sway') and self.sway:
			mc.addAttr(self.controlObjects[-2],at='doubleAngle',ln='sway',k=1)
		if not mc.objExists(self.controlObjects[-2]+'.stretch'):
			mc.addAttr(self.controlObjects[-2],at='double',ln='stretch',k=1,dv=self.stretch,min=0)
		if not mc.objExists(self.controlObjects[-2]+'.squash'):
			mc.addAttr(self.controlObjects[-2],at='double',ln='squash',k=1,dv=self.squash,min=0,max=99)
		if not mc.objExists(self.controlObjects[-2]+'.ikSwitch'):
			mc.addAttr(self.controlObjects[-2],at='enum',ln='ikSwitch',en='ik:fk',k=True,dv=1)# if self.switch=='fk' else 0

		#sway control

		if self.sway:

			adl=mc.createNode('addDoubleLinear')
			mc.connectAttr(self.ctrlJoints[1]+'.r'+self.poleAxis,adl+'.i1')
			mc.connectAttr(self.controlObjects[-2]+'.sway',adl+'.i2')
			childList=removeAll\
			(
				iterable(mc.listRelatives(self.joints[2],c=True,ad=True)),
				iterable(mc.listRelatives(self.joints[1],c=True,ad=True))
			)+[self.joints[2],self.joints[1]]
			for c in childList:
				if mc.nodeType(c)=='transform' or mc.nodeType(c)=='joint':
					pc=mc.parentConstraint(c,q=True)
					nc=listNodeConnections(self.ctrlJoints[1],pc,s=True,d=True)
					for conn in nc:
						if conn[0]==self.ctrlJoints[1]+'.rotate':
							mc.disconnectAttr(conn[0],conn[1])
							for a in removeAll(self.poleAxis,['x','y','z']):
								mc.connectAttr(conn[0]+a.upper(),conn[1]+a.upper(),f=True)
							mc.connectAttr(adl+'.o',conn[1]+self.poleAxis.upper(),f=True)

		# ik/fk switch

		for i in range(0,3):

			c=['r','g','b'][i]
			a=['x','y','z'][i]
			adl=mc.createNode('addDoubleLinear')
			mdl1=mc.createNode('multDoubleLinear')
			mc.setAttr(mdl1+'.i2',.01)
			mdl2=mc.createNode('multDoubleLinear')
			mc.setAttr(mdl2+'.i2',.01)
			revNode=mc.createNode('reverse')
			mc.setAttr(adl+'.i1',1)

			mc.connectAttr(	mdl1+'.o',adl+'.i2')
			mc.connectAttr(self.controlObjects[-2]+'.stretch',mdl1+'.i1')

			mc.connectAttr(	mdl2+'.o',revNode+'.ix')
			mc.connectAttr(self.controlObjects[-2]+'.squash',mdl2+'.i1')

			mc.connectAttr(adl+'.o',cn+'.mx'+c,f=True)
			mc.connectAttr(revNode+'.ox',cn+'.mn'+c,f=True)

		if not mc.objExists(self.controlObjects[-2]+'.zenPreviousIKState'):
			if self.switch=='fk':
				mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKState',k=0,dv=1)
			else:
				mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKState',k=0,dv=0)
		if not mc.objExists(self.controlObjects[-2]+'.zenPreviousIKParent'):
			if self.switch=='fk':
				mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKParent',k=0,dv=1)
			else:
				mc.addAttr(self.controlObjects[-2],at='long',ln='zenPreviousIKParent',k=0,dv=0)

		for i in range(0,2):
			for c in mc.listRelatives(self.controlObjects[i],s=True):
				mc.connectAttr(self.controlObjects[-2]+'.ikSwitch',c+'.v')

		mc.connectAttr(self.controlObjects[-2]+'.twist',self.ikHandle+'.twist')

		rev=mc.createNode('reverse')
		mc.connectAttr(self.controlObjects[-2]+'.ikSwitch',rev+'.ix')
		mc.connectAttr(rev+'.ox',self.ikHandle+'.ikBlend')

		for c in mc.listRelatives(self.controlObjects[-1],s=True):
			mc.connectAttr(rev+'.ox',c+'.v')

		# parent spaces

		for i in [0,1,2]:
			if(mc.objExists(self.jointParent)and i in [0,2]):
				ParentSpace(self.controlObjects[i],self.jointParent)
			else:
				ParentSpace(self.controlObjects[i],self.controlObjects[i-1])

		ParentSpace(self.controlObjects[-1],self.controlObjects[-2])
		if mc.objExists(self.jointParent):
			ParentSpace(self.controlObjects[-1],self.jointParent).setParent(self.jointParent)
			ParentSpace(self.controlObjects[-2],self.jointParent).setParent(self.jointParent)
		else:
			ParentSpace(self.controlObjects[-1],self.controlObjects[0])

		if self.switch=='fk':
			ParentSpace(self.controlObjects[2],self.controlObjects[1])

		for co in self.controlObjects[2:]:
			freeze(co,t=True)

		mc.aimConstraint\
		(
			self.ctrlJoints[1],self.controlObjects[-1],
			aim=(self.aimVector[0],self.aimVector[1],self.aimVector[2]),
			wuo=self.ctrlJoints[1],
			wut='objectrotation',
			mo=True
		)

		if mc.objExists(self.jointParent):
			mc.setAttr(self.controlObjects[0]+'.parentTo',l=True,k=False,cb=False)
		mc.setAttr(self.controlObjects[1]+'.parentTo',l=True,k=False,cb=False)

		#constraints

		orientConstraints=['','','']
		for i in [2,1,0]:
			orientConstraints[i]=mc.orientConstraint(self.controlObjects[i],self.ctrlJoints[i],mo=True)[0]
			mc.setAttr(self.controlObjects[i]+'.v',k=False)
			for attr in ['.sx','.sy','.sz']:
				mc.setAttr(self.controlObjects[i]+attr,l=True,k=False,cb=False)
			if i==1:
				if not self.sway:
					mc.setAttr(self.controlObjects[i]+'.r'+self.poleAxis,l=True,k=False,cb=False)
				mc.setAttr(self.controlObjects[i]+'.r'+self.orientAxis,l=True,k=False,cb=False)

		self.poleVectorConstraint=mc.poleVectorConstraint(self.controlObjects[-1],self.ikHandle)[0]

		for oc in orientConstraints[:-1]:
			octl=mc.orientConstraint(oc,q=True,tl=True)
			ocwal=mc.orientConstraint(oc,q=True,wal=True)
			weightAlias=ocwal[octl.index(self.controlObjects[orientConstraints.index(oc)])]
			mc.connectAttr(self.controlObjects[-2]+'.ikSwitch',oc+'.'+weightAlias)

		mc.parent(self.ikHandle,self.controlObjects[2],r=False)

		if self.switch=='ik':
			mc.setAttr(self.controlObjects[-2]+'.ikSwitch',0)

		# link for asset detection

		if 'zenIkFkLimbCtrls' not in mc.listAttr(self.group):
			mc.addAttr(self.group,ln='zenIkFkLimbCtrls',at='message',m=True)
		if 'zenIkFkLimbCtrlJoints' not in mc.listAttr(self.group):
			mc.addAttr(self.group,ln='zenIkFkLimbCtrlJoints',at='message',m=True)
		for co in self.controlObjects:
			if 'zenCtrl' not in mc.listAttr(co):
				mc.addAttr(co,ln='zenCtrl',at='message')
			mc.connectAttr(co+'.zenCtrl',self.group+'.zenIkFkLimbCtrls['+str(firstOpenPlug(self.group+'.zenIkFkLimbCtrls'))+']')
		for cj in self.ctrlJoints:
			if 'zenCtrl' not in mc.listAttr(cj):
				mc.addAttr(cj,ln='zenCtrl',at='message')
			mc.connectAttr(cj+'.zenCtrl',self.group+'.zenIkFkLimbCtrlJoints['+str(firstOpenPlug(self.group+'.zenIkFkLimbCtrlJoints'))+']')

		for bp in self.bindPoses:
			for co in self.controlObjects:
				mc.dagPose(co,a=True,n=bp)

		self[:]=[self.group]+self.controlObjects

		mc.cycleCheck(e=True)

		mc.select(self[-2])
Esempio n. 36
0
 def bindPoseFn(self):
     if self.currentSkin:
         bp = cmds.listConnections(self.currentSkin + '.bindPose', s=1)
         if len(bp) > 0: cmds.dagPose(bp[0], r=1)
         else: cmds.warning('Multiple bind poses detected: ' + str(bp))
     else: cmds.warning('No skin cluster loaded or mesh with skin cluster selected.')
Esempio n. 37
0
def restoreBindPose(poseName):
    cmds.dagPose(poseName, restore=True, g=True)
    return
def extract_faces(face_list=None,
                  new_name=None,
                  keep_original=False,
                  copy_skinning=False):
    """Extract faces from mesh and create a copy

    :param face_list: List of faces to extract
    :param new_name: New mesh name
    :param keep_original: Make a copy of mesh before extraction
    :param copy_skinning: Copy skin weights over to extracted mesh
    :return: Extracted mesh
    """

    if not face_list:
        selected_faces = cmds.ls(sl=True)
    else:
        selected_faces = face_list

    if not bool(cmds.filterExpand(selected_faces, ex=True, sm=34)) or []:
        raise RuntimeError("Must select one or more faces")

    shape = cmds.listRelatives(p=1)
    cur_mesh = cmds.listRelatives(shape, p=1)[0]

    cmds.select(cur_mesh + '.f[:]', tgl=1)
    faces_to_extract = cmds.ls(sl=1)

    # Save current pose
    influence_list = cmds.skinCluster(cur_mesh, q=True, wi=True)
    cur_pose = cmds.dagPose(influence_list, save=True, name='extractInPose')

    # Go to bind pose before copying weights
    bind_pose = cmds.dagPose(influence_list, q=True, bindPose=True)
    cmds.dagPose(bind_pose, restore=True)

    new_mesh = cmds.duplicate(cur_mesh)[0]

    # Rename mesh
    if new_name:
        new_mesh = cmds.rename(new_mesh, new_name)

    # Copy skin weights over to new mesh
    if copy_skinning:
        copy_proxy_to_skin(cur_mesh, new_mesh)

    if not keep_original:
        cmds.delete(selected_faces)

    # Swap current mesh to new mesh
    for i in range(len(faces_to_extract)):
        faces_to_extract[i] = faces_to_extract[i].replace(cur_mesh, new_mesh)

    cmds.delete(faces_to_extract)

    # Clean new mesh
    if copy_skinning:
        cmds.bakePartialHistory(cur_mesh, prePostDeformers=True)
        cmds.bakePartialHistory(new_mesh, prePostDeformers=True)
    else:
        cmds.delete(new_mesh, ch=1)

    cmds.dagPose(cur_pose, restore=True)
    cmds.delete(cur_pose)
    cmds.select(new_mesh, r=1)

    return new_mesh
Esempio n. 39
0
	def mkControlObjects(self):

		if not mc.objExists(self.handles[-1]):

			self.handles[-1]=mc.createNode('transform',n=uniqueNames(self.name[-1]))
			mc.xform(self.handles[-1],ws=True,a=True,m=mc.xform(self.ArcCtrl.handles[-1],q=True,ws=True,m=True))
			mc.xform(self.handles[-1],ws=True,a=True,piv=mc.xform(self.ArcCtrl.handles[-1],q=True,a=True,ws=True,piv=True)[:3])
			if 'type' not in self.handleOptions[-1]:
				self.handleOptions[-1]['type']=self.handleType[-1]
			if 'radius' not in self.handleOptions[-1]:
				self.handleOptions[-1]['radius']=self.radius
			self.handleShape[-1]=Handle(self.handles[-1],**self.handleOptions[-1])

		if mc.objExists(self.parent[-1]):
			mc.parent(self.handles[-1],self.parent[-1])

		if mc.objExists(self.softParent[-1]):
			self.parentSpace[-1]=ParentSpace(self.handles[-1],self.softParent[-1])
			for bp in getBindPoses(self.jointHierarchy): mc.dagPose(self.parentSpace[-1],a=True,n=bp)

		mc.makeIdentity(self.handles[-1],apply=True,t=True)#,r=True)

		mc.addAttr(self.handles[-1],ln='stretch',at='float',min=0,k=1,dv=self.stretch)
		mc.addAttr(self.handles[-1],ln='squash',at='float',min=0,max=1,k=1,dv=self.squash)
		mc.addAttr(self.handles[-1],ln='arcWeight',at='float',min=0,max=1,k=1,dv=self.arcWeight)
		mc.addAttr(self.handles[-1],ln='width',at='float',min=0.0001,k=1,dv=self.width)
		mc.connectAttr(self.handles[-1]+'.stretch',self.ArcCtrl.handles[-1]+'.stretch',f=True)
		mc.connectAttr(self.handles[-1]+'.squash',self.ArcCtrl.handles[-1]+'.squash',f=True)
		mc.connectAttr(self.handles[-1]+'.arcWeight',self.ArcCtrl.handles[-1]+'.arcWeight',f=True)
		mc.connectAttr(self.handles[-1]+'.width',self.ArcCtrl.handles[0]+'.width',f=True)

		if self.curl:
			mc.addAttr(self.handles[-1],ln='curl',at='doubleAngle',k=1,dv=0)

			for r in removeAll(self.jointHierarchy,self.rivet):

				axis='x'
				longestAxisLen=0

				for a in ['x','y','z']:

					axisLen=abs(mc.getAttr(r+'.t'+a))

					if axisLen>longestAxisLen:
						longestAxisLen=axisLen
						axis=a

				behaviorMirrored=False

				try:
					parentJoint=mc.listRelatives(r,p=True)[0]

					oppositeJoint=removeAll(r,mc.listRelatives(parentJoint,c=True,type='joint'))[0]
					for a in ['x','y','z']:

						if\
						(
							abs(180-abs(abs(mc.getAttr(r+'.jo'+a))-abs(mc.getAttr(oppositeJoint+'.jo'+a))))<5
						):
							behaviorMirrored=True
							break
				except:
					pass

				pcr=mc.listConnections(r+'.rx',type='parentConstraint')[0]

				pcTargets=mc.parentConstraint(pcr,q=True,tl=True)
				pcIDs=[]
				nsc=listNodeConnections(pcr,s=False,d=True)

				for n in range(0,len(nsc)):
					if len(nsc[n])==2 and mc.objExists(nsc[n][-1]):
						pcID=getIDs(nsc[n][-1])
						if isinstance(pcID,int):
							pcIDs.append(pcID)

				pcIDs=removeDuplicates(pcIDs)
				pcIDs.sort()
				pcID=pcIDs[-1]

				pma=mc.createNode('plusMinusAverage')

				if mc.getAttr(r+'.uPos')>50:
					mc.setAttr(pma+'.op',2)
					if\
					(
						(behaviorMirrored and parentJoint!=self.jointHierarchy[-1])
					):
						mc.setAttr(pma+'.op',1)
				if mc.getAttr(r+'.uPos')<50:
					mc.setAttr(pma+'.op',1)
					if\
					(
						behaviorMirrored
					):
						mc.setAttr(pma+'.op',2)

				mc.setAttr(pma+'.i1[0]',mc.getAttr(pcr+'.tg['+str(pcID)+'].tor'+axis))
				mc.setAttr(pcr+'.tg['+str(pcID)+'].tor'+axis,lock=False)
				mc.connectAttr(self.handles[-1]+'.curl',pma+'.i1[1]')
				mc.connectAttr(pma+'.o1',pcr+'.tg['+str(pcID)+'].tor'+axis)





		mc.parentConstraint(self.handles[-1],self.ArcCtrl.handles[-1],mo=True)
		mc.scaleConstraint(self.handles[-1],self.ArcCtrl.handles[-1],sk=('x','y'),mo=True)

		for bp in getBindPoses(self.jointHierarchy): mc.dagPose(self.handles[-1],a=True,n=bp)

		mc.setAttr(self.handles[-1]+'.sy',k=False,lock=True)
		mc.setAttr(self.handles[-1]+'.sx',k=False,lock=True)
		if not self.spread:
			mc.setAttr(self.handles[-1]+'.sz',k=False,lock=True)


		mc.setAttr(self.handles[-1]+'.v',k=False,cb=True)

		for bp in getBindPoses(self.jointHierarchy): mc.dagPose(self.handles[-1],a=True,n=bp)
Esempio n. 40
0
import maya.mel as mel
import maya.cmds as cmds

# add this to the function in zTools
sel = cmds.ls(sl=True)
for x in range(1, len(sel)):
    cmds.polyTransfer(sel[i], uv=1, ao=sel[0])

# leave only one bind pose in scene
sc = cmds.ls(type="dagPose")
for s in sc:
    cmds.delete(s)
cmds.dagPose(bp=True, save=True)

#stick a joint in center of verts
import maya.cmds as cmds
import maya.mel as mel
import zTools.rig.zbw_rig as rig

# convert this selection to components?
sel = cmds.ls(sl=True, fl=True)
jnt = cmds.joint(name="CenterJoint")
pos = rig.average_point_positions(sel)
cmds.xform(jnt, ws=True, t=pos)
# cmds.parent(jnt, w=True)