def testStaticVisibility(self):
        poly1  = MayaCmds.polyPlane(sx=2, sy=2, w=1, h=1, ch=0)[0]
        group1 = MayaCmds.group()
        group2 = MayaCmds.createNode("transform")
        MayaCmds.select(group1, group2)
        group3 = MayaCmds.group()

        group4 = (MayaCmds.duplicate(group1, rr=1))[0]
        group5 = MayaCmds.group()

        MayaCmds.select(group3, group5)
        root = MayaCmds.group(name='root')

        MayaCmds.setAttr(group1 + '.visibility', 0)
        MayaCmds.setAttr(group2 + '.visibility', 0)
        MayaCmds.setAttr(group5 + '.visibility', 0)

        self.__files.append(util.expandFileName('staticVisibilityTest.abc'))
        MayaCmds.AbcExport(j='-wv -root %s -file %s' % (root, self.__files[-1]))

        MayaCmds.AbcImport(self.__files[-1], m='open')
        self.failIf(MayaCmds.getAttr(group1+'.visibility'))
        self.failIf(MayaCmds.getAttr(group2+'.visibility'))
        self.failIf(MayaCmds.getAttr(group5+'.visibility'))

        self.failUnless(MayaCmds.getAttr(group1+'|'+poly1+'.visibility'))
        self.failUnless(MayaCmds.getAttr(group4+'|'+poly1+'.visibility'))
        self.failUnless(MayaCmds.getAttr(group3+'.visibility'))
        self.failUnless(MayaCmds.getAttr(group4+'.visibility'))
        self.failUnless(MayaCmds.getAttr(root+'.visibility'))
示例#2
0
文件: head.py 项目: skarone/PipeL
	def __init__(self, objs = [], vertices = []):
		self.objs = objs
		self.vertices = vertices
		#lattice  -divisions 2 3 2 -objectCentered true  -ol 1;
		#mc.select( self.objs, self.vertices )
		#CREATION
		grp = mn.Node( mc.group( n = "head_toon_GRP", em = True ) )
		deGrp = mn.Node( mc.group( n = "head_toon_deformer_GRP", em = True ) )
		deGrp.parent = grp
		deGrp.a.v.v = False
		deGrp.a.v.locked = True
		latNods = mc.lattice( self.objs, self.vertices, divisions = [ 2,3,2], objectCentered = True, ol = 1, n = 'head_toon_LAT' )
		latBase = mn.Node( latNods[2] )
		latBase.parent = deGrp
		lat = mn.Node( latNods[1] )
		lat.parent = deGrp
		#mc.select( lat + ".pt[0:1][2][0]", lat + ".pt[0:1][2][1]" )
		topClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][2][0]", lat.shape.name + ".pt[0:1][2][1]", n = 'top_face_toon_CLU' )[1] )
		topClus.a.v.v = False
		topClus.a.v.locked = True
		#mc.select( lat + ".pt[0:1][1][0]", lat + ".pt[0:1][1][1]" )
		midClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][1][0]", lat.shape.name + ".pt[0:1][1][1]", n = 'mid_face_toon_CLU' )[1] )
		#mc.select( lat + ".pt[0:1][0][0]", lat + ".pt[0:1][0][1]" )
		lowClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][0][0]", lat.shape.name + ".pt[0:1][0][1]", n = 'low_face_toon_CLU' )[1] )
		ctl = crv.Curve( "head_toon_CTL" )
		ctl = ctl.create( "sphere" )
		ctl.a.t.v = topClus.worldPosition
		mc.makeIdentity( ctl.name, apply = True, t = 1, r = 1, s = 1, n = 2 )
		topClus.parent = ctl
		midClus.parent = deGrp
		lowClus.parent = deGrp
		ctl.parent = grp
		#CONSTRAINS
		midClus.a.r >> topClus.a.r
		mc.pointConstraint( topClus.name, lowClus.name, midClus.name, mo = True )
		#SCALE FOR MID CLUSTER
		dist = mn.createNode( 'distanceBetween', n = 'head_toon_DIS' )
		ctl.a.worldMatrix >> dist.a.inMatrix1
		ctl.a.rp >> dist.a.point1
		lowClus.a.worldMatrix >> dist.a.inMatrix2
		lowClus.a.rp >> dist.a.point2
		mul = mn.createNode( 'multiplyDivide', n = 'head_toon_scale_MUL' )
		mul.a.input1.v = [dist.a.distance.v]*3
		mul.a.operation.v = 2
		dist.a.distance >> mul.a.input2X
		dist.a.distance >> mul.a.input2Y
		dist.a.distance >> mul.a.input2Z
		mul.a.output >> midClus.a.s
		#AIM CONSTRAINT
		upLocGrp = mn.Node( mc.group( n = "head_upVector_GRP", em = True ) )
		upLocGrp.a.t.v = midClus.worldPosition
		mc.makeIdentity( upLocGrp.name, apply = True, t = 1, r = 1, s = 1, n = 2 )
		upLocGrp.parent = deGrp
		mc.orientConstraint( ctl.name, lowClus.name, upLocGrp.name, mo = True )
		upLoc = mn.Node( mc.spaceLocator( n = 'head_upVector_LOC' )[0] )
		upLoc.a.t.v = midClus.worldPosition
		upLoc.a.tz.v = upLoc.a.tz.v + 5
		mc.aimConstraint( topClus.name, midClus.name, mo = True, weight = 1, aimVector = [1, 0, 0], upVector = [0, 1, 0], worldUpType = "object", worldUpObject = upLoc.name )
		upLoc.parent = upLocGrp
		mc.pointConstraint( topClus.name, lowClus.name, upLoc.name, mo = True )
示例#3
0
def exportSelection(selection, filepath):    
    # combine if selection is more than 1 mesh
    if len(selection) > 1:
        selection = modeling.combine()
    # get asset name
    base = os.path.basename(filepath)
    assetname = os.path.splitext(base)[0]
    
    # create groups
    cmds.select(clear=True)
    main_group = cmds.group(n=assetname, empty=True)
    geo_group = cmds.group(n=assetname+'_main', empty=True, p=main_group)
    lod0_group = cmds.group(n=assetname+'_lod0', empty=True, p=geo_group)
    col_group = cmds.group(n=assetname+'_collision', empty=True, p=main_group)
    
    # parent the geo to the lod0 group
    cmds.parent(selection, lod0_group)
    # create the collision
    collision = cmds.duplicate(selection)
    cmds.parent(collision, col_group)

    # rename meshes
    cmds.rename(selection, 'part_state0')
    cmds.rename(collision, 'part_state0_Mesh1')

    # select main group
    cmds.select(main_group, r=True)
    
    # set fbx settings
    mel.eval('FBXExportFileVersion "FBX201300"') 
    #mel.eval('FBXConvertUnitString "m"')
    mel.eval('FBXExportSmoothingGroups -v true')
    mel.eval('FBXExportUpAxis "Y"')
    # export selection
    mel.eval('FBXExport -f "'+filepath+'" -s')
示例#4
0
def reset_pivot(*args):

    sel = mc.ls(sl=True)
    if not sel:
        om.MGlobal.displayWarning('Nothing selected.')
        return

    if len(sel) > 1:
        om.MGlobal.displayWarning('Only works on one node at a time.')
        return

    if is_pivot_connected(sel[0]):
        return    

    node = sel[0]

    pivotPosition = mc.getAttr(node+'.rotatePivot')[0]
    if pivotPosition  == (0.0,0.0,0.0):
        return

    tempPosition = mc.group(em=True)
    tempPivot = mc.group(em=True)
    tempPivot = mc.parent(tempPivot, node)[0]
    mc.setAttr(tempPivot+'.translate', 0,0,0)
    mc.setAttr(tempPivot+'.rotate', 0,0,0)

    utl.matchBake(source=[tempPivot], destination=[tempPosition], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)

    mc.setAttr(node+'.rotatePivot', 0,0,0)
    utl.matchBake(source=[tempPosition], destination=[node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)

    mc.delete(tempPosition,tempPivot)    

    mc.select(node)
示例#5
0
文件: dave.py 项目: jonntd/Rigganator
    def _finger_hydraulics(self):
        """Connects the finger hydraulics."""
        for side in ['L', 'R']:
            for finger in ['pointer', 'middle', 'ring']:
                start_jnt = '%s_%sBase_result_%s' % (side, finger, self.nc.joint)
                end_jnt = '%s_%s1_result_%s' % (side, finger, self.nc.joint)

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

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

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

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

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

                try:
                    cmds.parent(mid_hydraulic, '%s_hand_%s' % (side, self.nc.group))
                except Exception as err:
                    print err
示例#6
0
def myPrimer(myjtText,mycvText):
	#myjtText=cmds.textField('jtText',q=1,text=1)	
	#mycvText=cmds.textField('cvText',q=1,text=1)	
	#mypadInt=cmds.intField('padInt',q=1,v=1)
	mypadInt=3
	cmds.pointConstraint(myjtText,mycvText,n='tmpCt')
	cmds.delete('tmpCt')
	print myjtText
	print mycvText
	cmds.parent(mycvText,myjtText)
	i=0
	while(i<mypadInt):
		if(i==0):
			newname=[mycvText[0] + '_wa']
			topNode=newname

		else:
			newname=[mycvText[0] + '_pad']

		cmds.group(mycvText,n=newname[0])
		i=i+1
		print topNode
		
	cmds.select(topNode)
	cmds.parent(w=1)
	cmds.makeIdentity(mycvText,apply=1,t=1,r=1,s=1,n=0)
示例#7
0
    def create_plane_rig(self):
        nurb_name = "plane"

        cmds.group(n="{0}Rig_grp".format(nurb_name), em=True)
        plane_grp_dag = oopmaya.DAG_Node()

        cmds.group(n="{0}Controller_grp".format(nurb_name), em=True)
        controller_grp_dag = oopmaya.DAG_Node()

        cmds.nurbsPlane(n="{0}_nurb".format(nurb_name), p=[0, 0, 0], ax=[0, 1, 0], w=10, lr=1, d=3, u=4, v=1, ch=True)
        plane_nurb_dag = oopmaya.DAG_Node()

        soft_mod = cmds.softMod("{0}.cv[3][0:3]".format(plane_nurb_dag.name()))[0]
        soft_mod_handle_dag = oopmaya.DAG_Node()

        oopmaya.Maya_Controller(name="{0}Deformer_controller".format(nurb_name), shape="diamond_curve")
        controller_dag = oopmaya.DAG_Node()

        plane_nurb_dag.set_parent(plane_grp_dag)
        controller_grp_dag.set_parent(plane_grp_dag)
        controller_dag.set_parent(controller_grp_dag)
        soft_mod_handle_dag.set_parent(plane_nurb_dag)
        soft_mod_handle_dag.parent_constraint(controller_dag)

        controller_grp_dag.parent_constraint(plane_nurb_dag)
        controller_grp_dag.scale_constraint(plane_nurb_dag)

        soft_mod_handle_dag.hide()

        cmds.setAttr("{0}.relative".format(soft_mod), 1)
        cmds.setAttr("{0}.falloffAroundSelection".format(soft_mod), 0)

        cmds.select(plane_nurb_dag.name())
def CreateHydraulicRig(upDir, *args):

    selection = cmds.ls(sl=True)
    if len(selection) != 3:
        cmds.confirmDialog(icon = "warning!!", title = "Hydraulic Rig Tool", message = "You must select exactly 3 objects.  Top of hydraulic, bottom of hydraulic, and the up vector.")
        return
    else:
        hyd_start_01_anim = selection[0]
        hyd_start_02_anim = selection[1]
        upObject = selection[2]
        
        hyd_start_01 = hyd_start_01_anim.rpartition("_")[0]
        hyd_start_02 = hyd_start_02_anim.rpartition("_")[0]

        # Create a rig for the lower arm extra hydraulic piston.
        cmds.delete("driver_"+hyd_start_01+"_parentConstraint1")
        robo_lowarm_pistonrod_01_anim_sub = cmds.group(em=True, name=hyd_start_01_anim+"_sub", parent=hyd_start_01_anim)
        const = cmds.parentConstraint(hyd_start_01_anim, robo_lowarm_pistonrod_01_anim_sub, weight=1, mo=False)
        cmds.delete(const)
        const = cmds.parentConstraint(robo_lowarm_pistonrod_01_anim_sub, "driver_"+hyd_start_01, weight=1, mo=True)
        
        cmds.delete("driver_"+hyd_start_02+"_parentConstraint1")
        robo_lowarm_pistonrod_02_anim_sub = cmds.group(em=True, name=hyd_start_02_anim+"_sub", parent=hyd_start_02_anim)
        const = cmds.parentConstraint(hyd_start_02_anim, robo_lowarm_pistonrod_02_anim_sub, weight=1, mo=False)
        cmds.delete(const)
        const = cmds.parentConstraint(robo_lowarm_pistonrod_02_anim_sub, "driver_"+hyd_start_02, weight=1, mo=True)

        # Hook up the hydraulics for the lowerarm piston.
        const1 = cmds.aimConstraint(robo_lowarm_pistonrod_01_anim_sub, robo_lowarm_pistonrod_02_anim_sub, weight=1, mo=True, aimVector=(-1, 0, 0), upVector=(0, 0, upDir), worldUpType="object", worldUpVector=(0, 0, -1), worldUpObject=upObject)
        const2 = cmds.aimConstraint(robo_lowarm_pistonrod_02_anim_sub, robo_lowarm_pistonrod_01_anim_sub, weight=1, mo=True, aimVector=(1, 0, 0), upVector=(0, 0, upDir), worldUpType="object", worldUpVector=(0, 0, -1), worldUpObject=upObject)
    
    cmds.select(const1, const2)
def _createParentMaster(obj, translation=True, rotation=True):
    '''Crea i gruppi necessari per utilizzare il parent master.'''

    # creo il parent handle e lo snap group dell'oggetto (aventi stesso pivot)
    # un file referenziato genera eccezione
    if cmds.referenceQuery(obj, inr=True) and (not ALLOW_REFERENCE_ROOT or cmds.listRelatives(obj, p=True)):
        sys.stdout.write('Read-only hierarchy detected\n')
        msg = 'Are you working with referenced files?\n\nZVPM can\'t group "%s" because it\'s in a read-only hierarchy.\n\n\nDo the following:\n\n- Open the referenced file.\n- Select this object, right-click on "Attach objects" button and "Create parent groups".\n- Save the file.' % obj
        cmds.confirmDialog(title='Referenced file - ZV Parent Master', message=msg)
        return False

    piv = cmds.xform(obj, q=True, rp=True, ws=True)
    cmds.group(obj, n=_getSnapGroup(obj))
    cmds.xform(_getSnapGroup(obj), piv=piv, ws=True)
    ph = cmds.group(_getSnapGroup(obj), n=_getParentHandle(obj))
    cmds.xform(_getParentHandle(obj), piv=piv, ws=True)

    # locca gli attributi non diponibili e quelli non richiesti
    ts = set(['tx', 'ty', 'tz'])
    rs = set(['rx', 'ry', 'rz'])

    availAttrs = set(cmds.listAttr(obj, k=True, u=True, sn=True) or [])
    attrsToLock = (ts | rs) - availAttrs
    if not translation:
        attrsToLock |= ts
    if not rotation:
        attrsToLock |= rs

    for attr in attrsToLock:
        cmds.setAttr('%s.%s' % (ph, attr), lock=True)

    return True
示例#10
0
def switchRHand():
    ns = nameSpace(ns=cmds.ls(sl=1)[0])
    mlt = 3.0
    thumb = [ns + ':' + 'r_handThumb2_CTRL',
             ns + ':' + 'r_handThumb1_CTRL',
             ns + ':' + 'r_handThumb_CTRL',
             ns + ':' + 'r_handThumbBase_CTRL']
    th = fingerRig(name='Rthumb', obj=thumb, size=0.2, aim=[1, 0, 0], u=[0, 1, 0], mlt=mlt)

    index = [ns + ':' + 'r_handFingerA2Fk_CTRL',
             ns + ':' + 'r_handFingerA1Fk_CTRL',
             ns + ':' + 'r_handFingerA0Fk_CTRL',
             ns + ':' + 'r_handIk_CTRL']
    ind = fingerRig(name='Rindex', obj=index, size=0.2, aim=[1, 0, 0], u=[0, 1, 0], mlt=mlt)

    middle = [ns + ':' + 'r_handFingerB2Fk_CTRL',
              ns + ':' + 'r_handFingerB1Fk_CTRL',
              ns + ':' + 'r_handFingerB0Fk_CTRL',
              ns + ':' + 'r_handIk_CTRL']
    mid = fingerRig(name='Rmiddle', obj=middle, size=0.2, aim=[1, 0, 0], u=[0, 1, 0], mlt=mlt)

    ring = [ns + ':' + 'r_handFingerC2Fk_CTRL',
            ns + ':' + 'r_handFingerC1Fk_CTRL',
            ns + ':' + 'r_handFingerC0Fk_CTRL',
            ns + ':' + 'r_handIk_CTRL']
    rin = fingerRig(name='Rring', obj=ring, size=0.2, aim=[1, 0, 0], u=[0, 1, 0], mlt=mlt)

    pinky = [ns + ':' + 'r_handFingerD2Fk_CTRL',
             ns + ':' + 'r_handFingerD1Fk_CTRL',
             ns + ':' + 'r_handFingerD0Fk_CTRL',
             ns + ':' + 'r_handIk_CTRL']
    pin = fingerRig(name='Rpinky', obj=pinky, size=0.2, aim=[1, 0, 0], u=[0, 1, 0], mlt=mlt)

    # group
    cmds.group(th, ind, mid, rin, pin, n='__RIGHT_HAND__')
def rigFace() : 
    jntGrp = 'facialJnt_grp'

    if not mc.objExists(jntGrp) : 
        mc.group(em = True, n = jntGrp)

    facePolyMap = {'L_brow_ply': 'L_brow_ctrl',
                     'L_baseEye_ply': 'L_baseEye_ctrl', 
                     'L_eye_ply': 'L_eye_ctrl',
                     'R_brow_ply': 'R_brow_ctrl', 
                     'R_baseEye_ply': 'R_baseEye_ctrl', 
                     'R_eye_ply': 'R_eye_ctrl', 
                     'nose_ply': 'noseface_ctrl', 
                     'mouth_ply': 'mount_ctrl'
                     }

    for each in facePolyMap : 
        poly = each
        ctrl = facePolyMap[poly]

        if mc.objExists(poly) : 

            movePivot(ctrl, poly)

            joint = mc.createNode('joint', n = poly.replace('_ply', '_jnt'))
            mc.delete(mc.pointConstraint(poly, joint))
            mc.skinCluster(poly, joint, tsb = True)
            mc.parentConstraint(ctrl, joint)
            mc.scaleConstraint(ctrl, joint)

            mc.parent(joint, jntGrp)
示例#12
0
文件: mdc.py 项目: ivanzotov/mdc
def prepare(setname="cache_set", groupname="cache_group", prefix="cache_"):
    selection = cmds.ls(sl=True, l=True)
    
    if len(selection) == 0:
        cmds.warning("Please select objects!")
        return
        
    cmds.duplicate()
    dup = cmds.ls(sl=True, l=True)
    
    if cmds.objExists(groupname):
        cmds.parent(dup, groupname)
    else:
        cmds.group(w=True, n=groupname)
    
    cmds.select(groupname)
    dup = get_shapes()
    add_to_set_of_shapes(setname, dup)
    
    i = 0
    for obj in dup:
        cmds.blendShape([selection[i], obj], w=(0, 1),o="world", foc=True)
        objects = []
        objects.append(obj)
        addattr(objects, prefix+str(i))
        i=i+1
示例#13
0
def setRestCurve( startCurves ):
    
    restCurves = []
    index = 0
    for startCurve in startCurves:
        
        follicle = cmds.listConnections( startCurve+'.wm', type='follicle', shapes=1 )[0]
        
        if cmds.listConnections( follicle+'.restPosition', s=1, d=0 ): continue
        
        startShape = cmds.listConnections( follicle+'.startPosition', s=1, d=0, shapes=1 )[0]
        
        rebuildCurve= cmds.listConnections( startShape+'.create', type='rebuildCurve' )[0]
        
        crvShape = cmds.createNode( 'nurbsCurve' )
        cmds.connectAttr( rebuildCurve+'.outputCurve', crvShape+'.create' )
        cmds.connectAttr( crvShape+'.worldSpace', follicle+'.restPosition' )
        cmds.setAttr( crvShape+'.io', 1 )
        
        crv = cmds.listRelatives( crvShape, p=1 )[0]
        crv = cmds.rename( crv, 'restCurve_%03d' % index )
        
        startMtx = cmds.getAttr( crv+'.wm' )
        cmds.xform( crv, ws=1, matrix=  startMtx )
        
        restCurves.append( crv )
        index += 1
    
    cmds.group( restCurves, n='restCurveGrps' )
示例#14
0
def createControl(ctrlinfo):
    control_info = []
    for info in ctrlinfo:
        # Create ik control
        # Get ws position of the joint
        pos = info[0]
        # Create circle control object
        ctrl_file = os.environ["AR_DATA"]+ 'controls/' + info[2]
 
         # Import a control object
        cmds.file(ctrl_file, i=True)
        ctrl = info[1]
        ctrlgrp = info[1] + '_GRP'
        if cmds.objExists('grp_control') == True:
            cmds.rename('grp_control', ctrlgrp )
            cmds.rename('control', ctrl)
        
        mgrp = cmds.group(n=info[1] + '_MOCAP', em=True)
        zgrp = cmds.group(n=info[1] + '_ZERO')
        cmds.parent(ctrlgrp, mgrp)
        # Move the group to the joint
        cmds.xform(zgrp, t=pos, ws=True)
        control_info.append([ctrlgrp, ctrl, zgrp, mgrp])

        # Lock Attrs
        for attr in info[3]:
            cmds.setAttr(ctrl+attr, channelBox=False, lock=True)
    return(control_info)
示例#15
0
def createLightStageLights(lightingDir):
	diameterIn = 4
	distanceToFrontIn = 55

	lightData = readLights(lightingDir)
	for dict, value in lightData.iteritems():
	    print( dict )
	    print( value )

	lightDirections = lightData['directions']
	lightPolarizations = lightData['polarization']
	lightConfigurations = lightData['configurations']

	lightsPolarized = []
	lightsUnpolarized = []
	for lightNumber, lightDirection in lightDirections.iteritems():
	    print( lightNumber, lightDirection )
	    if lightPolarizations[lightNumber] == 0:
	        name = "lightStageLightUnPolarized" + str(lightNumber)
	        lightsPolarized.append( createLightStageLight(name, lightDirection, diameterIn, distanceToFrontIn) )
	        setLightConfigurationVisibility(lightConfigurations, lightNumber, name)
	    else:    
	        name = "lightStageLightPolarized" + str(lightNumber)
	        lightsUnpolarized.append( createLightStageLight(name, lightDirection, diameterIn, distanceToFrontIn) )
	        setLightConfigurationVisibility(lightConfigurations, lightNumber, name)

	polarizedLightsGroup = cmds.group( lightsPolarized, name="polarizedLights" )
	unpolarizedLightsGroup = cmds.group( lightsUnpolarized, name="polarizedLights" )
	lightStageGroup = cmds.group( [polarizedLightsGroup, unpolarizedLightsGroup], name="lightStageLights" )

	return lightStageGroup
示例#16
0
def	postProcessControl	(	_control,	_function,	_controlled	):	# <<< string, string, list
	lockHideAttributes	(	_control	)

	if (cmds.objExists('anim_control_set') == False):	cmds.createNode('objectSet',name='anim_control_set',skipSelect=True)

	cmds.sets	(	_control,	addElement	=	'anim_control_set'	)
	cmds.toggle	(	localAxis				=	1	)

	if	len	(	_controlled	)	==	0:
		_control	=	cmds.rename	(	'_'	+	_function	+	'_control'	)
		_control	=	cmds.group	( 	world	=	1,	name	=	'_'	+	_function	+	'_control_offSet'	)
		cmds.move					(	0,	0,	0,	_control	+	'.rotatePivot',	_control	+	'.scalePivot'	)

		lockHideAttributes	(	_control	)

	else:
		_k				=	_controlled[0].rfind	(	'|'	)
		_control		=	_controlled[0][_k+1:]
		cmds.rename		(	_control	+	'_'	+	_function	+	'_control'	)
		_control		=	cmds.group	(	world	=	1,	name	=	_control	+	'_'	+ _function	+	'_control_offSet'	)
		cmds.move			(	0, 0, 0, _control + '.rotatePivot', _control + '.scalePivot' )

		lockHideAttributes	(	_control	)

		cmds.select		(	_controlled[0],	toggle	=	True	)
		cmds.parent		()
		cmds.xform		(	translation	=	(	0,	0,	0	),	rotation	=	(	0,	0,	0	)	)
		cmds.parent		(	world		= 	1	)
	
	cmds.pickWalk	(	direction	=	"down"	)
示例#17
0
        def blueprint(self,**kwargs):
			"""
				Creates a joint chain can be used for spine
			"""
			
			# create registries
			self.createRegistry("regBlueprintTransform")
			self.createRegistry("regBlueprintShape")
			
			# get blueprint attributes
			jointNo= int(self.blueprintAttributes["Joint number"].value)
			
			#create module top group
			rootGrp = cmds.group( n = (self.name + "Blueprint_GRP"), em = True )
			jointGrp = cmds.group( n = (self.name + "BlueprintJoint_GRP"), em = True, p = rootGrp )
			
			# create blueprinters
			spineChainData = Util.createBlueprinterChain( (self.name + "SpineChainBlueprinter"), {"chainNo": jointNo})
			spineChainJoints = spineChainData["jnt"]
			spineChainSctls = spineChainData["sctl"]
			
			cmds.parent(spineChainJoints[0], jointGrp)
			cmds.parent(spineChainData["root"], rootGrp)
			
			cmds.parent(rootGrp, self.rootGrp)
			
			# store joints and controls
			self.storeBlueprinterJoints( spineChainJoints )
			self.storeBlueprinterControls( spineChainSctls )
			
			# register Blueprinters
			self.registerObjects(Util.createSingleArray(spineChainSctls), "regBlueprintTransform")
示例#18
0
文件: pkTools.py 项目: myCodeTD/pkmel
def friendsAttachSkirtFix( name='' ) :
	
	geo = mc.ls( '*:%sFixGeo_grp' % name )[0]
	jnt = mc.ls( '*:%sFixJnt_grp' % name )[0]
	rig = mc.ls( '*:%sFixRig_grp' % name )[0]
	
	rootZro = mc.ls( '*:%sFix*RootCtrlZro_grp' % name )[0]
	
	animGrp = mc.ls( '*:anim_grp' )[0]
	stillGrp = mc.ls( '*:still_grp' )[0]
	pelvis = mc.ls( '*:pelvis_jnt' )[0]
	
	addRig = 'addRig_grp'
	
	if not mc.objExists( addRig ) :
		mc.group( em=True , n=addRig )
	
	mc.parent( geo , addRig )
	mc.parent( jnt , addRig )
	mc.parent( rig , addRig )
	
	mc.parentConstraint( stillGrp , geo , mo=True )
	mc.scaleConstraint( stillGrp , geo , mo=True )
	mc.parentConstraint( stillGrp , jnt , mo=True )
	mc.scaleConstraint( stillGrp , jnt , mo=True )
	mc.parentConstraint( animGrp , rig , mo=True )
	mc.scaleConstraint( animGrp , rig , mo=True )
	
	#skirtC_Rig:skirtCFixRootCtrlZro_grp
	mc.parentConstraint( pelvis , rig , mo=True )
	
	mc.setAttr( '%s.v' % jnt , 0 )
	mc.setAttr( '%s.v' % geo , 0 )
示例#19
0
文件: pkTools.py 项目: myCodeTD/pkmel
def friendsAddSpineOri() :
	
	# Create spine orientation to the selected control
	# Select control and world orientation group then run the script
	ctrl , worGrp = mc.ls( sl=True )
	
	mc.addAttr( ctrl , ln='headSpine' , min=0 , max=1 , k=True )
	
	sides = ( 'LFT' , 'RGT' , 'Back' )
	currSide = '_'
	
	for side in sides :
		
		if side in ctrl :
			currSide = '%s_' % side
	
	name = ctrl.split( currSide )[0]
	
	#worGrp = 'hairAWorOri%sgrp' % currSide
	ctrlOriGrp = '%sCtrlOri%sgrp' % ( name , currSide )
	
	oriGrp = '%sSpineOri%sgrp' % ( name , currSide )
	mc.group( ctrl , n=oriGrp )
	
	rev = mc.createNode( 'reverse' , n='%sSpineOri%s_rev' % ( name , currSide ) )
	
	parCon = mc.parentConstraint( ctrlOriGrp , worGrp , oriGrp , mo=True )[0]
	
	mc.connectAttr( '%s.headSpine' % ctrl , '%s.ix' % rev )
	mc.connectAttr( '%s.headSpine' % ctrl , '%s.w1' % parCon )
	mc.connectAttr( '%s.ox' % rev , '%s.w0' % parCon )
    def __init__(self, **keywords):
        """ Perform entire setup. """
        if not keywords.has_key("drivectrl"):
            raise Exception("No drive control passed in by caller.")
        drivectrl = keywords["drivectrl"]
        if not keywords.has_key("attrctrl"):
            raise Exception("No attribute control passed in by caller.")
        attrctrl = keywords["attrctrl"]
        if not keywords.has_key("driven"):
            raise Exception("No driven object passed in by caller.")
        driven = keywords["driven"]
        if not keywords.has_key("radius"):
            raise Exception("No radius passed in by caller.")
        radius = keywords["radius"]

        # Setup heirarchy
        try:
            cmds.select(driven, r=True)
            rGrp = cmds.group(n="%s_RotationSpinGrp" % drivectrl)
            cmds.select(rGrp, r=True)
            tGrp = cmds.group(n="%s_TransformSpinGrp" % drivectrl)
            cmds.select(tGrp, r=True)
            rootGrp = cmds.group(n="%s_SpinTopGrp" % drivectrl)

            cmds.parent(drivectrl, rootGrp)

        except Exception, e:
            raise Exception(e)
示例#21
0
文件: pkTools.py 项目: myCodeTD/pkmel
def friendsBeachRig() :
	
	for each in mc.ls( sl=True ) :
    
		currName = each.split( '_' )[0]
		
		ctrl = pc.Control( 'circle' )
		ctrl.name = '%s_ctrl' % currName
		ctrl.color = 'red'
		ctrl.attr( 'v' ).lock = True
		ctrl.attr( 'v' ).hide = True
		ctrl.scaleShape( 7 )
		grp = pc.group( ctrl )
		grp.snap( each )
		grp.name = '%sCtrlZro_grp' % currName
		
		geoZro = mc.listRelatives( each , p=True )[0]
		geoGrp = mc.listRelatives( geoZro , p=True )[0]
		rigGrp = geoGrp.replace( 'Geo_' , 'Rig_' )
		
		if not mc.objExists( rigGrp ) :
			mc.group( em=True , n=rigGrp )
		
		mc.parentConstraint( ctrl , geoZro , mo=True)
		mc.scaleConstraint( ctrl , geoZro , mo=True )
		mc.parent( grp , rigGrp )
示例#22
0
    def OrganizeLimb(self, limbObject, Name, Side, ObjectAttached, deformationParent):
        limbKinematics = cmds.group(empty=True, name=Name + "Kinematics")
        limbKinematics = self.NameConv.RMRenameNameInFormat(limbKinematics, Side=Side, System="kinematics")
        limbControls = cmds.group(empty=True, name=Name + "Controls")
        limbControls = self.NameConv.RMRenameNameInFormat(limbControls, Side=Side, System="controls")
        limbJoints = cmds.group(empty=True, name=Name + "Joints")
        limbJoints = self.NameConv.RMRenameNameInFormat(limbJoints, Side=Side, System="joints")

        cmds.parent(limbKinematics, self.kinematics)
        cmds.parent(limbControls, self.mainMover)
        cmds.parent(limbJoints, self.joints)

        RMRigTools.RMParentArray(limbKinematics, limbObject.kinematics)

        cmds.parent(limbObject.limbMover, limbJoints)

        cmds.parentConstraint(ObjectAttached, limbObject.limbMover, mo=True)

        cmds.parent(limbObject.IKControls, limbControls)
        cmds.parent(limbObject.FKControls, limbControls)
        cmds.parent(limbObject.ResetSpaceSwitchControl, limbControls)

        cmds.parent(limbObject.TJArm.TwistControlResetPoint, limbControls)
        cmds.parent(limbObject.TJArm.TwistResetJoints, deformationParent)
        cmds.parent(limbObject.TJElbow.TwistControlResetPoint, limbControls)
        # No es necesario emparentar las Twist delelbow dado que fueron emparentadas dentro de la classe Limb al momento de creacion
        RMRigTools.RMParentArray(limbKinematics, limbObject.TJArm.kinematics)
        RMRigTools.RMParentArray(limbKinematics, limbObject.TJElbow.kinematics)

        return {"kinematics": limbKinematics, "controls": limbControls, "joints": limbJoints}
示例#23
0
def createDistanceNode(**kwargs):
    
    startTransform = kwargs.get('start')
    endTransform = kwargs.get('end')
    name = kwargs.get('name')
    
    startPos = cmds.xform(startTransform,q = True,ws = True, translation = True)
    endPos = cmds.xform(endTransform,q = True,ws = True, translation = True)
    
    group = cmds.group(empty = True, name = '%s_Locator_Group'%name)
    startGroup = cmds.group(empty = True, name = '%s_Start_Locator_Group'%name)
    endGroup = cmds.group(empty = True, name = '%s_End_Locator_Group'%name)
    
    cmds.parent(startGroup,group)
    cmds.parent(endGroup,group)
    
    startLocator = cmds.spaceLocator(name = '%s_Start_Locator'%name)[0]
    endLocator = cmds.spaceLocator(name = '%s_End_Locator'%name)[0]
    
    cmds.parent(startLocator,startGroup)
    cmds.parent(endLocator,endGroup)
    
    cmds.move(startPos[0],startPos[1],startPos[2],startLocator,ws = True)
    cmds.move(endPos[0],endPos[1],endPos[2],endLocator,ws = True)
    
    lengthNode = cmds.createNode('kLengthNode',name = '%s_Length'%name)
    
    cmds.connectAttr('%s.worldMatrix[0]'%startLocator, '%s.startWorldMatrix'%lengthNode)
    cmds.connectAttr('%s.parentInverseMatrix[0]'%startLocator, '%s.startParentInverseMatrix'%lengthNode)
    
    cmds.connectAttr('%s.worldMatrix[0]'%endLocator, '%s.endWorldMatrix'%lengthNode)
    cmds.connectAttr('%s.parentInverseMatrix[0]'%endLocator, '%s.endParentInverseMatrix'%lengthNode)
    
    return lengthNode
	def attachGeoToBlueprint_parenting(self,blueprintJoint,geometry):
		jointName = utils.stripAllNamespaces(blueprintJoint)[1]
		parentGroup = cmds.group(empty=True,n=jointName + '_geoAttach_parentGrp#')
		
		if len(geometry) == 1:
			geoParent = cmds.listRelatives(geometry,parent=True)
			if geoParent != None:
				cmds.parent(parentGroup, geoParent)
				
		cmds.parentConstraint(blueprintJoint,parentGroup, maintainOffset=False,n=parentGroup+'_parentConstraint')
		cmds.scaleConstraint(blueprintJoint,parentGroup, maintainOffset=False,n=parentGroup+'_scaleConstraint')
		
		geoParent = parentGroup
		
		children = cmds.listRelatives(blueprintJoint, children=True)
		children = cmds.ls(children,type='joint')
		
		if len(children) != 0:
			childJoint = children[0]
			
			scaleGroup = cmds.group(empty=True, n=jointName+'_geoAttach_scaleGrp#')
			cmds.parent(scaleGroup,parentGroup,relative=True)
			
			geoParent = scaleGroup
			
			originalTxValue = cmds.getAttr(childJoint + '.translateX')
			scaleFactor = cmds.shadingNode('multiplyDivide', asUtility=True, n=scaleGroup+'_scaleFactor')
			cmds.setAttr(scaleFactor+'.operation',2)#divide
			cmds.connectAttr(childJoint+'.translateX',scaleFactor+'.input1X')
			cmds.setAttr(scaleFactor+'.input2X', originalTxValue)
			
			cmds.connectAttr(scaleFactor+'.outputX',scaleGroup+'.scaleX')
			
		for geo in geometry:
			cmds.parent(geo,geoParent,absolute=True)
示例#25
0
def makeFloatingJoints(locators = [],name = ''):
    
    joints = []
    jointsGroup = cmds.group(n = '%s_Jnt_Grp'%name,empty = True)
    
    i = 1
    
    for locator in locators:
        
        zeroString = '0'
        
        if i > 9:
            zeroString = ''
        
        group = cmds.group(empty = True, name = '%s_%s%i_Grp'%(name,zeroString,i))
        cmds.parentConstraint(locator,group)
        cmds.select(cl = True)
        joint = cmds.joint(name = '%s_Floating_%s%i_Jnt'%(name,zeroString,i))
        cmds.parent(joint,group)
        cmds.move(0,0,0,joint,os = True) 
        cmds.setAttr('%s.jointOrientX'%joint,0)
        cmds.setAttr('%s.jointOrientY'%joint,0)
        cmds.setAttr('%s.jointOrientZ'%joint,0)
        joints.append(joint)
        cmds.parent(group,jointsGroup)
        
        i += 1
        
    return joints
示例#26
0
 def axisPanelCreate(self , planeName , cur , axis):
         CurveEps = mc.ls(cur + '.ep[:]',fl = True)
         CurveCvs = mc.ls(cur + '.cv[:]',fl = True)
         cvworlds = []
         if axis == 'auto':
                 for i in range(len(CurveCvs)):
                         cv = CurveCvs[i]
                         cvworld = mc.xform(cv,q = True,ws = True,t = True)
                         cvworlds.append(cvworld)
                 axisFacet = mc.polyCreateFacet(p = cvworlds,ch = False,name = planeName + '_axis_Facet')[0]
         else:
                 curOffsetGrp = mc.group(em = True,name = planeName + '_axisPanelOffset')
                 curOffsetZero = mc.group(curOffsetGrp,name = curOffsetGrp + '_zero')
                 axisCurve01 = mc.duplicate(cur)[0]
                 axisCurve02 = mc.duplicate(cur)[0]
                 mc.parent(axisCurve01,curOffsetGrp)
                 mc.setAttr(curOffsetGrp + '.t' + axis,1)
                 mc.parent(axisCurve01,w = True)
                 mc.parent(axisCurve02,curOffsetGrp)
                 mc.setAttr(curOffsetGrp + '.t' + axis,0)
                 mc.parent(axisCurve02,w = True)
                 axisFacet = mc.loft(axisCurve01,axisCurve02,ch = 1,u = 1,c = 0,ar = 1,d = 3,ss = 1,rn = 0,po = 1,rsn = True,name = planeName + '_axis_Facet')[0]
                 mc.select(axisFacet)
                 mc.DeleteHistory()
                 mc.setAttr(curOffsetGrp + '.t' + axis,1)
                 mc.delete(curOffsetZero,axisCurve01,axisCurve02)
         return axisFacet
示例#27
0
def zGrp(obj = '', mode = '') : 
	results = []

	if obj == '' : 
		obj = mc.ls(sl = True)[0]

	name = obj
	elements = name.split('_')
	capElements = []

	i = 0
	for eachElement in elements : 
		if not i == 0 : 
			capElements.append(eachElement.capitalize())

		else : 
			capElements.append(eachElement)

		i+=1

	newName = '%s_zGrp' % ('').join(capElements)
	offsetGrpName = '%s_offsetGrp' % ('').join(capElements)

	groupName = mc.group(obj, n = newName)
	offsetGroupName = ''

	if mode == 'offset' : 
		offsetGroupName = mc.group(groupName, n = offsetGrpName)

	return groupName, offsetGroupName
示例#28
0
def groupGeneratedLocators():
    log('selecting created locators')
    
    locs = cmds.ls(type="locator")   
    if locs:
        cmds.select(locs)
        cmds.group(name="debug_locs")
示例#29
0
def createControllerOnTarget( target, pivotCtlOn=True ):

    import sgBFunction_connection
    import sgBFunction_dag
    import sgBModel_data
    targetPos = cmds.getAttr( target+'.wm' )
    targetP = cmds.listRelatives( target, p=1, f=1 )[0]
    
    targetName = target.split( '|' )[-1]
    ctl = cmds.circle( n='CTL_' + targetName )[0]
    ctlChild = cmds.createNode( 'transform', n='CTLChild_'+targetName );ctlChild = cmds.parent( ctlChild, ctl )[0]
    pivCtl = cmds.createNode( 'transform', n='PivCTL_'+targetName  ); cmds.setAttr( pivCtl+'.dh', 1 )
    cmds.setAttr( pivCtl+'.overrideEnabled', 1 )
    cmds.setAttr( pivCtl+'.overrideColor', 18 )
    ctlP = cmds.group( ctl, n='P'+ctl )
    ctlPPiv = cmds.group( ctlP, pivCtl, n='Piv' + ctlP )
    cmds.xform( ctlPPiv, ws=1, matrix=targetPos )

    cloneObject = sgBFunction_dag.getConstrainedObject( targetP )
    ctlPPiv = cmds.parent( ctlPPiv, cloneObject )[0]
    cmds.xform( pivCtl, os=1, matrix= sgBModel_data.getDefaultMatrix() )
    
    ctl = cmds.listRelatives( ctlP, c=1, f=1 )[0]
    sgBFunction_connection.getSourceConnection( target, ctlPPiv )

    for attr in [ 't', 'tx', 'ty', 'tz', 'r', 'rx', 'ry', 'rz', 's', 'sx', 'sy', 'sz', 'sh' ]:
        cons = cmds.listConnections( target+'.'+attr, s=1, d=0, p=1, c=1 )
        if not cons: continue
        for i in range( 0, len( cons ), 2 ):
            cmds.disconnectAttr( cons[i+1], cons[i] )
    
    sgBFunction_connection.constraintAll( ctlChild, target )
    
    cmds.connectAttr( pivCtl+'.t',  ctlP+'.t' )
    cmds.connectAttr( pivCtl+'.r',  ctlP+'.r' )
    cmds.connectAttr( pivCtl+'.s',  ctlP+'.s' )
    cmds.connectAttr( pivCtl+'.sh', ctlP+'.sh' )
    
    mmdcCtlChild = cmds.createNode( 'multMatrixDecompose' )
    cmds.connectAttr( ctlPPiv+'.wm', mmdcCtlChild+'.i[0]' )
    cmds.connectAttr( pivCtl+'.wim', mmdcCtlChild+'.i[1]' )
    cmds.connectAttr( mmdcCtlChild+'.ot',  ctlChild+'.t' )
    cmds.connectAttr( mmdcCtlChild+'.or',  ctlChild+'.r' )
    cmds.connectAttr( mmdcCtlChild+'.os',  ctlChild+'.s' )
    cmds.connectAttr( mmdcCtlChild+'.osh', ctlChild+'.sh' )
    
    ctlShape = sgBFunction_dag.getShape( ctl )
    circleNode = cmds.listConnections( ctlShape+'.create', s=1, d=0 )[0]
    
    mm = cmds.createNode( 'multMatrix' )
    trGeo = cmds.createNode( 'transformGeometry' )
    
    cmds.connectAttr( ctlPPiv+'.wm', mm+'.i[0]' )
    cmds.connectAttr( pivCtl+'.wim', mm+'.i[1]' )
    
    cmds.connectAttr( circleNode+'.outputCurve', trGeo+'.inputGeometry' )
    cmds.connectAttr( mm+'.matrixSum', trGeo+'.transform' )
    cmds.connectAttr( trGeo+'.outputGeometry', ctlShape+'.create', f=1 )
    
    return ctl
def set_empty_page():
    """Sets the current frame as an empty page.

    :returns: None.
    :raises: None.
    """
    # Then group the objects into their own page. The page number is dictated
    # by the current frame:
    current_frame = cmds.currentTime(query=True)
    page_name = "page_%04d" % (current_frame)

    if not cmds.objExists(page_name):

        cmds.group(name=page_name, empty=True)

        # Add the visibility override attribute to the group name:
        cmds.addAttr(page_name, longName="visibilityOverride", attributeType="bool")
        cmds.setKeyframe(page_name + ".visibilityOverride", time=1, value=0)

        # Set the key for this page and insert the page number into the attribute
        # on the flipbook node:
        _update_flipbook_node(page_name, current_frame)

    # Return
    return
def upperIKTwist(color, suffix, name, prefix, upperJnt, lowerJnt, sysGroup):
    print "START Building the " + suffix + " " + upperJnt + " UPPER IK twists---------------------------------------"

    #create a nice name
    name = prefix + name + suffix
    if name.find("_") == 0:
        name = name.partition("_")[2]

        # define the joints for this rig.
        upperjnt = prefix + upperJnt + suffix
        lowerjnt = prefix + lowerJnt + suffix
        #OLD - upperjnt_parent = "driver_" + prefix + "clavicle" + suffix
        upperjnt_parent = cmds.listRelatives(upperjnt, p=True)[0]
        driver_upperjnt = "driver_" + prefix + upperJnt + suffix
        driver_lowerjnt = "driver_" + prefix + lowerJnt + suffix

        numRolls = 0
        for joint in [
                "_twist_01", "_twist_02", "_twist_03", "_twist_04",
                "_twist_05", "_twist_06"
        ]:
            if cmds.objExists("driver_" + prefix + upperJnt + joint + suffix):
                numRolls = numRolls + 1

        print "...There are a total of " + str(numRolls) + " to build."

        for i in range(int(numRolls)):
            print "...Building upper twist_0" + str(i + 1)

            upperjnt_twist = prefix + upperJnt + "_twist_0" + str(i +
                                                                  1) + suffix
            driver_upperjnt_twist = "driver_" + prefix + upperJnt + "_twist_0" + str(
                i + 1) + suffix

            ####################################
            # Create a master group for the roll controls to be parented to.
            rollGrp = cmds.group(empty=True,
                                 name=upperjnt + "_roll_grp_0" + str(i + 1))
            cmds.parent(rollGrp, sysGroup)
            cmds.parentConstraint(upperjnt_parent, rollGrp, mo=True)

            # Create the manual twist control
            if i == 0:
                twistCtrl = utils.createControl("circle", 15,
                                                upperjnt + "_twist_anim")
            else:
                twistCtrl = utils.createControl(
                    "circle", 15, upperjnt + "_twist" + str(i + 1) + "_anim")
            cmds.setAttr(twistCtrl + ".ry", -90)
            cmds.setAttr(twistCtrl + ".sx", 0.8)
            cmds.setAttr(twistCtrl + ".sy", 0.8)
            cmds.setAttr(twistCtrl + ".sz", 0.8)
            cmds.makeIdentity(twistCtrl, r=1, s=1, apply=True)

            # move the manual control to the correct location
            constraint = cmds.parentConstraint(driver_upperjnt_twist,
                                               twistCtrl)[0]
            cmds.delete(constraint)

            # create a group for the manual control and parent the twist to it.
            twistCtrlGrp = cmds.group(empty=True, name=twistCtrl + "_grp")
            constraint = cmds.parentConstraint(driver_upperjnt_twist,
                                               twistCtrlGrp,
                                               mo=False)[0]
            cmds.delete(constraint)
            twistCtrlDeltoidOffsetGrp = cmds.group(empty=True,
                                                   name=twistCtrl +
                                                   "_deltOffset_grp")
            constraint = cmds.parentConstraint(driver_upperjnt_twist,
                                               twistCtrlDeltoidOffsetGrp,
                                               mo=False)[0]
            cmds.delete(constraint)
            cmds.parent(twistCtrl, twistCtrlDeltoidOffsetGrp)
            cmds.parent(twistCtrlDeltoidOffsetGrp, twistCtrlGrp)
            cmds.parent(twistCtrlGrp, rollGrp)
            cmds.makeIdentity(twistCtrl, t=1, r=1, s=1, apply=True)

            # set the manual controls visibility settings
            cmds.setAttr(twistCtrl + ".overrideEnabled", 1)
            cmds.setAttr(twistCtrl + ".overrideColor", color)
            for attr in [".sx", ".sy", ".sz"]:
                cmds.setAttr(twistCtrl + attr, lock=True, keyable=False)
            cmds.setAttr(twistCtrl + ".v", keyable=False)

            # add attr on rig settings for manual twist control visibility
            cmds.select("Rig_Settings")
            if i == 0:
                cmds.addAttr(longName=(upperjnt + "_twistCtrlVisUpper"),
                             at='bool',
                             dv=0,
                             keyable=True)
            cmds.connectAttr("Rig_Settings." + upperjnt + "_twistCtrlVisUpper",
                             twistCtrl + ".v")

            # add attr to rig settings for the twist ammount values
            cmds.select("Rig_Settings")
            cmds.addAttr(longName=(upperjnt + "_Twist" + str(i + 1) +
                                   "Amount"),
                         defaultValue=0.5,
                         minValue=0,
                         maxValue=1,
                         keyable=True)
            for u in range(int(i + 1)):
                cmds.setAttr(
                    "Rig_Settings." + upperjnt + "_Twist" + str(u + 1) +
                    "Amount", (1.0 / (i + 2.0) * ((2.0 - u) + (i - 1.0))))

            ####################################
            # Create the twist rig on the shoulder without any extra controls.  Those are added later.
            cmds.delete(upperjnt_twist + "_orientConstraint1")

            twistIKHandle = cmds.ikHandle(name="twistIKHandle_0" + str(i + 1) +
                                          "_" + upperjnt,
                                          sol="ikRPsolver",
                                          sj=upperjnt,
                                          ee=upperjnt_twist)[0]
            print "TWIST IK HANDLE IS: " + twistIKHandle
            cmds.setAttr(twistIKHandle + ".poleVectorX", 0)
            cmds.setAttr(twistIKHandle + ".poleVectorY", 0)
            cmds.setAttr(twistIKHandle + ".poleVectorZ", 0)
            cmds.parent(twistIKHandle, driver_upperjnt)

            driver_upperjnt_offset = cmds.duplicate(driver_upperjnt,
                                                    po=True,
                                                    name="driver_" + upperJnt +
                                                    "_twistOffset_l")[0]
            cmds.parent(driver_upperjnt_offset, driver_upperjnt)

            twistOrntConst = cmds.orientConstraint(driver_upperjnt,
                                                   upperjnt,
                                                   driver_upperjnt_offset,
                                                   mo=True)[0]
            cmds.setAttr(twistOrntConst + ".interpType", 2)

            twistMDNode = cmds.shadingNode("multiplyDivide",
                                           asUtility=True,
                                           name=driver_upperjnt_twist +
                                           "_MDnode")
            cmds.setAttr(twistMDNode + ".input2X", 1)
            cmds.setAttr(twistMDNode + ".input2Y", -1)

            cmds.connectAttr(driver_upperjnt_offset + ".rotateX",
                             twistMDNode + ".input1X",
                             force=True)
            cmds.connectAttr(driver_upperjnt + ".rotateX",
                             twistMDNode + ".input1Y",
                             force=True)
            cmds.connectAttr(twistMDNode + ".outputX",
                             driver_upperjnt_twist + ".rx",
                             force=True)
            cmds.connectAttr(twistMDNode + ".outputY",
                             twistCtrlDeltoidOffsetGrp + ".rx",
                             force=True)

            cmds.pointConstraint(driver_upperjnt_twist, twistCtrlGrp, mo=True)
            cmds.orientConstraint(driver_upperjnt_twist, twistCtrlGrp, mo=True)

            cmds.orientConstraint(twistCtrl, upperjnt_twist, mo=True)

            if cmds.objExists("deltoid_anim" + suffix):
                if suffix == "_l":
                    cmds.connectAttr("deltoid_anim" + suffix + ".rotateX",
                                     twistIKHandle + ".twist",
                                     force=True)
                else:
                    deltMDNode = cmds.shadingNode("multiplyDivide",
                                                  asUtility=True,
                                                  name=twistIKHandle +
                                                  "_MDNode")
                    cmds.setAttr(deltMDNode + ".input2X", -1)
                    cmds.connectAttr("deltoid_anim" + suffix + ".rotateX",
                                     deltMDNode + ".input1X",
                                     force=True)
                    cmds.connectAttr(deltMDNode + ".outputX",
                                     twistIKHandle + ".twist",
                                     force=True)

            reverseMDNode = cmds.shadingNode("reverse",
                                             asUtility=True,
                                             name=driver_upperjnt_offset +
                                             "_Reversenode")
            cmds.connectAttr("Rig_Settings." + upperjnt + "_Twist" +
                             str(i + 1) + "Amount",
                             reverseMDNode + ".inputX",
                             force=True)
            cmds.connectAttr(reverseMDNode + ".outputX",
                             twistOrntConst + "." + upperjnt + "W1",
                             force=True)
            cmds.connectAttr("Rig_Settings." + upperjnt + "_Twist" +
                             str(i + 1) + "Amount",
                             twistOrntConst + "." + driver_upperjnt + "W0",
                             force=True)

    print ".END Building the " + suffix + " " + upperJnt + " UPPER twists---------------------------------------"
示例#32
0
def armoireUp():

    #group MODULE
    mir = random.randint(0, 19)
    crazyR = random.randint(0, 1000)
    mName = 'MODULE' + str(mir) + str(crazyR)
    uName = 'MEUBLE_UP' + str(mir) + str(crazyR)
    # planche_height = 5
    # planche_width = 0.1
    # planche_depth = 2
    # module_width = 4
    # number_modules = 3
    planche_height = cmds.intSliderGrp(slider1, q=True, value=True)
    planche_width = cmds.floatSliderGrp(slider2, q=True, value=True)
    planche_depth = cmds.intSliderGrp(slider3, q=True, value=True)
    module_width = cmds.intSliderGrp(slider4, q=True, value=True)
    number_modules = cmds.intSliderGrp(slider5, q=True, value=True)

    #group MODULE

    cmds.group(n=mName, em=True)
    cmds.group(n=uName, em=True)

    #laterales
    for i in range(0, 2):
        planche = cmds.polyCube(h=planche_height,
                                w=planche_width,
                                depth=planche_depth)
        cmds.polyBevel3(offset=0.02)
        cmds.move(-i * module_width + module_width / 2.0, planche_height / 2.0,
                  0)
        cmds.parent(planche, mName, relative=True)
    #superior - inferior
    for i in range(0, 3):
        placheUpDown = cmds.polyCube(h=planche_width,
                                     w=module_width,
                                     depth=planche_depth)
        cmds.polyBevel3(offset=0.02)
        cmds.move(0, i * planche_height / 2.0, 0)
        cmds.parent(placheUpDown, mName, relative=True)
    #puerta
    puerta = cmds.polyCube(h=planche_height + planche_width,
                           w=module_width + planche_width,
                           depth=planche_width * 2.0)
    cmds.polyBevel3(offset=0.03)
    cmds.move(0, planche_height / 2.0,
              planche_depth / 2.0 + planche_width / 2.0)
    cmds.parent(puerta, mName, relative=True)

    #respaldo
    respaldo = cmds.polyCube(h=planche_height + planche_width,
                             w=module_width + planche_width,
                             depth=planche_width)
    cmds.polyBevel3(offset=0.03)
    cmds.move(0, planche_height / 2.0,
              -planche_depth / 2.0 + planche_width / 2.0)
    cmds.parent(respaldo, mName, relative=True)

    for i in range(1, number_modules):
        mNameInstance = cmds.instance(mName)
        cmds.move(i * (module_width + planche_width), 0, 0, mNameInstance)
        cmds.parent(mNameInstance, uName, relative=True)

    cmds.parent(mName, uName, relative=True)
示例#33
0
 def rigModule(self, *args):
     Base.StartClass.rigModule(self)
     # verify if the guide exists:
     if cmds.objExists(self.moduleGrp):
         try:
             hideJoints = cmds.checkBox('hideJointsCB',
                                        query=True,
                                        value=True)
         except:
             hideJoints = 1
         # articulation joint:
         self.addArticJoint = self.getArticulation()
         # start as no having mirror:
         sideList = [""]
         # analisys the mirror module:
         self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
         if self.mirrorAxis != 'off':
             # get rigs names:
             self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
             # get first and last letters to use as side initials (prefix):
             sideList = [
                 self.mirrorNames[0] + '_',
                 self.mirrorNames[len(self.mirrorNames) - 1] + '_'
             ]
             for s, side in enumerate(sideList):
                 duplicated = cmds.duplicate(
                     self.moduleGrp,
                     name=side + self.userGuideName + '_Guide_Base')[0]
                 allGuideList = cmds.listRelatives(duplicated,
                                                   allDescendents=True)
                 for item in allGuideList:
                     cmds.rename(item,
                                 side + self.userGuideName + "_" + item)
                 self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                             empty=True)
                 cmds.parent(side + self.userGuideName + '_Guide_Base',
                             self.mirrorGrp,
                             absolute=True)
                 # re-rename grp:
                 cmds.rename(
                     self.mirrorGrp,
                     side + self.userGuideName + '_' + self.mirrorGrp)
                 # do a group mirror with negative scaling:
                 if s == 1:
                     if cmds.getAttr(self.moduleGrp + ".flip") == 0:
                         for axis in self.mirrorAxis:
                             gotValue = cmds.getAttr(
                                 side + self.userGuideName +
                                 "_Guide_Base.translate" + axis)
                             flipedValue = gotValue * (-2)
                             cmds.setAttr(
                                 side + self.userGuideName + '_' +
                                 self.mirrorGrp + '.translate' + axis,
                                 flipedValue)
                     else:
                         for axis in self.mirrorAxis:
                             cmds.setAttr(
                                 side + self.userGuideName + '_' +
                                 self.mirrorGrp + '.scale' + axis, -1)
             # joint labelling:
             jointLabelAdd = 1
         else:  # if not mirror:
             duplicated = cmds.duplicate(self.moduleGrp,
                                         name=self.userGuideName +
                                         '_Guide_Base')[0]
             allGuideList = cmds.listRelatives(duplicated,
                                               allDescendents=True)
             for item in allGuideList:
                 cmds.rename(item, self.userGuideName + "_" + item)
             self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                         name="Guide_Base_Grp",
                                         relative=True)
             #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
             # re-rename grp:
             cmds.rename(self.mirrorGrp,
                         self.userGuideName + '_' + self.mirrorGrp)
             # joint labelling:
             jointLabelAdd = 0
         # store the number of this guide by module type
         dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                 "dpAR_type") + 1
         # run for all sides
         for s, side in enumerate(sideList):
             self.base = side + self.userGuideName + '_Guide_Base'
             self.ctrlZeroGrp = side + self.userGuideName + "_00_Ctrl_Zero_0_Grp"
             self.skinJointList = []
             # get the number of joints to be created:
             self.nJoints = cmds.getAttr(self.base + ".nJoints")
             for n in range(0, self.nJoints):
                 cmds.select(clear=True)
                 # declare guide:
                 self.guide = side + self.userGuideName + "_Guide_JointLoc" + str(
                     n + 1)
                 self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd"
                 self.radiusGuide = side + self.userGuideName + "_Guide_Base_RadiusCtrl"
                 # create a joint:
                 self.jnt = cmds.joint(name=side + self.userGuideName +
                                       "_%02d_Jnt" % (n),
                                       scaleCompensate=False)
                 cmds.addAttr(self.jnt,
                              longName='dpAR_joint',
                              attributeType='float',
                              keyable=False)
                 # joint labelling:
                 utils.setJointLabel(self.jnt, s + jointLabelAdd, 18,
                                     self.userGuideName + "_%02d" % (n))
                 self.skinJointList.append(self.jnt)
                 # create a control:
                 self.jntCtrl = self.ctrls.cvControl(
                     "id_007_FkLine",
                     side + self.userGuideName + "_%02d_Ctrl" % (n),
                     r=self.ctrlRadius,
                     d=self.curveDegree)
                 # position and orientation of joint and control:
                 cmds.delete(
                     cmds.parentConstraint(self.guide,
                                           self.jnt,
                                           maintainOffset=False))
                 cmds.delete(
                     cmds.parentConstraint(self.guide,
                                           self.jntCtrl,
                                           maintainOffset=False))
                 # zeroOut controls:
                 self.zeroOutCtrlGrp = utils.zeroOut([self.jntCtrl])[0]
                 # hide visibility attribute:
                 cmds.setAttr(self.jntCtrl + '.visibility', keyable=False)
                 # fixing flip mirror:
                 if s == 1:
                     if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                         cmds.setAttr(self.zeroOutCtrlGrp + ".scaleX", -1)
                         cmds.setAttr(self.zeroOutCtrlGrp + ".scaleY", -1)
                         cmds.setAttr(self.zeroOutCtrlGrp + ".scaleZ", -1)
                 cmds.addAttr(self.jntCtrl,
                              longName='scaleCompensate',
                              attributeType="bool",
                              keyable=False)
                 cmds.setAttr(self.jntCtrl + ".scaleCompensate",
                              1,
                              channelBox=True)
                 cmds.connectAttr(self.jntCtrl + ".scaleCompensate",
                                  self.jnt + ".segmentScaleCompensate",
                                  force=True)
                 if n == 0:
                     utils.originedFrom(objName=self.jntCtrl,
                                        attrString=self.base + ";" +
                                        self.guide + ";" + self.radiusGuide)
                     self.ctrlZeroGrp = self.zeroOutCtrlGrp
                 elif n == self.nJoints - 1:
                     utils.originedFrom(objName=self.jntCtrl,
                                        attrString=self.guide + ";" +
                                        self.cvEndJoint)
                 else:
                     utils.originedFrom(objName=self.jntCtrl,
                                        attrString=self.guide)
                 # grouping:
                 if n > 0:
                     # parent joints as a simple chain (line)
                     self.fatherJnt = side + self.userGuideName + "_%02d_Jnt" % (
                         n - 1)
                     cmds.parent(self.jnt, self.fatherJnt, absolute=True)
                     # parent zeroCtrl Group to the before jntCtrl:
                     self.fatherCtrl = side + self.userGuideName + "_%02d_Ctrl" % (
                         n - 1)
                     cmds.parent(self.zeroOutCtrlGrp,
                                 self.fatherCtrl,
                                 absolute=True)
                 # control drives joint:
                 cmds.parentConstraint(self.jntCtrl,
                                       self.jnt,
                                       maintainOffset=False,
                                       name=self.jnt + "_PaC")
                 cmds.scaleConstraint(self.jntCtrl,
                                      self.jnt,
                                      maintainOffset=True,
                                      name=self.jnt + "_ScC")
                 # add articulationJoint:
                 if n > 0:
                     if self.addArticJoint:
                         artJntList = utils.articulationJoint(
                             self.fatherJnt, self.jnt
                         )  #could call to create corrective joints. See parameters to implement it, please.
                         utils.setJointLabel(
                             artJntList[0], s + jointLabelAdd, 18,
                             self.userGuideName + "_%02d_Jar" % (n))
                 cmds.select(self.jnt)
                 # end chain:
                 if n == self.nJoints - 1:
                     # create end joint:
                     self.endJoint = cmds.joint(
                         name=side + self.userGuideName + "_JEnd",
                         radius=0.5)
                     cmds.delete(
                         cmds.parentConstraint(self.cvEndJoint,
                                               self.endJoint,
                                               maintainOffset=False))
             # create a masterModuleGrp to be checked if this rig exists:
             self.toCtrlHookGrp = cmds.group(
                 self.ctrlZeroGrp,
                 name=side + self.userGuideName + "_Control_Grp")
             self.toScalableHookGrp = cmds.group(
                 self.skinJointList[0],
                 name=side + self.userGuideName + "_Joint_Grp")
             self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp,
                                               self.toScalableHookGrp,
                                               name=side +
                                               self.userGuideName + "_Grp")
             # create a locator in order to avoid delete static group
             loc = cmds.spaceLocator(name=side + self.userGuideName +
                                     "_DO_NOT_DELETE_PLEASE_Loc")[0]
             cmds.parent(loc, self.toStaticHookGrp, absolute=True)
             cmds.setAttr(loc + ".visibility", 0)
             self.ctrls.setLockHide([loc], [
                 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
             ])
             # add hook attributes to be read when rigging integrated modules:
             utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
             utils.addHook(objName=self.toScalableHookGrp,
                           hookType='scalableHook')
             utils.addHook(objName=self.toStaticHookGrp,
                           hookType='staticHook')
             cmds.addAttr(self.toStaticHookGrp,
                          longName="dpAR_name",
                          dataType="string")
             cmds.addAttr(self.toStaticHookGrp,
                          longName="dpAR_type",
                          dataType="string")
             cmds.setAttr(self.toStaticHookGrp + ".dpAR_name",
                          self.userGuideName,
                          type="string")
             cmds.setAttr(self.toStaticHookGrp + ".dpAR_type",
                          CLASS_NAME,
                          type="string")
             # add module type counter value
             cmds.addAttr(self.toStaticHookGrp,
                          longName='dpAR_count',
                          attributeType='long',
                          keyable=False)
             cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
             if hideJoints:
                 cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
             # delete duplicated group for side (mirror):
             cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
         # finalize this rig:
         self.integratingInfo()
         cmds.select(clear=True)
     # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
     self.deleteModule()
示例#34
0
            '{}.rz'.format(target_object)
        ])
        target_properties.extend([
            '{}.sx'.format(target_object), '{}.sy'.format(target_object),
            '{}.sz'.format(target_object)
        ])

    for attr in target_properties:
        cmds.setAttr(attr, lock=True, keyable=False)


# -------------------------------- BODY PARTS CREATION -------------------------------- #

# MASTER CONTROL
# ----------------
main_group = cmds.group(name='BASIC_DOLL_FK', empty=True)

master_points = [
    (0.96, 0.0, 0.0), (0.917, 0.0, 0.024), (0.618, 0.0, 0.198),
    (0.575, 0.0, 0.223), (0.575, 0.0, 0.209), (0.575, 0.0, 0.116),
    (0.575, 0.0, 0.102), (0.568, 0.0, 0.102), (0.521, 0.0, 0.102),
    (0.514, 0.0, 0.102), (0.473, 0.0, 0.31), (0.31, 0.0, 0.473),
    (0.102, 0.0, 0.514), (0.102, 0.0, 0.521), (0.102, 0.0, 0.568),
    (0.102, 0.0, 0.575), (0.116, 0.0, 0.575), (0.209, 0.0, 0.575),
    (0.223, 0.0, 0.575), (0.198, 0.0, 0.618), (0.024, 0.0, 0.917),
    (0.0, 0.0, 0.96), (-0.024, 0.0, 0.917), (-0.198, 0.0, 0.618),
    (-0.223, 0.0, 0.575), (-0.209, 0.0, 0.575), (-0.116, 0.0, 0.575),
    (-0.102, 0.0, 0.575), (-0.102, 0.0, 0.568), (-0.102, 0.0, 0.521),
    (-0.102, 0.0, 0.514), (-0.31, 0.0, 0.473), (-0.473, 0.0, 0.31),
    (-0.514, 0.0, 0.102), (-0.521, 0.0, 0.102), (-0.568, 0.0, 0.102),
    (-0.575, 0.0, 0.102), (-0.575, 0.0, 0.116), (-0.575, 0.0, 0.209),
def makeRibbon(nurbs='____nurb', system_name='brows'):
    vertex_list = cmds.ls(flatten=True, orderedSelection=True)
    fol_number = len(vertex_list)

    #vertex_list = [u'HeadBrows_c_geo.vtx[334]', u'HeadBrows_c_geo.vtx[335]', u'HeadBrows_c_geo.vtx[337]', u'HeadBrows_c_geo.vtx[341]', u'HeadBrows_c_geo.vtx[342]', u'HeadBrows_c_geo.vtx[344]', u'HeadBrows_c_geo.vtx[346]', u'HeadBrows_c_geo.vtx[348]', u'HeadBrows_c_geo.vtx[350]', u'HeadBrows_c_geo.vtx[352]', u'HeadBrows_c_geo.vtx[359]', u'HeadBrows_c_geo.vtx[360]', u'HeadBrows_c_geo.vtx[522]', u'HeadBrows_c_geo.vtx[1693]', u'HeadBrows_c_geo.vtx[1695]', u'HeadBrows_c_geo.vtx[1697]', u'HeadBrows_c_geo.vtx[1700]', u'HeadBrows_c_geo.vtx[1701]', u'HeadBrows_c_geo.vtx[1703]', u'HeadBrows_c_geo.vtx[1706]', u'HeadBrows_c_geo.vtx[1708]', u'HeadBrows_c_geo.vtx[1710]', u'HeadBrows_c_geo.vtx[1712]', u'HeadBrows_c_geo.vtx[1719]', u'HeadBrows_c_geo.vtx[1875]', u'HeadBrows_c_geo.vtx[3616]', u'HeadBrows_c_geo.vtx[3617]']

    # Recover Vertex List
    vertex_list_ordered = []
    vertex_list_disordered = vertex_list[::]
    vertex_list_disordered_x_positions = []
    for vtx in vertex_list_disordered:
        vtx_x_position = cmds.xform(vtx,
                                    query=True,
                                    translation=True,
                                    worldSpace=True)[0]
        vertex_list_disordered_x_positions.append(vtx_x_position)

    while len(vertex_list_disordered) > 0:
        vtx_lower_pos = 10000000000000
        vtx_position_in_list = None
        for i, vtx_x_pos in enumerate(vertex_list_disordered_x_positions):
            if vtx_x_pos < vtx_lower_pos:
                vtx_lower_pos = vtx_x_pos
                vtx_position_in_list = i
        vertex_list_ordered.append(
            vertex_list_disordered[vtx_position_in_list])
        vertex_list_disordered_x_positions.pop(vtx_position_in_list)
        vertex_list_disordered.pop(vtx_position_in_list)

    vertex_right_list = vertex_list_ordered[:fol_number / 2][::-1]
    vertex_left_list = vertex_list_ordered[(fol_number / 2) + 1:]
    vertex_center = vertex_list_ordered[fol_number / 2]

    #Create Follicles
    nurbs_shape = cmds.listRelatives(nurbs, shapes=True,
                                     noIntermediate=True)[0]
    left_follicles_list = []
    right_follicle_list = []
    for x in nurbs_shape:
        if not 'Orig' in x:
            nurbs_shape
    for side in 'lr':
        for i in range(0, fol_number / 2):
            follicle_name = '{}{}_{}_fol'.format(system_name,
                                                 str(i + 1).zfill(2), side)
            follicle = cmds.createNode('transform', name=follicle_name)
            follicle_shape = cmds.createNode(
                'follicle',
                name='{}Shape'.format(follicle_name),
                parent=follicle)
            cmds.connectAttr('{}.local'.format(nurbs_shape),
                             '{}.inputSurface'.format(follicle_shape),
                             force=True)
            cmds.connectAttr('{}.worldMatrix[0]'.format(nurbs_shape),
                             '{}.inputWorldMatrix'.format(follicle_shape),
                             force=True)
            for axis in 'XYZ':
                cmds.connectAttr('{}.outTranslate{}'.format(
                    follicle_shape, axis),
                                 '{}.translate{}'.format(follicle, axis),
                                 force=True)
                #cmds.connectAttr('{}.outRotate{}'.format(follicle_shape, axis), '{}.rotate{}'.format(follicle, axis), force = True)
            if side == 'l':
                left_follicles_list.append(follicle)
            elif side == 'r':
                right_follicle_list.append(follicle)

    center_follicle_name = '{}_c_fol'.format(system_name)
    center_follicle = cmds.createNode('transform', name=center_follicle_name)
    center_follicle_shape = cmds.createNode(
        'follicle',
        name='{}Shape'.format(center_follicle_name),
        parent=center_follicle)
    cmds.connectAttr('{}.local'.format(nurbs_shape),
                     '{}.inputSurface'.format(center_follicle_shape),
                     force=True)
    cmds.connectAttr('{}.worldMatrix[0]'.format(nurbs_shape),
                     '{}.inputWorldMatrix'.format(center_follicle_shape),
                     force=True)
    for axis in 'XYZ':
        cmds.connectAttr('{}.outTranslate{}'.format(center_follicle_shape,
                                                    axis),
                         '{}.translate{}'.format(center_follicle, axis),
                         force=True)
        #cmds.connectAttr('{}.outRotate{}'.format(center_follicle_shape, axis), '{}.rotate{}'.format(center_follicle, axis), force = True)

    for i, r_fol in enumerate(right_follicle_list):
        temp_closestSuface = cmds.createNode('closestPointOnSurface',
                                             name='temp_closest')
        cmds.connectAttr('{}.local'.format(nurbs_shape),
                         '{}.inputSurface'.format(temp_closestSuface),
                         force=True)
        vtx_position = cmds.xform(vertex_right_list[i],
                                  query=True,
                                  translation=True,
                                  worldSpace=True)
        cmds.setAttr('{}.inPosition'.format(temp_closestSuface),
                     vtx_position[0], vtx_position[1], vtx_position[2])
        parameter_U = cmds.getAttr('{}.parameterU'.format(temp_closestSuface))
        parameter_V = cmds.getAttr('{}.parameterV'.format(temp_closestSuface))
        follicle_shape = cmds.listRelatives(r_fol, shapes=True)[0]
        cmds.setAttr('{}.parameterU'.format(follicle_shape), parameter_U)
        cmds.setAttr('{}.parameterV'.format(follicle_shape), parameter_V)
        cmds.delete(temp_closestSuface)

    for i, l_fol in enumerate(left_follicles_list):
        temp_closestSuface = cmds.createNode('closestPointOnSurface',
                                             name='temp_closest')
        cmds.connectAttr('{}.local'.format(nurbs_shape),
                         '{}.inputSurface'.format(temp_closestSuface),
                         force=True)
        vtx_position = cmds.xform(vertex_left_list[i],
                                  query=True,
                                  translation=True,
                                  worldSpace=True)
        cmds.setAttr('{}.inPosition'.format(temp_closestSuface),
                     vtx_position[0], vtx_position[1], vtx_position[2])
        parameter_U = cmds.getAttr('{}.parameterU'.format(temp_closestSuface))
        parameter_V = cmds.getAttr('{}.parameterV'.format(temp_closestSuface))
        follicle_shape = cmds.listRelatives(l_fol, shapes=True)[0]
        cmds.setAttr('{}.parameterU'.format(follicle_shape), parameter_U)
        cmds.setAttr('{}.parameterV'.format(follicle_shape), parameter_V)
        cmds.delete(temp_closestSuface)

    cmds.setAttr('{}.parameterU'.format(center_follicle_shape), 0.5)
    cmds.setAttr('{}.parameterV'.format(center_follicle_shape), 0.5)

    #Creacion de Huesos por foliculo
    follicles_list = left_follicles_list + right_follicle_list + [
        center_follicle
    ]
    cmds.group(em=True, n='{}GeoSkin_c_grp'.format(system_name))
    cmds.group(em=True, n='{}SystemFols_c_grp'.format(system_name))
    for fol in follicles_list:
        jnt_name = '{}_{}_skn'.format(*fol.split('_'))
        jnt_zero_name = '{}Skn_{}_zero'.format(*fol.split('_'))
        jnt = cmds.createNode('joint', name=jnt_name)
        jnt_zero = cmds.createNode('transform', name=jnt_zero_name)
        jnt = cmds.parent(jnt, jnt_zero)[0]
        fol_matrix = cmds.xform(fol, query=True, matrix=True, worldSpace=True)
        cmds.xform(jnt_zero, matrix=fol_matrix, worldSpace=True)
        subs_node_name = '{}Fol_{}_subs'.format(*fol.split('_'))
        subs_node = cmds.createNode('plusMinusAverage', name=subs_node_name)
        cmds.setAttr('{}.operation'.format(subs_node), 2)
        for axis in 'xyz':
            cmds.connectAttr('{}.t{}'.format(fol, axis),
                             '{}.input3D[0].input3D{}'.format(subs_node, axis),
                             force=True)
            cmds.connectAttr('{}.t{}'.format(fol, axis),
                             '{}.input3D[1].input3D{}'.format(subs_node, axis),
                             force=True)
            cmds.disconnectAttr(
                '{}.t{}'.format(fol, axis),
                '{}.input3D[1].input3D{}'.format(subs_node, axis))
            cmds.connectAttr('{}.output3D{}'.format(subs_node, axis),
                             '{}.t{}'.format(jnt, axis),
                             force=True)
        cmds.parent(jnt_zero, '{}GeoSkin_c_grp'.format(system_name))
    #Hold bullshit
    if cmds.objExists('facialControls_c_grp') == False:
        cmds.group(em=True, n='facialControls_c_grp')
    if cmds.objExists('facialRig_c_grp') == False:
        cmds.group(em=True, n='facialRig_c_grp')
    if cmds.objExists('facialSystems_c_grp') == False:
        cmds.group(em=True, n='facialSystems_c_grp')
    cmds.createNode('joint', n='{}_c_Hold'.format(system_name))
    cmds.createNode('transform', name='{}Hold_c_zero'.format(system_name))
    cmds.parent('{}_c_Hold'.format(system_name),
                '{}Hold_c_zero'.format(system_name))
    cmds.parent('{}Hold_c_zero'.format(system_name),
                '{}GeoSkin_c_grp'.format(system_name))

    cmds.createNode('transform', n='{}SystemFols_c_grp'.format(system_name))
    for fol in follicles_list:
        cmds.parent(fol, '{}SystemFols_c_grp'.format(system_name))
    cmds.parent('{}SystemFols_c_grp'.format(system_name),
                'facialSystems_c_grp')
示例#36
0
def extrapFromWire(wire):
    
    curveShapeConnection = cmds.connectionInfo('%s.deformedWire[0]'%wire, sfd = True)
    curveShape = curveShapeConnection.split('.')[0]
    
    dagMembers = DeformerLib.WeightListTool.getDagMembers(wire)
    
    curvePath = GenAPI.getDagPath(curveShape)
    
    progressWin = UILib.ProgressWin()
    progressWin.setTitle('Extrap Skincluster from Wire')
    progressWin.itr = 5
    
    progressWin.inc = 1
    progressWin.progress()
    #creating clusters
    
    cvSelection = om.MSelectionList()
    
    cvItr = om.MItCurveCV(curvePath)
    
    clusters = []
    
    while not cvItr.isDone():
        
        cvSelection.clear()
        
        currentCV = cvItr.currentItem()
        
        cvSelection.add(curvePath,currentCV)
        om.MGlobal.setActiveSelectionList(cvSelection)
        
        cluster = cmds.cluster()
        clusters.append(cluster)
        
        cvItr.next()
    
    progressWin.inc = 2
    progressWin.message = 'extraping...'
    progressWin.progress()  
    #getting weights from clusters
    
    allWeightLists = []
    
    for mesh in dagMembers:
        
        influenceWeightLists = []
        
        for cluster in clusters:
            
            currentWeightList = MeasuringLib.MeasuringTool.createWeigthListFromTransform(mesh, cluster[1])
            influenceWeightLists.append(currentWeightList)
            
        allWeightLists.append(influenceWeightLists)
    
    #delete clusters
    for cluster in clusters:
        cmds.delete(cluster[0])
    
    progressWin.inc = 3
    progressWin.progress()
    #create joints    
    
    cmds.select(cl = True)
    
    joints = []
    
    cvItr.reset(curvePath)
    
    while not cvItr.isDone():
        
        cmds.select(cl = True)
        
        position = cvItr.position(om.MSpace.kWorld)
        
        currentJoint = cmds.joint()
        cmds.move(position.x,position.y,position.z,currentJoint)
        joints.append(currentJoint)
        
        cvItr.next()
    
    cmds.select(cl = True)
        
    baseJoint = cmds.joint()
    
    progressWin.inc = 4
    progressWin.progress()
    #create group for bind joints
    
    jointGroup = cmds.group(empty = True)
    cmds.parent(baseJoint,jointGroup)
    
    for joint in joints:
        
        cmds.parent(joint,jointGroup)
    
    progressWin.inc = 5
    progressWin.message = 'setting weights'
    progressWin.progress()   
    #smooth bind
    
    
    inc = 0
    for mesh in dagMembers:
        
        progressWin = UILib.ProgressWin()
        progressWin.setTitle('Setting Weights for %s'%mesh)
        progressWin.itr = len(joints)

    
        skincluster = cmds.skinCluster(mesh,baseJoint)[0]
        skinningTool = SkinningTool(skincluster,mesh)
        
        cmds.setAttr('%s.liw'%baseJoint, 0)
        
        for i in range(len(joints)):
            
            cmds.skinCluster(skincluster,e = True , weight = 0,addInfluence = joints[i])
            cmds.setAttr('%s.liw'%joints[i], 0)
            
            skinningTool.setWeights(GenAPI.getDagPath(joints[i]), allWeightLists[inc][i])
            
            cmds.setAttr('%s.liw'%joints[i], 1)
            
            progressWin.inc = i
            progressWin.progress()
            
        inc += 1
        progressWin.end()
示例#37
0
    def geometryCacheReplace(self):
        object_listTemp = cmds.ls(sl=True, long=True)
        global object
        object = object_listTemp[0]

        dupObjectName = cmds.textField('Face_Control_Object_Name',
                                       q=True,
                                       tx=True)
        #print dupObjectName

        minTime = cmds.playbackOptions(q=True, min=True)
        maxTime = cmds.playbackOptions(q=True, max=True)

        attrs = cmds.listHistory(object)
        meshList = []
        for i in attrs:
            if cmds.objectType(i, isType='mesh'):
                meshList.append(i)
        cmds.cacheFile(fm='OneFile',
                       cf='mcc',
                       ws=True,
                       f=dupObjectName + 'GeometryCache',
                       refresh=0,
                       st=minTime,
                       et=maxTime,
                       dir='D:\Cache',
                       pts=meshList[0])

        cmds.currentTime(minTime, edit=True)

        try:
            cmds.select(dupObjectName + '_Group')
            cmds.delete()
            cmds.select(object)
            cmds.duplicate(name=dupObjectName)
            cmds.group(dupObjectName,
                       name=dupObjectName + '_Group',
                       world=True)
        except:
            #print 'No element'
            cmds.select(object)
            cmds.duplicate(name=dupObjectName)
            cmds.group(dupObjectName,
                       name=dupObjectName + '_Group',
                       world=True)

        cmds.select(dupObjectName)

        if os.path.exists('D:\Cache\TrashCache.mc') or os.path.exists(
                'D:\Cache\TrashCache.xml'):
            os.remove('D:\Cache\TrashCache.mc')
            os.remove('D:\Cache\TrashCache.xml')
        else:
            print 'Go ahead'

        mel.eval(
            '''doCreateGeometryCache 6 { "2", "1", "10", "OneFile", "1", "D:/Cache","0","TrashCache","0", "add", "0", "1", "1","0","0","mcc","1" } ;'''
        )
        cmds.currentTime(minTime, edit=True)

        dupObjAttrs = cmds.listHistory(dupObjectName)
        cacheNameList = []
        for i in dupObjAttrs:
            if cmds.objectType(i, isType='cacheFile'):
                cacheNameList.append(i)

        cmds.setAttr("%s.cacheName" % cacheNameList[0],
                     dupObjectName + 'GeometryCache',
                     type='string')
示例#38
0
    def generateConnectedTestScene(self,
                                   shadingNodeAttributes,
                                   ignoreColorSpaceFileRules=False):
        """
        Generate test scene containing a UsdPreviewSurface with bindings to other shading nodes
        exports correctly.
        :type shadingNodeAttributes: List[Tuple[str, Any]]
        :type ignoreColorSpaceFileRules: bool
        """
        maya_file = os.path.join(self.temp_dir,
                                 "UsdExportConnectedUsdPreviewSurfaceTest.ma")
        cmds.file(force=True, new=True)
        mesh = "ConnectedMaterialSphere"
        cmds.polySphere(name=mesh,
                        subdivisionsX=20,
                        subdivisionsY=20,
                        radius=1)
        cmds.group(mesh, name="Geom")
        cmds.group("Geom", name="UsdPreviewSurfaceExportTest")
        shading_node = "usdPreviewSurface_Connected"
        cmds.shadingNode("usdPreviewSurface", name=shading_node, asShader=True)

        for attr in shadingNodeAttributes:
            if isinstance(attr[1], Gf.Vec3f):
                cmds.setAttr(
                    "%s.%s" % (shading_node, attr[0]),
                    attr[1][0],
                    attr[1][1],
                    attr[1][2],
                )
            else:
                cmds.setAttr("%s.%s" % (shading_node, attr[0]), attr[1])

        texture_dir = os.path.join(self.input_dir,
                                   "UsdExportUsdPreviewSurfaceTest")
        cmds.defaultNavigation(createNew=True,
                               destination="%s.diffuseColor" % shading_node)
        file_node = cmds.shadingNode("file",
                                     asTexture=True,
                                     name="Brazilian_Rosewood_Texture")
        cmds.setAttr(file_node + ".ignoreColorSpaceFileRules",
                     ignoreColorSpaceFileRules)

        cmds.setAttr(
            file_node + ".fileTextureName",
            os.path.join(texture_dir, "Brazilian_rosewood_pxr128.png"),
            type="string",
        )
        cmds.connectAttr("%s.outColor" % file_node,
                         "%s.diffuseColor" % shading_node,
                         force=True)

        # This file node should have stayed "sRGB":
        if not ignoreColorSpaceFileRules:
            self.assertEqual(cmds.getAttr(file_node + ".colorSpace"), "sRGB")

        cmds.defaultNavigation(createNew=True,
                               destination="%s.roughness" % shading_node)
        file_node = cmds.shadingNode("file",
                                     asTexture=True,
                                     name="Brazilian_Rosewood_Bump_Texture")
        cmds.setAttr(file_node + ".ignoreColorSpaceFileRules",
                     ignoreColorSpaceFileRules)

        cmds.setAttr(
            file_node + ".fileTextureName",
            os.path.join(texture_dir, "Brazilian_rosewood_pxr128_bmp.png"),
            type="string",
        )
        cmds.connectAttr("%s.outColorR" % file_node,
                         "%s.roughness" % shading_node,
                         force=True)

        # The monochrome file node should have been set to "Raw" automatically:
        if not ignoreColorSpaceFileRules:
            self.assertEqual(cmds.getAttr(file_node + ".colorSpace"), "Raw")

        cmds.defaultNavigation(createNew=True,
                               destination="%s.clearcoatRoughness" %
                               shading_node)
        cmds.connectAttr(
            "%s.outColorR" % file_node,
            "%s.clearcoatRoughness" % shading_node,
            force=True,
        )

        cmds.defaultNavigation(createNew=True,
                               destination="%s.normal" % shading_node)
        file_node = cmds.shadingNode("file",
                                     asTexture=True,
                                     name="Brazilian_Rosewood_Normal_Texture")
        cmds.setAttr(
            file_node + ".fileTextureName",
            os.path.join(texture_dir, "Brazilian_rosewood_pxr128_n.png"),
            type="string",
        )
        cmds.connectAttr("%s.outColor" % file_node,
                         "%s.normal" % shading_node,
                         force=True)

        # The file node should have been set to "NormalMap" automatically:
        self.assertEqual(cmds.getAttr(file_node + ".colorSpace"), "Raw")
        self.assertEqual(cmds.getAttr(file_node + ".colorGainR"), 2)
        self.assertEqual(cmds.getAttr(file_node + ".colorGainG"), 2)
        self.assertEqual(cmds.getAttr(file_node + ".colorGainB"), 2)
        self.assertEqual(cmds.getAttr(file_node + ".colorOffsetR"), -1)
        self.assertEqual(cmds.getAttr(file_node + ".colorOffsetG"), -1)
        self.assertEqual(cmds.getAttr(file_node + ".colorOffsetB"), -1)
        self.assertEqual(cmds.getAttr(file_node + ".alphaGain"), 1)
        self.assertEqual(cmds.getAttr(file_node + ".alphaOffset"), 0)

        shading_engine = "%sSG" % shading_node
        cmds.sets(renderable=True,
                  noSurfaceShader=True,
                  empty=True,
                  name=shading_engine)
        cmds.connectAttr(
            "%s.outColor" % shading_node,
            "%s.surfaceShader" % shading_engine,
            force=True,
        )
        cmds.sets(mesh, edit=True, forceElement=shading_engine)

        cmds.file(rename=maya_file)
        cmds.file(save=True, type="mayaAscii")
        self.assertTrue(os.path.exists(maya_file))

        return maya_file
示例#39
0
def createSubCtrl(polyComp):
    meshShape=mc.ls(polyComp,o=1)
    mesh=mc.listRelatives(meshShape,p=1)[0]
    deformers=mm.eval('findRelatedDeformer("%s")'%mesh)
    skinNode,blendNodes=[],[]
    for i in deformers:
        if mc.nodeType(i)=='skinCluster':
            skinNode.append(i)
        if mc.nodeType(i)=='blendShape':
            blendNodes.append(i)
    blendValue=[]
    for i in blendNodes:
        blendValue.append(mc.getAttr(i+'.envelope'))
        mc.setAttr((i+'.envelope'),0)
        
    allVetices=mc.polyEvaluate(mesh,v=1)
    souceAllPos=[]
    for i in range(0,allVetices):
        soucePos=mc.xform(mesh+'.vtx['+str(i)+']',q=1,ws=1,t=1)
        souceAllPos.append(soucePos)
    mc.move(0,100,0,r=1,ws=1,wd=1)
    allPos=[]
    for i in range(0,allVetices):
        pos=mc.xform(mesh+'.vtx['+str(i)+']',q=1,ws=1,t=1)
        allPos.append(pos)
    mc.move(0,-100,0,r=1,ws=1,wd=1)
    weights=[]
    for i in range(0,allVetices):
        weights.append((allPos[i][1]-souceAllPos[i][1])*0.01)
    
    jointPos=mc.xform(polyComp,q=1,ws=1,t=1)
    strCtrl = mm.eval("curve -d 1 -p -8.19564e-008 0 0.5 -p 0.0975451 0 0.490393 -p 0.191342 0 0.46194 -p 0.277785 0 0.415735 -p 0.353553 0 0.353553 -p 0.415735 0 0.277785 -p 0.46194 0 0.191342 -p 0.490393 0 0.0975452 -p 0.5 0 0 -p 0.490392 0 -0.0975448 -p 0.461939 0 -0.191341 -p 0.415734 0 -0.277785 -p 0.353553 0 -0.353553 -p 0.277785 0 -0.415734 -p 0.191342 0 -0.461939 -p 0.0975453 0 -0.490392 -p 2.23517e-007 0 -0.5 -p -0.0975448 0 -0.490392 -p -0.191341 0 -0.461939 -p -0.277785 0 -0.415735 -p -0.353553 0 -0.353553 -p -0.415734 0 -0.277785 -p -0.461939 0 -0.191342 -p -0.490392 0 -0.0975453 -p -0.5 0 -1.63913e-007 -p -0.490392 0 0.097545 -p -0.46194 0 0.191341 -p -0.415735 0 0.277785 -p -0.353553 0 0.353553 -p -0.277785 0 0.415735 -p -0.191342 0 0.46194 -p -0.0975452 0 0.490392 -p -8.19564e-008 0 0.5 -p -8.03816e-008 0.0975452 0.490392 -p -7.57178e-008 0.191342 0.46194 -p -6.81442e-008 0.277785 0.415735 -p -5.79519e-008 0.353553 0.353553 -p -4.55325e-008 0.415735 0.277785 -p -3.13634e-008 0.46194 0.191342 -p -1.59889e-008 0.490393 0.0975451 -p 0 0.5 0 -p 4.36061e-008 0.490393 -0.0975451 -p 8.55364e-008 0.46194 -0.191342 -p 1.2418e-007 0.415735 -0.277785 -p 1.58051e-007 0.353553 -0.353553 -p 1.85848e-007 0.277785 -0.415734 -p 2.06503e-007 0.191342 -0.461939 -p 2.19223e-007 0.0975452 -0.490392 -p 2.23517e-007 0 -0.5 -p 2.19223e-007 -0.0975452 -0.490392 -p 2.06503e-007 -0.191342 -0.461939 -p 1.85848e-007 -0.277785 -0.415734 -p 1.58051e-007 -0.353553 -0.353553 -p 1.2418e-007 -0.415735 -0.277785 -p 8.55364e-008 -0.46194 -0.191342 -p 4.36061e-008 -0.490393 -0.0975451 -p 0 -0.5 0 -p -1.59889e-008 -0.490393 0.0975451 -p -3.13634e-008 -0.46194 0.191342 -p -4.55325e-008 -0.415735 0.277785 -p -5.79519e-008 -0.353553 0.353553 -p -6.81442e-008 -0.277785 0.415735 -p -7.57178e-008 -0.191342 0.46194 -p -8.03816e-008 -0.0975452 0.490392 -p -8.19564e-008 0 0.5 -p -0.0975452 0 0.490392 -p -0.191342 0 0.46194 -p -0.277785 0 0.415735 -p -0.353553 0 0.353553 -p -0.415735 0 0.277785 -p -0.46194 0 0.191341 -p -0.490392 0 0.097545 -p -0.5 0 -1.63913e-007 -p -0.490392 -0.0975452 -1.60763e-007 -p -0.461939 -0.191342 -1.51436e-007 -p -0.415735 -0.277785 -1.36288e-007 -p -0.353553 -0.353553 -1.15904e-007 -p -0.277785 -0.415735 -9.10651e-008 -p -0.191342 -0.46194 -6.27267e-008 -p -0.0975451 -0.490393 -3.19778e-008 -p 0 -0.5 0 -p 0.0975452 -0.490393 0 -p 0.191342 -0.46194 0 -p 0.277785 -0.415735 0 -p 0.353553 -0.353553 0 -p 0.415735 -0.277785 0 -p 0.46194 -0.191342 0 -p 0.490393 -0.0975452 0 -p 0.5 0 0 -p 0.490393 0.0975452 0 -p 0.46194 0.191342 0 -p 0.415735 0.277785 0 -p 0.353553 0.353553 0 -p 0.277785 0.415735 0 -p 0.191342 0.46194 0 -p 0.0975452 0.490393 0 -p 0 0.5 0 -p -0.0975451 0.490393 -3.19778e-008 -p -0.191342 0.46194 -6.27267e-008 -p -0.277785 0.415735 -9.10651e-008 -p -0.353553 0.353553 -1.15904e-007 -p -0.415735 0.277785 -1.36288e-007 -p -0.461939 0.191342 -1.51436e-007 -p -0.490392 0.0975452 -1.60763e-007 -p -0.5 0 -1.63913e-007 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 18 -k 19 -k 20 -k 21 -k 22 -k 23 -k 24 -k 25 -k 26 -k 27 -k 28 -k 29 -k 30 -k 31 -k 32 -k 33 -k 34 -k 35 -k 36 -k 37 -k 38 -k 39 -k 40 -k 41 -k 42 -k 43 -k 44 -k 45 -k 46 -k 47 -k 48 -k 49 -k 50 -k 51 -k 52 -k 53 -k 54 -k 55 -k 56 -k 57 -k 58 -k 59 -k 60 -k 61 -k 62 -k 63 -k 64 -k 65 -k 66 -k 67 -k 68 -k 69 -k 70 -k 71 -k 72 -k 73 -k 74 -k 75 -k 76 -k 77 -k 78 -k 79 -k 80 -k 81 -k 82 -k 83 -k 84 -k 85 -k 86 -k 87 -k 88 -k 89 -k 90 -k 91 -k 92 -k 93 -k 94 -k 95 -k 96 -k 97 -k 98 -k 99 -k 100 -k 101 -k 102 -k 103 -k 104");mc.DeleteHistory()
    strCtrl =mc.rename(strCtrl,mesh.replace('_MO_','_')+'_subCtrl#')
    strCtrlDrv = mc.group(strCtrl,n=strCtrl +'_driven')
    strCtrlInverse=mc.group(strCtrlDrv,n=strCtrl+'_inverse')
    strCtrlGrp = mc.group(strCtrlInverse,n=strCtrl +'_GRP')
    mc.xform(strCtrlGrp,a=True,ws=True,t=jointPos)
    softSelJoint=mc.joint(strCtrl,p=jointPos,n=strCtrl+'_joint');mc.hide(softSelJoint)
    softSelJointGrp = mc.group(softSelJoint,n=strCtrl+'_joint_GRP')
    mc.setAttr(strCtrl+'.overrideEnabled',1)
    mc.setAttr(strCtrl+'.overrideColor',13) 
    mc.skinCluster(mesh,e=1,wt=0,ai=softSelJoint)
    
    for i in range(0,allVetices):
        if not weights[i]==0:
            mc.skinPercent(skinNode[0],mesh+'.vtx['+str(i)+']',tv=[softSelJoint,weights[i]])
    mc.skinCluster(mesh,e=1,lw=1,inf=softSelJoint)
    infJoints=mc.skinCluster(skinNode[0],q=1,inf=1)
    activeList=om.MSelectionList()
    om.MGlobal.getSelectionListByName(skinNode[0],activeList)
    depNode=om.MObject() 
    iter=om.MItSelectionList(activeList)
    iter.reset()
    iter.getDependNode(depNode)
    mfnDN=om.MFnDependencyNode(depNode)
    bindPreMatrixPlug=mfnDN.findPlug('bindPreMatrix')
    bindPreMatrix=bindPreMatrixPlug.elementByPhysicalIndex(len(infJoints)-1).info()
    mc.connectAttr(strCtrlInverse+'.worldInverseMatrix',bindPreMatrix,f=1)
    firstMesh=mc.listConnections(mesh+'.firstObject',s=1)[0]
    loca=polyAttach(firstMesh+'.vtx['+polyComp.split('.vtx[')[1])
    if not mc.objExists('attachLocators'):
        mc.group(em=1,n='attachLocators')
        if mc.objExists('secondarySystem'):
            mc.parent('attachLocators','secondarySystem')
    mc.parent(loca,'attachLocators')
    mc.parentConstraint(loca,strCtrlGrp,mo=1)
    mc.hide(loca)
    for i in blendNodes:
        index=blendNodes.index(i)
        mc.setAttr((i+'.envelope'),blendValue[index])
    mc.select(strCtrl,r=1)
示例#40
0
# FK pos and rot. First select controlobject then a joint by Niclas Halvarsson
import maya.cmds as mc

my_sel = mc.ls(sl=True)

if len(my_sel) < 2 or len(my_sel) > 3:
    mc.error("Please select atleast 1 ctrlCurve and 1 joints")

ctl_og = mc.group(empty=True)
mc.parent(my_sel[0], my_sel[1])
mc.parent(ctl_og, my_sel[1])

axis = ["x", "y", "z"]
for i in axis:
    mc.setAttr(my_sel[0] + ".t" + i, 0)
    mc.setAttr(my_sel[0] + ".r" + i, 0)
    mc.setAttr(ctl_og + ".t" + i, 0)
    mc.setAttr(ctl_og + ".r" + i, 0)

mc.parent(ctl_og, w=True)
mc.parent(my_sel[0], ctl_og)

newname = mc.rename(my_sel[0], my_sel[1] + "_CTL")
grpname = newname.split("_CTL")[0]
og_name = mc.rename(ctl_og, grpname + "_OG")

mc.parentConstraint(newname, my_sel[1], mo=False)
if len(my_sel) == 3:
    mc.parentConstraint(my_sel[2], og_name, mo=True)

示例#41
0
    def splineIK(self, *args):
        tempIKJnts = []
        tempBindJnts = []

        #select top joint of chain for IK
        all = cmds.select(hi=True)
        rawJnts = cmds.ls(sl=True, type="joint")

        #rename to "bind"
        for jnt in rawJnts:
            if cmds.listRelatives(jnt, p=True):
                cmds.parent(jnt, w=True)
            thisRaw = cmds.rename(jnt, "bind_%02d_JNT" % (rawJnts.index(jnt)))
            tempBindJnts.append(thisRaw)

        for x in range(len(tempBindJnts)):
            thisIkRaw = cmds.duplicate(tempBindJnts[x])
            newName = "IK_%02d_JNT" % x
            thisIKJnt = cmds.rename(thisIkRaw, newName)
            tempikJnts.append(thisIKJnt)

        for x in range(len(tempBindJnts) - 1, 0, -1):
            cmds.parent(tempBindJnts[x], tempBindJnts[x - 1])
            cmds.parent(self.tempIKJnts[x], self.tempIKJnts[x - 1])

        cmds.select(tempBindJnts[0], hi=True)
        self.bindJnts = cmds.ls(sl=True, l=True)
        cmds.select(self.tempIKJnts[0], hi=True)
        self.ikJnts = cmds.ls(sl=True, l=True)

        #on IK chain create an IKRP on each jnt pointing to the next one down
        for i in range(len(self.bindJnts) - 1):
            ikName = "%s_IKHandle" % self.bindJnts[i].rpartition("|")[2]
            cmds.ikHandle(n=ikName,
                          sj=self.bindJnts[i],
                          ee=self.bindJnts[i + 1],
                          solver="ikRPsolver")
            cmds.parent(ikName, self.ikJnts[i + 1])
            self.ikHandles.append(ikName)

        #create splineIK on IK jnts
        self.ikSplineName = "ikSplineHandle"
        splineIK = cmds.ikHandle(sol="ikSplineSolver",
                                 n=ikSplineName,
                                 sj=self.ikJnts[0],
                                 ee=self.ikJnts[len(self.ikJnts) - 1])
        self.curve = splineIK[2]

        #on each IK joint create a loc and move it off in some direction (relative to the IKRPsolver), hook it to the IK Handle
        for j in range(len(self.ikHandles)):
            locName = "pv_loc_%02d" % j
            groupName = locName + "_GRP"
            #create locator
            cmds.spaceLocator(n=locName, p=(0, 0, 0))
            #get joint position
            jntPos = cmds.xform(self.ikJnts[j], ws=True, q=True, rp=True)
            cmds.xform(locName,
                       ws=True,
                       t=[jntPos[0], jntPos[1] - 1, jntPos[2]])
            cmds.poleVectorConstraint(locName, self.ikHandles[j])
            self.locList.append(locName)
            #create an empty group and put it at the jntPos
            cmds.group(empty=True, n=groupName)
            self.groupList.append(groupName)
            cmds.xform(groupName, ws=True, t=jntPos)
            #parent the locs to the groups
            cmds.parent(locName, groupName)
            #parent the groups to the self.ikJnts
            cmds.parent(groupName, self.ikJnts[j])
示例#42
0
def ctrlPointCurve(curve,
                   numCtrlPts=3,
                   guideGeo=None,
                   meshIntersect=None,
                   prefix=None):
    '''
	Create a control point (locator) curve and project to guide surface.
	Control points are projected to guide using geometry constraints.
	@param curve: Curve to create control points from.
	@type curve: str
	@param numCtrlPts: Number of curve control points to build.
	@type numCtrlPts: str
	@param guideGeo: Guide surface to constrain control points to.
	@type guideGeo: str
	@param meshIntersect: MeshIntersectArray node to attach to. If None, use geometryConstraint.
	@type meshIntersect: str or None
	@param prefix: Naming prefix.
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

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

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

    paramList = glTools.utils.curve.sampleParam(curve=curve,
                                                samples=numCtrlPts,
                                                useDistance=True)

    # Build Anchors
    ctrlPts = []
    for i in range(len(paramList)):

        # Create Anchor
        ind = glTools.utils.stringUtils.alphaIndex(i)
        ctrlPt = glTools.tools.createAlongCurve.createAtParam(
            curve,
            param=paramList[i],
            objType='locator',
            name=prefix + '_ctrlPt' + ind + '_loc')
        ctrlPts.append(ctrlPt)

    # ===============
    # - Build Curve -
    # ===============

    degree = 3
    if numCtrlPts < 4: degree = 1
    ctrlCrv = glTools.utils.curve.createFromLocators(locatorList=ctrlPts,
                                                     degree=degree,
                                                     attach=True,
                                                     prefix=prefix + '_ctrlPt')
    # Rebuild Degree 1 Curve
    if degree == 1:
        glTools.utils.shape.createIntermediate(ctrlCrv)
        mc.rebuildCurve(ctrlCrv, d=3, s=0, rt=0, rpo=1, end=1, fitRebuild=0)

    # Group Curve
    grp = mc.group(ctrlCrv, ctrlPts, n=prefix + '_grp')

    # =========================
    # - Constrain to Geometry -
    # =========================

    geoConstraint = None
    intersectPt = []
    if guideGeo:

        # Use meshIntersectArray
        if meshIntersect:
            for ctrlPt in ctrlPts:
                #ctrlPtAttr = mc.listConnections(ctrlPt+'.worldPosition[0]',s=False,d=True,p=True)[0]
                intersectPt.append(
                    mc.duplicate(ctrlPt,
                                 name='%s_intersectPt_loc' % prefix)[0])
                outputAttr = glTools.utils.meshIntersectArray.addIntersect(
                    meshIntersect, intersectPt[-1] + '.worldPosition[0]')

                mc.connectAttr(outputAttr[0], '%s.translate' % ctrlPt, f=True)

        # Use geometryConstraint
        else:
            geoConstraint = [
                mc.geometryConstraint(guideGeo, ctrlPt)[0]
                for ctrlPt in ctrlPts
            ]
            ''' may want to add an option in the future for using follicles
			uvList = []
			for i, pt in enumerate(ctrlPts):
				pos = mc.pointPosition(pt, world=True)
				uv = glTools.utils.mesh.closestUV(guideGeo,point=pos)
				uvList.append(uv)
			
				follicleList.append( glTools.utils.follicle.create( targetGeo = guideGeo,
												parameter    = uv,
												prefix       = '%s_%s_follicle' % (prefix, i) ) )
				
				mc.parent(pt, follicleList[-1])
				mc.parent(follicleList[-1], grp)
				mc.setAttr('%s.translate' % pt, *[0,0,0])
				mc.setAttr('%s.rotate' % pt, *[0,0,0])
			'''

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

    result = {}
    result['grp'] = grp
    result['crv'] = ctrlCrv
    result['pnt'] = ctrlPts
    result['geoConstraint'] = geoConstraint
    result['intersectPt'] = intersectPt
    return result
	def tweakHiearchy(self, eachGrp, control, position, eachSel ):
			''' Tweakable Hierarchy. '''

			self.twkGrp= []
			self.trgtGrp= []
			# Checks to see if tweakable hierarchy is set.
			if self.option == self.menuItems[2]:
				
				if self.lastCreatedControl != None:

					__controlXform= cmds.xform( self.lastCreatedControl, ws=1, m= True , q=1)
					
					# Creates _twk group and positions it for each selected.
					__twkGrpName= control.replace( "_ctl", "_twk" )
					__trgtGrpName= control.replace( "_ctl", "_trgt" )
					
					self.twkGrp= cmds.group( name= __twkGrpName, em=1  )
					self.trgtGrp= cmds.group( name= __trgtGrpName, em=1 )


					cmds.xform( self.twkGrp, ws=1, m= __controlXform )
					cmds.xform( self.trgtGrp, ws=1, m= position )
					
					# Parents each created controller's group, the target group to tweak group.
					cmds.parent( eachGrp, self.trgtGrp, self.twkGrp )
					
					#cmds.pointConstraint( self.lastCreatedControl, eachSel, mo=0 )
					#print self.lastCreatedControl, '>>>>', eachSel
					
					cmds.orientConstraint( self.trgtGrp, eachSel, mo=0 )
					cmds.orientConstraint( self.lastCreatedControl,self.twkGrp  )
					
					# Stores the last created control for next operation in the class.
					self.lastCreatedControl= control

				
				if self.lastCreatedControl == None:
					
					baseControl= []
				
					__trgtGrpName= control.replace( "_ctl", "_trgt" )
					self.trgtGrp= cmds.group( name= __trgtGrpName, em=1 )
					
					
					baseControl= cmds.xform( control, ws=1, m=True, query=True )
					cmds.xform( self.trgtGrp, ws=1, m= baseControl )
					
					cmds.parent( self.trgtGrp, control )
					
					cmds.orientConstraint( control, eachSel, mo=0 )
					
					self.lastCreatedControl= control

				self.lastCreatedtwkGrp.append( self.twkGrp )
				self.lastCreatedtrgtGrp.append( self.trgtGrp )

				if len( self.selection ) == len( self.lastCreatedtrgtGrp ):
					for eachTweak, eachTarget in zip( self.lastCreatedtwkGrp[1:], self.lastCreatedtrgtGrp ):
						#print "parenting {0} to {1}".format( eachTweak, eachTarget )
						cmds.parent( eachTweak, eachTarget )
				
				# PointConstraints each controller created to each selected object.
				cmds.pointConstraint( control, eachSel, mo=True )
				print control, '>>>', eachSel
示例#44
0
    def createJointLid(self, crv, worldUpObject, eyeballJnt, scale, sideRGT,
                       sideLFT, side):
        self.allJointCenter = []
        self.allJoint = []
        self.allLocator = []

        if sideRGT in crv:
            crvNewName = crv.replace(sideRGT, '')
        elif sideLFT in crv:
            crvNewName = crv.replace(sideLFT, '')
        else:
            crvNewName = crv

        for i, v in enumerate(self.vtxCrv):

            # get the number
            # try:
            #     patterns = [r'\d+']
            #     prefixNumber = au.prefixName(newName)
            #     for p in patterns:
            #         prefixNumber = re.findall(p, prefixNumber)[0]
            # except:
            #     prefixNumber = ''
            # # get the prefix without number
            # prefixNoNumber = str(au.prefixName(newName)).translate(None, digits)

            # create joint
            mc.select(cl=1)
            self.joint = mc.joint(n='%s%02d%s%s' % (au.prefixName(crvNewName),
                                                    (i + 1), side, '_jnt'),
                                  rad=0.1 * scale)
            pos = mc.xform(v, q=1, ws=1, t=1)
            mc.xform(self.joint, ws=1, t=pos)
            self.allJoint.append(self.joint)

            mc.select(cl=1)
            self.jointCenter = mc.joint(n='%s%s%02d%s%s' %
                                        (au.prefixName(crvNewName), 'Ctr',
                                         (i + 1), side, '_jnt'),
                                        rad=0.1 * scale)
            posC = mc.xform(eyeballJnt, q=1, ws=1, t=1)
            mc.xform(self.jointCenter, ws=1, t=posC)
            mc.parent(self.joint, self.jointCenter)

            # change direction of joint center
            mc.joint(self.jointCenter,
                     e=1,
                     oj="xyz",
                     secondaryAxisOrient="yup",
                     ch=1,
                     zso=1)
            self.allJointCenter.append(self.jointCenter)

            # create locator
            self.locator = mc.spaceLocator(n='%s%02d%s%s' %
                                           (au.prefixName(crvNewName),
                                            (i + 1), side, '_loc'))[0]

            mc.xform(self.locator, ws=1, t=pos)

            # aim constraint of joint
            mc.aimConstraint(self.locator,
                             self.jointCenter,
                             mo=1,
                             weight=1,
                             aimVector=(1, 0, 0),
                             upVector=(0, 1, 0),
                             worldUpType="object",
                             worldUpObject=worldUpObject)

            self.allLocator.append(self.locator)

            # connect curve to locator grp
            curveRelatives = mc.listRelatives(crv, s=True)[0]
            u = self.getUParam(pos, curveRelatives)
            pci = mc.createNode("pointOnCurveInfo",
                                n='%s%02d%s%s' % (au.prefixName(crvNewName),
                                                  (i + 1), side, '_pci'))
            mc.connectAttr(curveRelatives + '.worldSpace', pci + '.inputCurve')
            mc.setAttr(pci + '.parameter', u)
            mc.connectAttr(pci + '.position', self.locator + '.t')

        # grouping joint
        self.jointGrp = mc.group(em=1,
                                 n=au.prefixName(crvNewName) + 'Jnt' + side +
                                 '_grp')
        mc.parent(self.allJointCenter, worldUpObject, self.jointGrp)
        mc.hide(self.jointGrp)

        # grouping locator
        self.locatorGrp = mc.group(em=1,
                                   n=au.prefixName(crvNewName) + 'Loc' + side +
                                   '_grp')
        mc.setAttr(self.locatorGrp + '.it', 0, l=1)
        mc.parent(self.allLocator, self.locatorGrp)
        mc.hide(self.locatorGrp)
	def createControl(self, *args ):
		''' Creates a single Controller '''

		if self.AboveAlphabet == False:

			nurbCircle= cmds.circle( name= self.name + '%s_ctl'%self.eachAlpha )
			self.ctl= nurbCircle[0]
			cirlceHistory= nurbCircle[1]
			ctlShape= cmds.listRelatives( self.ctl, children=1 )[0]
			
			grpA= cmds.group( self.ctl, name= self.name + '%s_ctl_cnst'%self.eachAlpha )
			grpZro= cmds.group( grpA, name= self.name + '%s_zro'%self.eachAlpha )
			grpPlug= cmds.group( grpZro, name= self.name + '%s_plug'%self.eachAlpha )
			self.grpC= cmds.group( grpPlug, name= self.name + '%s_grp'%self.eachAlpha )

		if self.AboveAlphabet == True:

			nurbCircle= cmds.circle( self.name + '%s_ctl'%self.index )
			self.ctl= nurbCircle[0]
			cirlceHistory= nurbCircle[1]
			ctlShape= cmds.listRelatives( self.ctl, children=1 )[0]
			
			grpA= cmds.group( self.ctl, name= self.name + '%s_ctl_cnst'%self.index )
			grpZro= cmds.group( grpA, name= self.name + '%s_zro'%self.index )
			grpPlug= cmds.group( grpZro, name= self.name + '%s_plug'%self.index )
			self.grpC= cmds.group( grpPlug, name= self.name + '%s_grp'%self.index )

		self.ctlList.append( self.ctl )
		self.grpList.append( self.grpC )
		self.cirlceHistoryList.append( cirlceHistory )
		self.ctlShapeList.append( ctlShape )

		cmds.addAttr( self.ctl, ln='globalScale',at='float', min=0, dv=1 )
		cmds.setAttr( self.ctl + '.globalScale',  k=1 )

		for each in self.scaleList:
			cmds.connectAttr( self.ctl + '.globalScale', self.ctl + each )
		for each in self.channelList:
			cmds.setAttr( self.ctl + each, lock=1, k=0 )
		
		# Radius.
		cmds.addAttr( ctlShape, ln='radius', at='float', min=0, dv=1 )
		cmds.setAttr( '%s.radius'%ctlShape, k=1, lock=0, channelBox=1 )

		cmds.connectAttr( '%s.radius'%ctlShape, '%s.radius'%cirlceHistory )


		# Center Shape Offsets..
		cmds.addAttr( ctlShape, ln='centerX', at='float', dv=0 )
		cmds.setAttr( '%s.centerX'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.addAttr( ctlShape, ln='centerY', at='float', dv=0 )
		cmds.setAttr( '%s.centerY'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.addAttr( ctlShape, ln='centerZ', at='float', dv=0 )
		cmds.setAttr( '%s.centerZ'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.centerX'%ctlShape, '%s.centerX'%cirlceHistory )
		cmds.connectAttr( '%s.centerY'%ctlShape, '%s.centerY'%cirlceHistory )
		cmds.connectAttr( '%s.centerZ'%ctlShape, '%s.centerZ'%cirlceHistory )

		# Normals Shape Offsets..
		cmds.addAttr( ctlShape, ln='normalX', at='float', dv=1 )
		cmds.setAttr( '%s.normalX'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.addAttr( ctlShape, ln='normalY', at='float', dv=0 )
		cmds.setAttr( '%s.normalY'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.addAttr( ctlShape, ln='normalZ', at='float', dv=0 )
		cmds.setAttr( '%s.normalZ'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.normalX'%ctlShape, '%s.normalX'%cirlceHistory )
		cmds.connectAttr( '%s.normalY'%ctlShape, '%s.normalY'%cirlceHistory )
		cmds.connectAttr( '%s.normalZ'%ctlShape, '%s.normalZ'%cirlceHistory )

		
		# Degree // resolution << Naming conflict
		cmds.addAttr( ctlShape, ln='resolution', at='float', dv=0, min=0, max=1 )
		cmds.setAttr( '%s.resolution'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.resolution'%ctlShape, '%s.degree'%cirlceHistory )

		# Sweep
		cmds.addAttr( ctlShape, ln='sweep', at='float', dv=360, min=0, max=360 )
		cmds.setAttr( '%s.sweep'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.sweep'%ctlShape, '%s.sweep'%cirlceHistory )

		
		# Sections
		cmds.addAttr( ctlShape, ln='sections', at='float', dv=1, min=0 )
		cmds.setAttr( '%s.sections'%ctlShape, k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.sections'%ctlShape, '%s.sections'%cirlceHistory )

		# Renames circle history.
		if self.AboveAlphabet == False:
			cmds.rename( cirlceHistory, 'HISTORY%s%s_ctl'%( self.name, self.eachAlpha ) )
		
		if self.AboveAlphabet == True:
			cmds.rename( cirlceHistory, 'HISTORY%s%s_ctl'%( self.name, self.index  ) )
			
		# Locking uneeded channels upon connection choice.
		if self.scaleCon == False:
			cmds.setAttr( '%s%s'%( self.ctl, '.globalScale' ), lock = False, keyable = False )
示例#46
0
    def createRibbon(self, *args):
        self.name = cmds.textFieldGrp(self.widgets["ribbonNameTFG"],
                                      q=True,
                                      tx=True)
        self.numDiv = (cmds.intFieldGrp(
            self.widgets["jointsIFG"], q=True, v=True)[0]) - 1
        self.fk = cmds.checkBox(self.widgets["fkSetupCB"], q=True, v=True)
        self.height = cmds.floatFieldGrp(self.widgets["heightFFG"],
                                         q=True,
                                         v1=True)
        self.ratio = cmds.floatFieldGrp(self.widgets["ratioFFG"],
                                        q=True,
                                        v1=True)
        self.axis = cmds.radioButtonGrp(self.widgets["axis"], q=True, sl=True)

        print("axis = :%s" % self.axis)
        self.ribbonName = "%s_ribbonGeo" % self.name
        self.numJoints = self.numDiv
        self.follicleList = []
        self.follicleJntList = []
        self.own = cmds.checkBox(self.widgets["existingGeoCB"], q=True, v=True)
        self.myGeo = cmds.textFieldButtonGrp(self.widgets["geoTFBG"],
                                             q=True,
                                             tx=True)
        self.dir = cmds.radioButtonGrp(self.widgets["directionRBG"],
                                       q=True,
                                       sl=True)
        print("dir: %s" % self.dir)
        self.centerPos = cmds.floatSliderGrp(self.widgets["centerPosFSG"],
                                             q=True,
                                             v=True)
        self.follicleGrpList = []

        #-----------make sure the num of divisions is at least 1
        #-----------create the nurbs plane in the correct axis (just make the plane in the axis and figure out how to rotate joint local rotational axes to match it) DON'T WORRY ABOUT THIS SO MUCH (IT'S HIDDEN), WORRY ABOUT THE CONTROLS BEING ORIENTED CORRECTLY!!!

        if self.own == 0:
            self.dir = 2
        if self.dir == 1:
            dir = "u"
            uDiv = self.numDiv
            vDiv = 1
        else:
            dir = "v'"
            uDiv = 1
            vDiv = self.numDiv

        # if self.axis  == 1:
        axis = [0, 0, 1]
        # elif self.axis  == 2:
        # 	axis = [0, 1, 0]
        # elif self.axis  == 3:
        # 	axis = [0, 0, 1]

        if self.own == 0:
            width = self.height / self.ratio
            #create the nurbsPlane
            cmds.nurbsPlane(ax=axis,
                            w=width,
                            lr=self.ratio,
                            d=3,
                            u=uDiv,
                            v=vDiv,
                            ch=0,
                            n=self.ribbonName)
            cmds.rebuildSurface(self.ribbonName,
                                ch=0,
                                rpo=1,
                                rt=0,
                                end=1,
                                kr=0,
                                kcp=0,
                                kc=0,
                                su=1,
                                du=1,
                                sv=self.numDiv,
                                dv=3,
                                tol=0.1,
                                fr=0,
                                dir=0)
            cmds.move(0, self.height / 2, 0, self.ribbonName)

            cmds.xform(self.ribbonName, ws=True, rp=[0, 0, 0])
        else:
            self.ribbonName = self.myGeo

        #find the ratio for the uv's (one dir will be .5, the other a result of the num joints)
        factor = 1.0 / self.numJoints

        #-------keep follicle joints separate, not parente under each follicle, separate group for those
        #-------follicle jnts each go under a ctrl (star) that is under a group. That group gets parent constrained to the follicles
        #-------these joints should be aligned with the follicles??? does that make a difference?

        #create the follicles on the surface, joints on the follicles
        for x in range(self.numJoints + 1):
            val = x * factor
            folName = "%s_follicle%s" % (self.name, x)
            #create a follicle in the right direction
            if self.dir == 1:
                follicle = rig.follicle(self.ribbonName, folName, val, 0.5)[0]
            else:
                follicle = rig.follicle(self.ribbonName, folName, 0.5, val)[0]

            self.follicleList.append(follicle)

            #create joint and parent to follicle
            jointName = "%s_fol%s_JNT" % (self.name, x)
            #---------have to figure out how to orient this correctly (just translate and rotate the joints (or the controls they're under))
            #create joint control? then move the control and the joint under it to the correct rot and pos
            folPos = cmds.xform(follicle, q=True, ws=True, t=True)
            folRot = cmds.xform(follicle, q=True, ws=True, ro=True)
            cmds.select(cl=True)
            folJoint = cmds.joint(n=jointName, p=(0, 0, 0))
            folGroup = cmds.group(
                folJoint, n="%s_GRP" %
                folJoint)  #this could become control for the joint
            cmds.xform(folGroup, a=True, ws=True, t=folPos)
            cmds.xform(folGroup, a=True, ws=True, ro=folRot)
            self.follicleJntList.append(folJoint)
            self.follicleGrpList.append(folGroup)
            cmds.parent(folGroup, follicle)

        #now create the control structure for the ribbon
        # basePosRaw = cmds.xform(self.follicleJntList[0], ws=True, q=True, t=True)
        # topPosRaw = cmds.xform(self.follicleJntList[self.numJoints], ws=True, q=True, t=True)
        # baseVec = om.MVector(basePosRaw[0], basePosRaw[1], basePosRaw[2])
        # topVec = om.MVector(topPosRaw[0], topPosRaw[1], topPosRaw[2])

        #find the center position
        ratio = self.centerPos  #number 0-1, .5 is the middle

        #---------------- now just need to feed adjusted uv pos of mid into "alignToUV"
        #---------------- here i should align each top, mid, end to the UV pos I want. . .
        midUV = 0.5 * 2 * ratio

        #create ctrl structure
        prefixList = ["base", "mid", "top"]
        uvList = [0.0, midUV, 1.0]
        groupList = []
        # vecList = [baseVec, midVec, topVec]
        locList = []
        upLocList = []
        ctrlList = []
        ctrlJntList = []

        #-----------create some options with switches for how things aim, etc at each other
        #--------deal with axis stuff below
        #-------then down below we need to use object space to move the locators
        #--------below must figure out how to parent the up locs to controls? ???
        #for each of "base", "mid", "top" create the control structure
        for i in range(3):
            groupName = "%s_%s_GRP" % (self.name, prefixList[i])
            groupList.append(groupName)

            # vecName = "%sVec"%prefixList[i]
            # vecList.append(vecName)
            #----------------create the whole setup at 000, then align the top group
            #create group
            cmds.group(empty=True, n=groupName)

            thisPos = cmds.xform(groupName, ws=True, q=True, t=True)

            #create and parent constraint locator
            locName = "%s_%s_constr_LOC" % (self.name, prefixList[i])
            locList.append(locName)

            cmds.spaceLocator(n=locName)
            cmds.xform(locName,
                       ws=True,
                       t=(thisPos[0], thisPos[1], thisPos[2]))

            cmds.parent(locName, groupName)

            #create a parent constraint locator under the aim locator

            #create up locator
            upLocName = "%s_%s_up_LOC" % (self.name, prefixList[i])
            upLocList.append(upLocName)

            cmds.spaceLocator(n=upLocName)
            #create option for what direction the up vec is?
            #----------------axis here
            cmds.xform(upLocName, ws=True, t=[0, 0, -1])
            cmds.parent(upLocName, groupName)

            #create controls
            ctrlName = "%s_%s_CTRL" % (self.name, prefixList[i])
            ctrlList.append(ctrlName)
            #----------------axis here
            cmds.circle(nr=(0, 1, 0), r=(self.height / 10 * 3), n=ctrlName)
            cmds.parent(ctrlName, locName)

            #create control joints (will already be parented to ctrl)
            jntName = "%s_%s_ctrl_JNT" % (self.name, prefixList[i])
            ctrlJntList.append(jntName)

            ctrlJoint = cmds.joint(n=jntName, p=(0, 0, 0))
            #----------------axis here
            #align group to surface
            rig.alignToUV(targetObj=groupName,
                          sourceObj=self.ribbonName,
                          sourceU=0.5,
                          sourceV=uvList[i],
                          mainAxis="+z",
                          secAxis="+y",
                          UorV="v")

        #now bind the nurbs geo
        cmds.select(cl=True)

        for jnt in ctrlJntList:
            cmds.select(jnt, add=True)
            cmds.select(self.ribbonName, add=True)

        cmds.skinCluster(mi=3, sw=0.5, omi=True, tsb=True, nw=1)

        #-------here add in the constraints to make this work properly. . . on each control have it tell what to aim at? lock these or not (depends on whether it's FK or not?)
        #-------also add in the FK option here, too. . .

        #base aim constrain to look at center
        #top aim constrain to look at center
        #mid parent constrain to either?, aim to either, point to either?

        #start packaging stuff up
        #-------hide the locators

        folGroup = cmds.group(empty=True, n="%s_follicles_GRP" % self.name)
        for fol in self.follicleList:
            cmds.parent(fol, folGroup)
        cmds.setAttr("%s.inheritsTransform" % folGroup, 0)

        ctrlsGroup = cmds.group(empty=True, n="%s_ctrls_GRP" % self.name)
        for grp in groupList:
            cmds.parent(grp, ctrlsGroup)

        geoGroup = cmds.group(empty=True, n="%s_geo_GRP" % self.name)
        cmds.parent(self.ribbonName, geoGroup)
        cmds.setAttr("%s.inheritsTransform" % geoGroup, 0)

        ribbonGroup = cmds.group(empty=True, n="%s_ribbon_GRP" % self.name)
        cmds.parent(folGroup, ribbonGroup)
        cmds.parent(ctrlsGroup, ribbonGroup)
        cmds.parent(geoGroup, ribbonGroup)

        cmds.select(ribbonGroup)
示例#47
0
from maya import cmds
'''
This script is for joining multiple curves into one curve Object
'''
sel = cmds.ls(selection=True)
if sel:
    cmds.makeIdentity(sel,
                      apply=True,
                      t=True,
                      r=True,
                      s=True,
                      n=False,
                      pn=True)
    grp = cmds.group(em=True, name='joined_CTR_01')
    all_shapes = []
    for obj in sel:
        shapes = cmds.listRelatives(obj, shapes=True)
        if shapes:
            for s in shapes:
                cmds.parent(obj + "|" + s, grp, s=True, r=True)
    cmds.delete(sel)
    cmds.xform(grp, cp=True)
else:
    print "There's no selection"
	def createLayerControl(self, *args ):
		''' Creates multiLayeredControllers. '''
		self.grpList= []
		self.ctlShapeList= []
		self.ctlList= []
		self.cirlceHistoryList= []

		
		for i in range(3):

			nurbCircle= cmds.circle( name= self.name + '%s%s_ctl'%( self.index + 1, self.alpha[i] ) )
			ctl= nurbCircle[0]
			ctlShape= cmds.listRelatives( ctl, children= 1 )[0]
			__cirlceHistory= nurbCircle[1]
			cirlceHistory= cmds.rename( __cirlceHistory, 'HISTORY%s%s%s_ctl'%( self.name, self.index + 1, self.alpha[i] ) )

			#print ctl
			grpA= cmds.group( ctl, name= self.name + '%s%s_ctl_cnst'%( self.index + 1, self.alpha[i] ) )
			grpZro= cmds.group( grpA, name= self.name + '%s%s_zro'%( self.index + 1, self.alpha[i] ) )
			grpPlug= cmds.group( grpZro, name= self.name + '%s%s_plug'%( self.index + 1, self.alpha[i] ) )
			grpB= cmds.group( grpPlug, name= self.name + '%s%s_grp'%( self.index + 1, self.alpha[i] ) )

			self.ctlList.append( ctl )
			self.grpList.append( grpB )
			self.ctlShapeList.append( ctlShape )
			self.cirlceHistoryList.append( cirlceHistory )
			
			cmds.addAttr( ctl, ln='globalScale',at='float', min=0, dv=1 )
			cmds.setAttr( ctl + '.globalScale',  k=1 )

			for each in self.scaleList:
				cmds.connectAttr( ctl + '.globalScale', ctl + each )
			for each in self.channelList:
				cmds.setAttr( ctl + each, lock=1, k=0 )

		# Center Shape Offsets.
		cmds.addAttr( self.ctlShapeList[0], ln='centerX', at='float', min=0, dv=0 )
		cmds.setAttr( '%s.centerX'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.addAttr( self.ctlShapeList[0], ln='centerY', at='float', min=0, dv=0 )
		cmds.setAttr( '%s.centerY'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.addAttr( self.ctlShapeList[0], ln='centerZ', at='float', min=0, dv=0 )
		cmds.setAttr( '%s.centerZ'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.centerX'%self.ctlShapeList[0], '%s.centerX'%self.cirlceHistoryList[0] )
		cmds.connectAttr( '%s.centerY'%self.ctlShapeList[0], '%s.centerY'%self.cirlceHistoryList[0] )
		cmds.connectAttr( '%s.centerZ'%self.ctlShapeList[0], '%s.centerZ'%self.cirlceHistoryList[0] )

		# Normals Shape Offsets.
		cmds.addAttr( self.ctlShapeList[0], ln='normalX', at='float', dv=0 )
		cmds.setAttr( '%s.normalX'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.addAttr( self.ctlShapeList[0], ln='normalY', at='float', dv=0 )
		cmds.setAttr( '%s.normalY'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.addAttr( self.ctlShapeList[0], ln='normalZ', at='float', dv=0 )
		cmds.setAttr( '%s.normalZ'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.normalX'%self.ctlShapeList[0], '%s.normalX'%self.cirlceHistoryList[0] )
		cmds.connectAttr( '%s.normalY'%self.ctlShapeList[0], '%s.normalY'%self.cirlceHistoryList[0] )
		cmds.connectAttr( '%s.normalZ'%self.ctlShapeList[0], '%s.normalZ'%self.cirlceHistoryList[0] )

		# Radius.
		cmds.addAttr( self.ctlShapeList[0], ln='radius', at='float', dv=1, min=0 )
		cmds.setAttr( '%s.radius'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.radius'%self.ctlShapeList[0], '%s.radius'%self.cirlceHistoryList[0] )

		# Degree >> resolution << Naming conflict.
		cmds.addAttr( self.ctlShapeList[0], ln='resolution', at='float', dv=0, min=0, max=1 )
		cmds.setAttr( '%s.resolution'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.resolution'%self.ctlShapeList[0], '%s.degree'%self.cirlceHistoryList[0] )

		# Sweep.
		cmds.addAttr( self.ctlShapeList[0], ln='sweep', at='float', dv=360 , min=0, max=360 )
		cmds.setAttr( '%s.sweep'%self.ctlShapeList[0], k=1, lock=0, channelBox=1 )
		cmds.connectAttr( '%s.sweep'%self.ctlShapeList[0], '%s.sweep'%self.cirlceHistoryList[0] )

		# Adds controlB, controlC VIS attributes.
		cmds.addAttr( self.ctlList[0], ln='controlB', at='float', min=0, max=1, dv=0, hidden=0 )
		cmds.setAttr( self.ctlList[0] + '.controlB', k=1 )
		cmds.addAttr( self.ctlList[0], ln='controlC',at='float', min=0, max=1, dv=0, hidden=0)
		cmds.setAttr( self.ctlList[0] + '.controlC', k=1 )
		cmds.connectAttr( self.ctlList[0] + '.controlB', self.ctlShapeList[1] + '.visibility' )
		cmds.connectAttr( self.ctlList[0] + '.controlC', self.ctlShapeList[2] + '.visibility' )
		
		# Adds a MultiplyDivide node to offset the radius values on the controlB, controlC.
		MDNb= cmds.createNode( 'multiplyDivide',name= self.name + '%iB_mdn'%( self.index + 1 ) )
		MDNc= cmds.createNode( 'multiplyDivide',name= self.name + '%iC_mdn'%( self.index + 1 ) )
		cmds.connectAttr( self.ctlShapeList[0] + '.radius', MDNb + '.input1X' )
		cmds.connectAttr( self.ctlShapeList[0] + '.radius', MDNc + '.input1X' )
		cmds.connectAttr( MDNb + '.outputX', self.cirlceHistoryList[1] + '.radius' )
		cmds.connectAttr( MDNc + '.outputX', self.cirlceHistoryList[2] + '.radius' )

		for i in range( 3, 6 ):
			cmds.setAttr( MDNb + self.mdnChannel[i], 0.75 )
			cmds.setAttr( MDNc + self.mdnChannel[i], 0.50 )

		# propagate the attributes to the coltrolB, controlC.
		# Centers.
		cmds.connectAttr( self.ctlShapeList[0] + '.centerX', self.cirlceHistoryList[1] + '.centerX' )
		cmds.connectAttr( self.ctlShapeList[0] + '.centerY', self.cirlceHistoryList[1] + '.centerY' )
		cmds.connectAttr( self.ctlShapeList[0] + '.centerZ', self.cirlceHistoryList[1] + '.centerZ' )
		cmds.connectAttr( self.ctlShapeList[0] + '.centerX', self.cirlceHistoryList[2] + '.centerX' )
		cmds.connectAttr( self.ctlShapeList[0] + '.centerY', self.cirlceHistoryList[2] + '.centerY' )
		cmds.connectAttr( self.ctlShapeList[0] + '.centerZ', self.cirlceHistoryList[2] + '.centerZ' )
	
		# Normals
		cmds.connectAttr( self.ctlShapeList[0] + '.normalX', self.cirlceHistoryList[1] + '.normalX' )
		cmds.connectAttr( self.ctlShapeList[0] + '.normalY', self.cirlceHistoryList[1] + '.normalY' )
		cmds.connectAttr( self.ctlShapeList[0] + '.normalZ', self.cirlceHistoryList[1] + '.normalZ' )
		cmds.connectAttr( self.ctlShapeList[0] + '.normalX', self.cirlceHistoryList[2] + '.normalX' )
		cmds.connectAttr( self.ctlShapeList[0] + '.normalY', self.cirlceHistoryList[2] + '.normalY' )
		cmds.connectAttr( self.ctlShapeList[0] + '.normalZ', self.cirlceHistoryList[2] + '.normalZ' )
	
		# Resolutions
		cmds.connectAttr( self.ctlShapeList[0] + '.sweep', self.cirlceHistoryList[1] + '.degree' )
		cmds.connectAttr( self.ctlShapeList[0] + '.sweep', self.cirlceHistoryList[2] + '.degree' )
	
		# Sweep.
		cmds.connectAttr( self.ctlShapeList[0] + '.sweep', self.cirlceHistoryList[1] + '.sweep' )
		cmds.connectAttr( self.ctlShapeList[0] + '.sweep', self.cirlceHistoryList[2] + '.sweep' )
		
		# Parents the respective controllers under the respective _cnst groups.
		cmds.parent( self.grpList[1], self.ctlList[0] )
		cmds.parent( self.grpList[2], self.ctlList[1] )

		for each in self.grpChannel:
			cmds.setAttr( self.grpList[1] + each, lock=1, k=0 )
			cmds.setAttr( self.grpList[2] + each, lock=1, k=0 )

		
		# Locking uneeded channels upon connection choice.
		if self.scaleCon == False:
			cmds.setAttr( '%s%s'%( self.ctlList[0], '.globalScale' ), lock = False, keyable = False )
示例#49
0
    def __init__(self,
                 prefix='new',
                 scale=1.0,
                 translateTo='',
                 rotateTo='',
                 not_rot_shape=False,
                 parent='',
                 shape='circle',
                 lockChannels=['s', 'v']):
        """
        @param prefix: str, prefix to name new object groups
        @param scale: float, scale value for size of control.
        @param translateTo: str, reference object for control position
        @param rotateTo: str, reference object for control orientation
        @param parent: str, object to be parent of new control
        @param shape: str, control shape type
        @param lockChannels: list(str), list of channels on control to be locked and non-keyable
        @return: none
        """

        ctrlObject = None
        circleNormal = [1, 0, 0]
        degree = 3
        sections = 8

        # control shape library
        if shape in ['circle', 'circleX']:
            circleNormal = [1, 0, 0]
            degree = 3
            sections = 8
        elif shape == 'circleY':
            circleNormal = [0, 1, 0]
            degree = 3
            sections = 8
        elif shape == 'circleZ':
            circleNormal = [0, 0, 1]
            degree = 3
            sections = 8
        elif shape in ['diamond', 'diamondX']:
            circleNormal = [1, 0, 0]
            degree = 1
            sections = 4
        elif shape == 'diamondY':
            circleNormal = [0, 1, 0]
            degree = 1
            sections = 4
        elif shape == 'diamondZ':
            circleNormal = [0, 0, 1]
            degree = 1
            sections = 4
        elif shape == 'sphere':
            ctrlObject = mc.circle(name=prefix + '_ctrl',
                                   constructionHistory=False,
                                   normal=[1, 0, 0],
                                   radius=scale)[0]
            addShape1 = mc.circle(name=prefix + '_ctrl',
                                  constructionHistory=False,
                                  normal=[0, 1, 0],
                                  radius=scale)[0]
            addShape2 = mc.circle(name=prefix + '_ctrl',
                                  constructionHistory=False,
                                  normal=[0, 0, 1],
                                  radius=scale)[0]
            mc.parent(mc.listRelatives(addShape1, s=1),
                      ctrlObject,
                      relative=1,
                      shape=1)
            mc.parent(mc.listRelatives(addShape2, s=1),
                      ctrlObject,
                      relative=1,
                      shape=1)
            mc.delete(addShape1)
            mc.delete(addShape2)
        elif shape == 'cube':
            ctrlObject = mc.curve(name=prefix + '_ctrl',
                                  d=True,
                                  p=[(0.5, 0.5, 0.5), (0.5, -0.5, 0.5),
                                     (-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5),
                                     (0.5, 0.5, 0.5), (0.5, -0.5, 0.5),
                                     (0.5, -0.5, -0.5), (0.5, 0.5, -0.5),
                                     (0.5, 0.5, 0.5), (0.5, 0.5, -0.5),
                                     (0.5, -0.5, -0.5), (-0.5, -0.5, -0.5),
                                     (-0.5, 0.5, -0.5), (0.5, 0.5, -0.5),
                                     (-0.5, 0.5, -0.5), (-0.5, -0.5, -0.5),
                                     (-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5),
                                     (-0.5, 0.5, -0.5)],
                                  k=[
                                      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                                      13, 14, 15, 16, 17, 18
                                  ])

            mc.scale(scale, scale, scale, ctrlObject + '.cv[0:18]')
        elif shape == 'rectangle':
            ctrlObject = mc.curve(name=prefix + '_ctrl',
                                  d=True,
                                  p=[(0.7, 0.3, 0.5), (0.7, -0.3, 0.5),
                                     (-0.7, -0.3, 0.5), (-0.7, 0.3, 0.5),
                                     (0.7, 0.3, 0.5), (0.7, -0.3, 0.5),
                                     (0.7, -0.3, -0.5), (0.7, 0.3, -0.5),
                                     (0.7, 0.3, 0.5), (0.7, 0.3, -0.5),
                                     (0.7, -0.3, -0.5), (-0.7, -0.3, -0.5),
                                     (-0.7, 0.3, -0.5), (0.7, 0.3, -0.5),
                                     (-0.7, 0.3, -0.5), (-0.7, -0.3, -0.5),
                                     (-0.7, -0.3, 0.5), (-0.7, 0.3, 0.5),
                                     (-0.7, 0.3, -0.5)])

            mc.scale(scale, scale, scale, ctrlObject + '.cv[0:18]')
        elif shape == 'global':
            ctrlObject = mc.curve(name=prefix + '_ctrl',
                                  d=1,
                                  p=[(-5.472546, 0, 1.778139),
                                     (-5.472546, 0, -1.778137),
                                     (-4.655226, 0, -3.382219),
                                     (-3.38222, 0, -4.655226),
                                     (-1.778138, 0, -5.472547),
                                     (1.778139, 0, -5.472547),
                                     (3.382222, 0, -4.655227),
                                     (4.655229, 0, -3.38222),
                                     (5.47255, 0, -1.778138),
                                     (5.472546, 0, 1.778139),
                                     (4.655226, 0, 3.382221),
                                     (3.38222, 0, 4.655227),
                                     (1.778138, 0, 5.472547),
                                     (-1.778137, 0, 5.472547),
                                     (-3.382219, 0, 4.655227),
                                     (-4.655226, 0, 3.382221),
                                     (-5.472546, 0, 1.778139)])
            globalShape = mc.listRelatives(ctrlObject, s=True)
            globalShape = mc.rename(globalShape, ctrlObject + 'WorldShape')
            mc.scale(scale, scale, scale, ctrlObject + '.cv[0:16]')

            worldForward = mc.curve(name=prefix + 'worldForward',
                                    d=1,
                                    p=[(1.778138, 0, 5.472547),
                                       (6.55294e-07, 0, 8.059775),
                                       (-1.778137, 0, 5.472547)])
            worldBackward = mc.curve(name=prefix + 'worldBackward',
                                     d=1,
                                     p=[(-1.778138, 0, -5.472547),
                                        (8.61953e-07, 0, -6.934346),
                                        (1.778139, 0, -5.472547)])
            worldLeft = mc.curve(name=prefix + 'worldRight',
                                 d=1,
                                 p=[(5.47255, 0, -1.778138),
                                    (6.934345, 0, 1.43659e-06),
                                    (5.472546, 0, 1.778139)])
            worldRight = mc.curve(name=prefix + 'worldLeft',
                                  d=1,
                                  p=[(-5.472546, 0, -1.778137),
                                     (-6.934345, 0, 1.43659e-06),
                                     (-5.472546, 0, 1.778139)])

            globalExtraShapes = []
            globalExtraShapes.extend(
                [worldForward, worldBackward, worldLeft, worldRight])
            for shape in globalExtraShapes:
                getShape = mc.listRelatives(shape, s=True)
                nn = shape + 'Shape'
                newShapeName = mc.rename(getShape, nn)
                mc.parent(newShapeName, ctrlObject, s=True, r=True)
                mc.scale(scale, scale, scale, newShapeName + '.cv[0:2]')

            mc.delete(worldForward, worldBackward, worldLeft, worldRight)
        elif shape == 'settings':
            ctrlObject = mc.curve(name=prefix + '_ctrl',
                                  d=1,
                                  p=[(0, 0, 1), (-1, 0, 1), (-1, 0, 0),
                                     (-2, 0, 0), (-2, 0, -1), (-1, 0, -1),
                                     (-1, 0, -2), (0, 0, -2), (0, 0, -1),
                                     (1, 0, -1), (1, 0, 0), (0, 0, 0),
                                     (0, 0, 1)])
        elif shape == 'offset':
            ctrlObject = mc.curve(name=prefix + '_ctrl',
                                  d=1,
                                  p=[(-5.472546, 0, 1.778139),
                                     (-5.472546, 0, -1.778137),
                                     (-4.655226, 0, -3.382219),
                                     (-3.38222, 0, -4.655226),
                                     (-1.778138, 0, -5.472547),
                                     (1.778139, 0, -5.472547),
                                     (3.382222, 0, -4.655227),
                                     (4.655229, 0, -3.38222),
                                     (5.47255, 0, -1.778138),
                                     (5.472546, 0, 1.778139),
                                     (4.655226, 0, 3.382221),
                                     (3.38222, 0, 4.655227),
                                     (1.778138, 0, 5.472547),
                                     (-1.778137, 0, 5.472547),
                                     (-3.382219, 0, 4.655227),
                                     (-4.655226, 0, 3.382221),
                                     (-5.472546, 0, 1.778139)])
            mc.scale(scale, scale, scale, ctrlObject + '.cv[0:16]')
        elif shape == 'fancy_sphere':
            ctrlObject = mc.curve(name=prefix + '_ctrl',
                                  d=1,
                                  p=[(0, 3.21, 0), (0, 2.96, 1.23),
                                     (0, 2.27, 2.27), (0, 1.23, 2.96),
                                     (0, 0, 3.21), (0, -1.23, 2.96),
                                     (0, -2.27, 2.27), (0, -2.97, 1.23),
                                     (0, -3.21, 0), (0, -2.96, -1.23),
                                     (0, -2.27, -2.27), (0, -1.23, -2.96),
                                     (0, 0, -3.21), (0, 1.23, -2.96),
                                     (0, 2.27, -2.27), (0, 2.96, -1.23),
                                     (0, 3.21, 0), (-0.87, 2.96, 0.97),
                                     (-1.60, 2.27, 1.60), (-2.09, 1.23, 2.09),
                                     (-2.27, 0, 2.27), (-2.09, -1.23, 2.09),
                                     (-1.60, -2.27, 1.60), (-0.87,
                                                            -2.96, 0.87),
                                     (0, -3.21, 0), (0.87, -2.97, -0.87),
                                     (1.60, -2.27, -1.60),
                                     (2.09, -1.23, -2.09), (2.27, 0, -2.27),
                                     (2.09, 1.23, -2.09), (1.60, 2.27, -1.60),
                                     (0.87, 2.86, -0.87), (0, 3.21, 0),
                                     (-1.23, 2.97, 0), (-2.27, 2.27, 0),
                                     (-2.97, 1.23, 0), (-3.21, 0, 0),
                                     (-2.97, -1.23, 0), (-2.27, -2.27, 0),
                                     (-1.23, -2.96, 0), (0, -3.21, 0),
                                     (1.23, -2.97, 0), (2.27, -2.27, 0),
                                     (2.97, -1.23, 0), (3.21, 0, 0),
                                     (2.97, 1.23, 0), (2.27, 2.27, 0),
                                     (1.23, 2.97, 0), (0, 3.21, 0),
                                     (-0.87, 2.97, -0.87), (-1.60, 2.27,
                                                            -1.60),
                                     (-2.09, 1.23, -2.09), (-2.27, 0, -2.27),
                                     (-2.09, -1.23, -2.09),
                                     (-1.60, -2.27, -1.60),
                                     (-0.87, -2.96, -0.87), (0, -3.21, 0),
                                     (0.87, -2.97, 0.87), (1.60, -2.27, 1.60),
                                     (2.09, -1.23, 2.09), (2.27, 0, 2.27),
                                     (2.09, 1.23, 2.09), (1.60, 2.27, 1.60),
                                     (0.87, 2.97, 0.87), (0, 3.21, 0),
                                     (1.23, 2.97, 0), (2.27, 2.27, 0),
                                     (2.97, 1.23, 0), (3.21, 0, 0),
                                     (2.27, 0, 2.27), (0, 0, 3.21),
                                     (-2.27, 0, 2.27), (-3.21, 0, 0),
                                     (-2.27, 0, -2.27), (0, 0, -3.21),
                                     (2.27, 0, -2.27), (3.21, 0, 0),
                                     (2.27, 0, 2.27), (0, 0, 3.21)])
        elif shape == 'line_sphere':
            ctrlObject = mc.curve(name=prefix + '_ctrl',
                                  d=1,
                                  p=[(0, 0, 0), (0, 0, 4.6666666666666661),
                                     (0, 0, 9.3333333333333321), (0, 0, 14)])
            linePosz = mc.getAttr(ctrlObject + ".cv[3].zValue")
            addShape1 = mc.circle(name=prefix + '_ctrl',
                                  constructionHistory=False,
                                  normal=[1, 0, 0],
                                  radius=scale * 0.5)[0]
            addShape2 = mc.circle(name=prefix + '_ctrl',
                                  constructionHistory=False,
                                  normal=[0, 1, 0],
                                  radius=scale * 0.5)[0]
            addShape3 = mc.circle(name=prefix + '_ctrl',
                                  constructionHistory=False,
                                  normal=[0, 0, 1],
                                  radius=scale * 0.5)[0]
            mc.setAttr(addShape1 + ".tz", 17)
            mc.setAttr(addShape2 + ".tz", 17)
            mc.setAttr(addShape3 + ".tz", 17)
            mc.makeIdentity(addShape1, apply=True, t=True)
            mc.makeIdentity(addShape2, apply=True, t=True)
            mc.makeIdentity(addShape3, apply=True, t=True)
            mc.parent(mc.listRelatives(addShape1, s=1),
                      ctrlObject,
                      relative=1,
                      shape=1)
            mc.parent(mc.listRelatives(addShape2, s=1),
                      ctrlObject,
                      relative=1,
                      shape=1)
            mc.parent(mc.listRelatives(addShape3, s=1),
                      ctrlObject,
                      relative=1,
                      shape=1)
            mc.delete(addShape1)
            mc.delete(addShape2)
            mc.delete(addShape3)
        if not ctrlObject:

            ctrlObject = mc.circle(name=prefix + '_ctrl',
                                   constructionHistory=False,
                                   normal=circleNormal,
                                   degree=degree,
                                   sections=sections,
                                   radius=scale)[0]

        ctrlOffset = mc.group(n=prefix + 'Offset_grp', em=1)
        mc.parent(ctrlObject, ctrlOffset)

        # set control color
        getCtrlShape = mc.listRelatives(ctrlObject, s=1)
        [mc.setAttr(s + '.ove', 1) for s in getCtrlShape]

        if prefix.startswith('l_'):
            [mc.setAttr(s + '.ovc', 6) for s in getCtrlShape]
        elif prefix.startswith('r_'):
            [mc.setAttr(s + '.ovc', 13) for s in getCtrlShape]
        else:
            [mc.setAttr(s + '.ovc', 22) for s in getCtrlShape]

        # translate control
        if mc.objExists(translateTo):
            mc.delete(mc.pointConstraint(translateTo, ctrlOffset))

        # rotate control
        if mc.objExists(rotateTo):
            if not_rot_shape:
                shapes = mc.listRelatives(ctrlObject, shapes=True)
                loc = mc.spaceLocator()[0]
                for shape in shapes:
                    mc.parent(shape, loc, relative=1, shape=1)
                mc.delete(mc.orientConstraint(rotateTo, ctrlOffset))
                mc.parent(loc, rotateTo)
                mc.setAttr(loc + ".tx", 0)
                mc.setAttr(loc + ".ty", 0)
                mc.setAttr(loc + ".tz", 0)
                mc.makeIdentity(loc, apply=True, r=True, t=True)
                for shape in shapes:
                    mc.parent(shape, ctrlObject, relative=1, shape=1)
                mc.delete(loc)
            else:
                mc.delete(mc.orientConstraint(rotateTo, ctrlOffset))

        # parent control
        if mc.objExists(parent):
            mc.parent(ctrlOffset, parent)

        # lock control channels
        singleAttributeLockList = []

        for ch in lockChannels:
            if ch in ['t', 'r', 's']:
                for axis in ['x', 'y', 'z']:
                    attr = ch + axis
                    singleAttributeLockList.append(attr)
            else:
                singleAttributeLockList.append(ch)
        for attr in singleAttributeLockList:
            mc.setAttr(ctrlObject + '.' + attr, l=1, k=0)

        # add public variables
        self.C = ctrlObject
        self.Off = ctrlOffset
	def locators(self, *args):
		''' Locator(s) function. Independent from the __init__ module. '''

		selection= cmds.ls( sl=True, fl=True )

		parentSelection = cmds.checkBox( self.locCheckBoxes[0], value= True, query= True )
		addAdditionalGroups = cmds.checkBox( self.locCheckBoxes[1], value= True, query= True )
		selNaming = cmds.checkBox( self.locCheckBoxes[2], value= True, query= True )
		alpha = string.uppercase
		object= []
		locators= []

		AboveAlphabet = False
		vtxSel = False

		if not selection:
			om.MGlobal.displayWarning('Please select a normalform object or a vertex component.')
			sys.exit()


		if selNaming == False:
			locName = cmds.textField( self.locTexts, query= True, tx=1 )

			if not locName:
				om.MGlobal.displayWarning('Cannot have an empty text field!.')
				sys.exit()


			

		print '---------------------------------------------'

		try:

			if selection[0].split('.')[1].split('[')[0] == 'vtx':
				print 'Selection is a vertex.'

				object = selection[0].split('.')[0]
	
				if selNaming == True:
					locName= 'geo_%s_grp'%selection[0].split('.')[0]

	
				vtxSel = True

		except:

			pass

		if cmds.nodeType(selection[0]) == 'normalform':
			print 'Selection is a normalform.'

		if addAdditionalGroups == True:
			print 'Adding additional groups:  %s'%addAdditionalGroups

		if selNaming == True:
			print 'Use naming from selection:  %s'%selNaming

		if selNaming == False:
			print 'Use naming from textField:  %s'%selNaming

		if parentSelection == True:
			print 'Parenting selections:  %s'%parentSelection


		# Create locators in the center of geos.
		if vtxSel == False:

			if (len( selection ) < 26) == True:
				AboveAlphabet = False
				print "%s is greater than 25: %s"%( len(selection), AboveAlphabet)
	
			if (len( selection ) > 26) == True:
				AboveAlphabet = True
				print "%s is greater than 26: %s"%( len(selection), AboveAlphabet)



			for index, eachSel in enumerate(selection):
				

				if cmds.getAttr( '%s.tx'%eachSel, k=0, l=1 ):

					cmds.setAttr( '%s.tx'%eachSel, k=1, l=0 )
					cmds.setAttr( '%s.ty'%eachSel, k=1, l=0 )
					cmds.setAttr( '%s.tz'%eachSel, k=1, l=0 )

				if cmds.getAttr( '%s.tx'%eachSel, k=1, l=0 ):

					# Alphabet has 26 letters. If selection is > 26, do numbers.
					if selNaming == True:

						locName = eachSel

						if "_grp" in eachSel:
							locName.replace( "_grp", "" )


						if "_GRP" in eachSel:
							locName.replace( "_GRP", "" )


						if "_GP" in eachSel:
							locName.replace( "_GP", "" )

						if "_gp" in eachSel:
							locName.replace( "_gp", "" )


						if AboveAlphabet == False:
							point= cmds.spaceLocator( name= '%s%s_grp'%( locName, alpha[index] ) )

						if AboveAlphabet == True:
							point= cmds.spaceLocator( name= '%s%s_grp'%( locName, index ) )



					if selNaming == False:



						if AboveAlphabet == False:
							point= cmds.spaceLocator( name= '%s%s_grp'%( locName, alpha[index] ) )

						if AboveAlphabet == True:
							point= cmds.spaceLocator( name= '%s%s_grp'%( locName, index ) )
					

					cmds.align( point, eachSel, xAxis='mid', yAxis='mid', zAxis='mid', atl=True )

					print 'Created a locator for: %s'%eachSel


				if addAdditionalGroups == True:

					rename = point[0].replace( "_grp", "" )
					dupl= cmds.duplicate( point, name = rename + '_plug' )

					cmds.select(clear=True)
					originGrp= cmds.group( name= '%s_zro'%rename, em=True, world=True )
					cmds.parent( originGrp, dupl )

					cmds.delete( cmds.listRelatives( dupl, shapes=True )[0] )

					cmds.parent( dupl, point )


				if parentSelection == True:

					if addAdditionalGroups == False:
						cmds.parent( eachSel, point )

					if addAdditionalGroups == True:
						cmds.parent( eachSel, originGrp )


				locators.append( point )

			cmds.select(clear=True)
			for eachLoc in locators:
				cmds.select( eachLoc, tgl=True )

			# End of len(selection) function of locator method.
			print '---------------------------------------------'
			
		
		# Create locators with aim constrained towards a vertex.
		if vtxSel == True:

			if len(selection) == 1:

				vertexA= selection[0].split('.')[1].split('[')[1].split(']')[0].split(':')[0]
				print selection[0].split('.')[0] + '.vtx[%s]'%vertexA

				Target0= cmds.xform( selection[0].split('.')[0] + '.vtx[%s]'%vertexA, translation=True, worldSpace=True, query=True )

				point= cmds.spaceLocator( name= locName )

				cmds.xform( point, translation= Target0 )

				if addAdditionalGroups == True:

					rename = point[0].replace( "_grp", "" )
					dupl= cmds.duplicate( point, name = rename + '_plug' )

					cmds.select(clear=True)
					originGrp= cmds.group( name= '%s_zro'%rename, em=True, world=True )
					cmds.parent( originGrp, dupl )

					cmds.delete( cmds.listRelatives( dupl, shapes=True )[0] )

					cmds.parent( dupl, point )


				if parentSelection == True:

					if addAdditionalGroups == False:
						cmds.parent( object, point )

					if addAdditionalGroups == True:
						cmds.parent( object, originGrp )

					cmds.select( point )


				print( ' Created a locator on a vertex:  %s'%selection[0].split('.')[1] )


			if len(selection) == 2:

				start= cmds.spaceLocator( name='start_placer_loc' )
				end= cmds.spaceLocator( name='end_placer_loc' )

				point= cmds.spaceLocator( name= locName )

				locList= cmds.ls( start, end )

				target0= cmds.xform( selection[0], translation=True, worldSpace=True, query=True )
				target1= cmds.xform( selection[1], translation=True, worldSpace=True, query=True )

				cmds.xform( start, ws=1, t= target0 )
				cmds.xform( end, ws=1, t= target1 )

				cmds.pointConstraint( start, end, point, maintainOffset=False )
				cmds.aimConstraint( start, point, maintainOffset=False )


				cmds.delete(start, end)


				if addAdditionalGroups == True:

					rename = point[0].replace( "_grp", "" )
					dupl= cmds.duplicate( point, name = rename + '_plug' )

					cmds.select(clear=True)
					originGrp= cmds.group( name= '%s_zro'%rename, em=True, world=True )
					cmds.parent( originGrp, dupl )

					cmds.delete( cmds.listRelatives( dupl, shapes=True )[0] )

					cmds.parent( dupl, point )


				if parentSelection == True:

					if addAdditionalGroups == False:
						cmds.parent( object, point )

					if addAdditionalGroups == True:
						cmds.parent( object, originGrp )

					cmds.select( point )



			if len(selection) > 2:

				# Credit: Marc English for the boundingbox.
				point= cmds.spaceLocator( name= locName )


				bbox =  cmds.exactWorldBoundingBox(selection)	

				x = (bbox[0] + bbox[3]) / 2	
				y = (bbox[1] + bbox[4]) / 2	
				z = (bbox[2] + bbox[5]) / 2


				cmds.setAttr( point ,x,y,z)


				if addAdditionalGroups == True:

					rename = point[0].replace( "_grp", "" )
					dupl= cmds.duplicate( point, name = rename + '_plug' )

					cmds.select(clear=True)
					originGrp= cmds.group( name= '%s_zro'%rename, em=True, world=True )
					cmds.parent( originGrp, dupl )

					cmds.delete( cmds.listRelatives( dupl, shapes=True )[0] )

					cmds.parent( dupl, point )


				if parentSelection == True:

					if addAdditionalGroups == False:
						cmds.parent( object, point )

					if addAdditionalGroups == True:
						cmds.parent( object, originGrp )

					cmds.select( point )


			print( ' Created a locator between two vertices:  %s'%point )

			print '---------------------------------------------'
示例#51
0
    def fk_system(self):
        """
        building up the fk system

        Args:

        Returns:

        """
        # self.fk_chain = joints_utils.related_clean_joint_chain(self.main_chain, self.side, "fk", True)
        # self.fk_system_objs.append(self.fk_chain[0])

        if self.num_fk_ctrls == -1 or self.num_fk_ctrls == len(self.fk_chain):
            for i, jnt in enumerate(self.fk_chain):
                if i == 0:
                    ctrl = controller.Control("{}".format(jnt[:len(jnt) - 4]),
                                              3.0, 'circle', jnt, jnt, '',
                                              ['s', 'v'], '', True, True,
                                              False)
                    self.fk_controls.append(ctrl)
                    cmds.parentConstraint(self.fk_controls[i].get_control(),
                                          jnt,
                                          maintainOffset=True)
                elif i == len(self.fk_chain) - 1:
                    break
                else:
                    ctrl = controller.Control(
                        "{}".format(jnt[:len(jnt) - 4]), 3.0, 'circle', jnt,
                        jnt, self.fk_controls[i - 1].get_control(), ['s', 'v'],
                        '', True, True, False)
                    self.fk_controls.append(ctrl)
                    cmds.parentConstraint(self.fk_controls[i].get_control(),
                                          jnt,
                                          maintainOffset=True)
        else:
            print("WIP PART")
            '''
            joints_numb = len(self.fk_chain)
            ctrl_index_position = self.num_fk_ctrls / joints_numb
            for i, jnt in enumerate(slef.fk_chain):
                if i == 0:
                    ctrl = controller.Control("{}".format(jnt[:len(jnt)-4]), 3.0, 'circle', jnt, jnt, '', ['s', 'v'], '', True, True, False)
                    self.fk_controls.append(ctrl)
                    cmds.parentConstraint(self.fk_controls[i].get_control(), jnt, maintainOffset=True)
            '''

        # clean up the scene
        cmds.group(empty=True, name=self.fk_ctrls_main_grp)
        cmds.parent(self.fk_controls[0].get_offset_grp(),
                    self.fk_ctrls_main_grp)
        fk_system_grp = cmds.group(self.fk_system_objs,
                                   name="{}_{}_fkSystem_GRP".format(
                                       self.side, self.name))

        self.module_main_grp(fk_system_grp)

        # connect to root
        if self.root_space == "" or self.root_space == None:
            print "###--- No root space found. It'll skipped ---###"
        else:
            name_attr = "spaces"
            transforms_utils.make_spaces(
                self.fk_controls[0].get_control(),
                self.fk_controls[0].get_offset_grp(),
                name_attr, [self.world_space_loc[0], self.root_space],
                naming=["world", "root"])
            cmds.setAttr(
                "{}.{}".format(self.fk_controls[0].get_control(), name_attr),
                1)

        return True
mc.CreateWrap()
#mc.setAttr('wrap6.exclusiveBind', 1)

mc.select('ten_robe_model_main_ten_Hero_Sash', replace=True)  #Wrap Sash
mc.select('ten_robe_model_main_ten_Hero_Robe_Sleeveless', add=True)
mc.CreateWrap()
#mc.setAttr('wrap7.exclusiveBind', 0)

#Rename/Group Simulation Objects
mc.rename('nucleus1', 'nucleus_ten')  #Nucleus

mc.rename('nRigid1', 'nRigid_ten_body')  #nRigid
mc.rename('nRigid2', 'nRigid_ten_mitten_l')
mc.rename('nRigid3', 'nRigid_ten_mitten_r')
mc.group('nRigid_ten_body',
         'nRigid_ten_mitten_l',
         'nRigid_ten_mitten_r',
         name='ten_nRigid')

mc.rename('nCloth1', 'nCloth_ten_robe')  #nCloth
mc.rename('nCloth2', 'nCloth_ten_pants')
mc.group('nCloth_ten_robe', 'nCloth_ten_pants', name='ten_nCloth')

mc.rename('dynamicConstraint1',
          'dynamicConstraint_ten_robe_lapel')  #dynamicConstraint
mc.rename('dynamicConstraint2', 'dynamicConstraint_ten_robe_back')
mc.rename('dynamicConstraint3', 'dynamicConstraint_ten_robe_front')
mc.rename('dynamicConstraint4', 'dynamicConstraint_ten_pants')
mc.group('dynamicConstraint_ten_robe_lapel',
         'dynamicConstraint_ten_robe_back',
         'dynamicConstraint_ten_robe_front',
         'dynamicConstraint_ten_pants',
示例#53
0
def bakeBlendShapeNode(sourceObject, blendShapeNode, baseNameToUse = False, stripPrefix = False, ignoreInbetweens = False, ignoreTargets = False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for exporting an object's blendshapes

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    stripPrefix(bool) - whether to strip the first '_' segment
    ignoreInbetweens(bool)
    ignoreTargets(list) - targets to ignore in the processing

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    targetDict = returnBlendShapeTargetsAndWeights(sourceObject,blendShapeNode)
    targetSets = []
    blendShapeNodeChannels = []

    for key in targetDict.keys():
        targetSetBuffer = targetDict.get(key)
        targetSets.append(targetSetBuffer)

        baseSet = targetSetBuffer[-1]
        blendShapeNodeChannels.append(baseSet[0])

    blendShapeShortNames = []

    """ first loop gets connections, breaks them and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ get the connection """
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        print blendShapeConnections
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeBuffer,0)


    # Bake it
    bakedGeo = bakeBlendShapes(sourceObject, sourceObject, blendShapeNode, baseNameToUse, stripPrefix, ignoreInbetweens, ignoreTargets)


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """ group for geo """
    meshGroup = mc.group( em=True)
    if baseNameToUse != False:
        attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    return returnList
示例#54
0
 def __init__(
              self,
              prefix = 'new',
              scale = 1.0,
              translateTo = '',
              rotateTo = '',
              parent = '',
              shape = 'circle',
              lockChannels = ['s']
              ):
     
     """
     @param prefix: str, prefix to name new objects
     @param scale: float, scale value for size of control shapes
     @param translateTo: str, reference object for control position
     @param rotateTo: str, reference object for control orientation
     @param parent: str, object to be parent of new control
     @param shape: str, control shape type
     @param lockChannels: list( str ), list of channels on control to be locked and non-keyable
     @return: None
     """
     
     ctrlObject = None
     circleNormal = [1, 0, 0]
     
     if shape in ['circle', 'circleX']:
         
         circleNormal = [1, 0, 0]
     
     elif shape == 'circleY':
         
         circleNormal = [0, 1, 0]
     
     elif shape == 'circleZ':
         
         circleNormal = [0, 0, 1]
     
     elif shape == 'sphere':
         
         ctrlObject = mc.circle( n = prefix + '_ctl', ch = False, normal = [1, 0, 0], radius = scale )[0]
         addShape = mc.circle( n = prefix + '_ctl2', ch = False, normal = [0, 0, 1], radius = scale )[0]
         mc.parent( mc.listRelatives( addShape, s = 1 ), ctrlObject, r = 1, s = 1 )
         mc.delete( addShape )
     
     if not ctrlObject:
         
         ctrlObject = mc.circle( n = prefix + '_ctl', ch = False, normal = circleNormal, radius = scale )[0]
         
     ctrlOffset = mc.group( n = prefix + 'Offset_grp', em = 1 )
     mc.parent( ctrlObject, ctrlOffset )
     
     # color control
     ctrlShapes = mc.listRelatives( ctrlObject, s = 1 )
     [ mc.setAttr( s + '.ove', 1 ) for s in ctrlShapes ]
     
     if prefix.startswith( 'l_' ):
         
         [ mc.setAttr( s + '.ovc', 6 ) for s in ctrlShapes ]
     
     elif prefix.startswith( 'r_' ):
         
         [mc.setAttr( s + '.ovc', 13 ) for s in ctrlShapes ]
     
     else:
         
         [mc.setAttr( s + '.ovc', 22 ) for s in ctrlShapes ]
     
     # translate control
     
     if mc.objExists( translateTo ):
         
         mc.delete( mc.pointConstraint( translateTo, ctrlOffset ) )
     
     # rotate control
     
     if mc.objExists( rotateTo ):
         
         mc.delete( mc.orientConstraint( rotateTo, ctrlOffset ) )
     
     # parent control
     
     if mc.objExists( parent ):
         
         mc.parent( ctrlOffset, parent )
     
     # lock control channels
     
     singleAttributeLockList = []
     
     for lockChannel in lockChannels:
         
         if lockChannel in ['t','r','s']:
             
             for axis in ['x','y','z']:
                 
                 at = lockChannel + axis
                 singleAttributeLockList.append( at )
         
         else:
             
             singleAttributeLockList.append( lockChannel )
     
     for at in singleAttributeLockList:
         
         mc.setAttr( ctrlObject + '.' + at, l = 1, k = 0 )
     
     
     # add public members
     
     self.C = ctrlObject
     self.Off = ctrlOffset
示例#55
0
def bakeCombinedBlendShapeNodeToTargetObject(targetObject,sourceObject, blendShapeNode, baseName = False, directions=['left','right']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes from one object to another when you have a left/right variant

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    directions[list] = (['left','right'])

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(targetObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseName == False:
        baseName = ''
    else:
        baseName = baseName + '_'

    """reference check """
    refPrefix = search.returnReferencePrefix(sourceObject)
    if refPrefix != False:
        referencePrefix = (search.returnReferencePrefix(sourceObject) + ':')
    else:
        referencePrefix = ''

    """ wrap deform object """
    wrapBuffer = wrapDeformObject(targetObject,sourceObject,True)
    targetObjectBaked = wrapBuffer[1]

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    #setAttr ($wrapDeformer[0] + ".autoWeightThreshold") 1;
    """ cause maya is stupid and doesn't have a python equivalent"""
    mc.select(targetObjectBaked,r=True)
    mc.select(sourceObject,tgl=True)
    mel.eval('AddWrapInfluence')
    mc.select(cl=True)

    """
    may need to add this in later
    //reorders deformation order for proper baking of skinned mesh
    //reorderDeformers "tweak1" "face_skinCluster" $deformerGeo;
    """

    blendShapeNodeChannels = search.returnBlendShapeAttributes(blendShapeNode)
    blendShapeShortNames = []

    """ first loop stores and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeNode,shape,0)

    """ Find pairs """
    blendshapePairs = lists.returnMatchedStrippedEndList(blendShapeNodeChannels,directions)

    """ first loop stores and sets everything to 0 """
    for pair in blendshapePairs:
        blendShapeBuffer = (blendShapeNode+'.'+pair[0])
        splitBuffer = pair[0].split('_')
        nameBuffer = splitBuffer[:-1]
        pairBaseName = '_'.join(nameBuffer)

        if '_' in list(pairBaseName):
            newSplitBuffer = pair[0].split('_')
            newNameBuffer = newSplitBuffer[1:]
            blendShapeShortNames.append('_'.join(newNameBuffer))
        else:
            blendShapeShortNames.append(pairBaseName)

    t=1
    pair = 0
    for i in range (len(blendshapePairs)):
        row = i//5
        if t>5:
            t=1
        """ start extracting """
        blendShapeNodeChannelsBuffer = blendshapePairs[pair]
        shape1 = blendShapeNodeChannelsBuffer[0]
        shape2 = blendShapeNodeChannelsBuffer[1]
        attributes.doSetAttr(blendShapeNode,shape1,1)
        attributes.doSetAttr(blendShapeNode,shape2,1)
        dupBuffer = mc.duplicate(targetObjectBaked)
        splitBuffer = blendShapeShortNames[pair].split('_')
        nameBuffer = splitBuffer[:-1]
        shortName = '_'.join(nameBuffer)

        dupBuffer = mc.rename (dupBuffer,(baseName+shortName))
        mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
        bakedGeo.append(dupBuffer)

        attributes.doSetAttr(blendShapeNode,shape1,0)
        attributes.doSetAttr(blendShapeNode,shape2,0)
        pair +=1
        t+=1

    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """delete the wrap"""
    mc.delete(wrapBuffer[0])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    attributes.storeInfo(meshGroup,'cgmName', baseName)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    mc.delete(targetObjectBaked)
    return returnList
示例#56
0
    def etc_set(self):

        ### attribute

        # sup con vis

        for x in range(8):
            cmds.addAttr(TP.AA['PL'][x],
                         ln='sub_con_vis',
                         at='enum',
                         en='off:on:')
            cmds.setAttr(TP.AA['PL'][x] + '.sub_con_vis', e=1, keyable=1)
            cmds.connectAttr(TP.AA['PL'][x] + '.sub_con_vis',
                             TP.AA['CL'][x] + '.visibility')

        # FK / IK switch
        for x in range(2):
            switchCon = controllerShape(TP.conVis['key'][x][0] + '_CON',
                                        'cross', 'yellow')
            switchNul = cmds.group(switchCon,
                                   n=TP.conVis['key'][x][0] + '_NUL')

            cmds.delete(cmds.pointConstraint(TP.conVis['key'][x][1],
                                             switchNul))
            cmds.parent(switchNul, TP.conVis['key'][x][1])
            cmds.move(5, 0, 0, ws=1, r=1)

            cmds.addAttr(switchCon,
                         ln=TP.conVis['attr'][0],
                         at='enum',
                         en='off:on:')
            cmds.setAttr(switchCon + '.' + TP.conVis['attr'][0],
                         e=1,
                         keyable=1)

            cmds.addAttr(switchCon,
                         ln=TP.conVis['attr'][1],
                         at='enum',
                         en='off:on:')
            cmds.setAttr(switchCon + '.' + TP.conVis['attr'][1],
                         e=1,
                         keyable=1)

        for x in range(2):
            top_list = TP.conVis['vis'][x]
            for y in top_list:
                for z in y:
                    if len(y) == 1:
                        cmds.connectAttr(
                            TP.conVis['key'][x][0] + '_CON.' +
                            TP.conVis['attr'][0], z + '.visibility')
                    else:
                        cmds.connectAttr(
                            TP.conVis['key'][x][0] + '_CON.' +
                            TP.conVis['attr'][1], z + '.visibility')

                    cmds.setAttr(TP.conVis['key'][x][0] + '_CON.IK_con_vis', 1)

        ### Parent node

        cmds.group(p='noneTransform_GRP', em=1, n='locator_GRP')
        cmds.parent(TP.noneTrans_list, 'locator_GRP')
        cmds.parent(TP.attach_list, 'attach_GRP')
        cmds.parent(TP.auxillary_list, 'auxillary_GRP')
        cmds.parent(TP.neck_list, 'C_neck_GRP')
        cmds.parent(TP.spine_list, 'C_spine_GRP')
        cmds.parent(TP.L_foreLeg_list, 'L_foreLeg_GRP')
        cmds.parent(TP.R_foreLeg_list, 'R_foreLeg_GRP')
        cmds.parent(TP.L_hindLeg_list, 'L_hindLeg_GRP')
        cmds.parent(TP.R_hindLeg_list, 'R_hindLeg_GRP')
        cmds.parent(TP.tail_list, 'C_tail_GRP')

        cmds.delete(TP.delete_list)

        cmds.select(TP.noneTrans_list, 'templateJoint_GRP', TP.hide_list,
                    TP.hide_list2)
        cmds.HideSelectedObjects()

        ### Rotate controler

        self.controlerRotate(TP.rotate_con_list_A, 0, 0, -90)
        self.controlerRotate(TP.rotate_con_list_B, -90, 0, 0)

        ### controler Color

        for x in TP.R_con_list:
            conShapeName = cmds.listRelatives(x, s=1)[0]
            cmds.setAttr(conShapeName + '.overrideEnabled', 1)
            cmds.setAttr(conShapeName + '.overrideColor', 13)

        for x in TP.switch_con_list:
            conShapeName = cmds.listRelatives(x, s=1)[0]
            cmds.setAttr(conShapeName + '.overrideEnabled', 1)
            cmds.setAttr(conShapeName + '.overrideColor', 14)

        ### controler Scale

        for x in TP.scale_con_list:
            scale_value = 2
            CRV_shape_name = cmds.listRelatives(x, s=1)[0]
            CRV_span_num = cmds.getAttr(CRV_shape_name + '.spans')
            cmds.select(x + '.cv[0:%s]' % (CRV_span_num))
            cmds.scale(scale_value, scale_value, scale_value, r=1)

        ### controler Parent

        for x in range(2):
            PL = TP.parent_list['PL'][x]
            for y in TP.parent_list['CL'][x]:
                cmds.parentConstraint(PL, y, mo=1)

        ### hindLeg Parent

        cmds.setAttr('L_rig_hip_JNT.inheritsTransform', 0)
        cmds.setAttr('R_rig_hip_JNT.inheritsTransform', 0)

        itemList = ['.sx', '.sy', '.sz']

        for x in TP.targetjointList:
            for y in itemList:
                cmds.connectAttr('place_CON.globalScale', x + y)
示例#57
0
    cmds.polyUnite(muv=1, n='grass' + str(i))  #Combine and rename
    cmds.delete(ch=True)
    cmds.select('grass' + str(i))  #slect new shape

    ################################ Create FX ###########################
    cmds.lattice(dv=(7, 7, 7), oc=True)
    cmds.select("ffd" + str(x) + "Lattice")
    cmds.duplicate(n="ffd" + str(x) + "Lattice_goal")
    cmds.select("ffd" + str(x) + "Base")
    cmds.duplicate(n="ffd" + str(x) + "Base_goal")

    cmds.select("ffd" + str(x) + "Lattice")
    cmds.soft("ffd" + str(x) + "Lattice", c=True)
    cmds.goal("ffd" + str(x) + "LatticeParticle",
              g="ffd" + str(x) + "Lattice_goal",
              w=0.5)
    cmds.connectDynamic("ffd" + str(x) + "LatticeParticle", f='Grass_wind_FX')
    cmds.select('grass' + str(i), "ffd" + str(x) + "Lattice",
                "ffd" + str(x) + "Base", "ffd" + str(x) + "Lattice_goal",
                "ffd" + str(x) + "Base1", "ffd" + str(x) + "Base_goal")
    cmds.group(n='Dynamic_grass' + str(i))

    x += 2  #increment

l = 1
for i in range(109):
    cmds.select("ffd" + str(l) + "Lattice", "ffd" + str(l) + "Lattice_goal",
                "ffd" + str(l) + "Base1", "ffd" + str(l) + "Base_goal")
    cmds.hide(cs=True)
    l += 2
print "DONE!!!"
示例#58
0
def bakeCombinedBlendShapeNode(sourceObject, blendShapeNode, baseNameToUse = False, directions=['left','right']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes out from one object that have a split type

    ARGUMENTS:
    sourceObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    directions[list] = (['left','right'])

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(sourceObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    blendShapeNodeChannels = search.returnBlendShapeAttributes(blendShapeNode)
    blendShapeShortNames = []

    """ first loop stores and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeBuffer,0)

    """ Find pairs """
    blendshapePairs = lists.returnMatchedStrippedEndList(blendShapeNodeChannels,directions)

    """ first loop stores and sets everything to 0 """
    for pair in blendshapePairs:
        blendShapeBuffer = (blendShapeNode+'.'+pair[0])
        splitBuffer = pair[0].split('_')
        nameBuffer = splitBuffer[:-1]
        pairBaseName = '_'.join(nameBuffer)

        if '_' in list(pairBaseName):
            newSplitBuffer = pair[0].split('_')
            newNameBuffer = newSplitBuffer[1:]
            blendShapeShortNames.append('_'.join(newNameBuffer))
        else:
            blendShapeShortNames.append(pairBaseName)

    t=1
    pair = 0
    for i in range (len(blendshapePairs)):
        row = i//5
        if t>5:
            t=1
        """ start extracting """
        blendShapeNodeChannelsBuffer = blendshapePairs[pair]
        shape1 = blendShapeNodeChannelsBuffer[0]
        shape2 = blendShapeNodeChannelsBuffer[1]
        blendShape1Buffer = (blendShapeNode+'.'+shape1)
        blendShape2Buffer = (blendShapeNode+'.'+shape2)
        attributes.doSetAttr(blendShape1Buffer,1)
        attributes.doSetAttr(blendShape2Buffer,1)
        dupBuffer = mc.duplicate(sourceObject)


        splitBuffer = blendShapeShortNames[pair].split('_')
        if len(splitBuffer)>1:
            nameBuffer = splitBuffer[:-1]
        else:
            nameBuffer = splitBuffer
        shortName = '_'.join(nameBuffer)

        dupBuffer = mc.rename (dupBuffer,(baseName+shortName))
        """ Unlock it """
        attributes.doSetLockHideKeyableAttr(dupBuffer,False,True,True)

        mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
        bakedGeo.append(dupBuffer)

        attributes.doSetAttr(blendShape1Buffer,0)
        attributes.doSetAttr(blendShape2Buffer,0)
        pair +=1
        t+=1

    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    return returnList
示例#59
0
import maya.cmds as mc
from proportion import *
createLoc()
from body_joint import *
joint_creation()

#create FK controller and constraint
for i in ('Shoulder', 'Elbow', 'Wrist', 'Thigh', 'Knee', 'Ankle', 'Foot',
          'Toe'):
    mc.circle(n='FK_Left' + i + '_CON', c=(0, 0, 0), r=1)
    mc.group('FK_Left' + i + '_CON', name='FK_Left' + i + '_CON_grp')
    mc.delete(
        mc.parentConstraint(i + 'Left_JNT',
                            'FK_Left' + i + '_CON_grp',
                            mo=False))
    mc.setAttr('FK_Left' + i + '_CON.rotateY', 90)
    mc.makeIdentity('FK_Left' + i + '_CON', apply=True)
    mc.parentConstraint('FK_Left' + i + '_CON', i + 'Left_JNT')
mc.parent('FK_LeftWrist_CON_grp', 'FK_LeftElbow_CON')
mc.parent('FK_LeftElbow_CON_grp', 'FK_LeftShoulder_CON')
mc.parent('FK_LeftAnkle_CON_grp', 'FK_LeftKnee_CON')
mc.parent('FK_LeftKnee_CON_grp', 'FK_LeftThigh_CON')
mc.parent('FK_LeftFoot_CON_grp', 'FK_LeftKnee_CON')
mc.parent('FK_LeftToe_CON_grp', 'FK_LeftFoot_CON')

#finger FK contrller
for each in ('Pinkie', 'Ring', 'Middle', 'Index', 'Thumb'):
    if each == 'Thumb':
        joint_num = 3
    else:
        joint_num = 4
示例#60
0
def bakeBlendShapeNodeToTargetObject(targetObject,sourceObject, blendShapeNode, baseNameToUse = False, stripPrefix = False,ignoreInbetweens = False, ignoreTargets = False, transferConnections = True):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes from one object to another

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseNameToUse(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    stripPrefix(bool)
    ignoreInbetweens(bool)
    ignoreTargets(list) - list of targets to ignore
    transferConnections(bool) - if True, builds a new blendshape node and transfers the connections from our base objects

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(targetObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'

    """ wrap deform object """
    wrapBuffer = wrapDeformObject(targetObject,sourceObject,True)
    targetObjectBaked = wrapBuffer[1]

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    blendShapeNodeChannels = returnBlendShapeAttributes(blendShapeNode)

    blendShapeShortNames = []
    """ first loop stores and sets everything to 0 """

    for shape in blendShapeNodeChannels:
        keepGoing = True
        if ignoreTargets != False:
            if shape in ignoreTargets:
                keepGoing = False
            else:
                keepGoing = True

        blendShapeBuffer = (blendShapeNode + '.' + shape)
        """ get the connection """
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))

        if keepGoing == True:
            print ('breaking....' + blendShapeBuffer)
            """break it """
            attributes.doBreakConnection(blendShapeBuffer)
            attributes.doSetAttr(blendShapeNode,shape,0)

    # Bake it
    bakedGeo = bakeBlendShapes(sourceObject, targetObjectBaked, blendShapeNode, baseNameToUse, stripPrefix, ignoreInbetweens, ignoreTargets)


    """ restore connections """
    for shape in blendShapeNodeChannels:
        keepGoing = True
        if ignoreTargets != False:
            if shape in ignoreTargets:
                keepGoing = False
            else:
                keepGoing = True

        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if keepGoing == True:
            print ('connecting....' + blendShapeBuffer)
            print blendShapeConnections[currentIndex]
            if blendShapeConnections[currentIndex] != False:
                attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)


    # Need to build a new blendshape node?
    if transferConnections == True:
        # Build it
        newBlendShapeNode = buildBlendShapeNode(targetObject, bakedGeo, baseNameToUse)

        newBlendShapeChannels = returnBlendShapeAttributes(newBlendShapeNode)

        for shape in newBlendShapeChannels:
            blendShapeBuffer = (newBlendShapeNode+'.'+shape)
            currentIndex = newBlendShapeChannels.index(shape)
            if blendShapeConnections[currentIndex] != False:
                attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """delete the wrap"""
    mc.delete(wrapBuffer[0])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    if baseNameToUse != False:
        attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    mc.delete(targetObjectBaked)
    return returnList