Ejemplo n.º 1
0
    def aimRig(self,name):
    
        #query start location and orient
        startPosition = MeasuringTool.getPointLocation(self.objectStart)
        startOrient = MeasuringTool.getWorldEulerRotation(self.objectStart)
        
        
        #create locators
        aimLoc = cmds.spaceLocator(n = '%s_Aim_AimVector_Loc'%(name))
        upLoc = cmds.spaceLocator(n = '%s_Aim_UpVector_Loc'%(name))
        tgt = cmds.spaceLocator(n = '%s_Aim_Target_Loc'%(name))

        #create hierarchy
        posNull = cmds.group(aimLoc[0],upLoc[0],tgt[0],n = '%s_Aim_Pos_Null'%(name))

        cmds.move(startPosition[0],startPosition[1],startPosition[2],posNull)
        cmds.rotate(startOrient[0],startOrient[1],startOrient[2],posNull)
        
        #find vector length
        distance = self.getPointDistanceBetween()
        length = MeasuringTool.getVectorLength([distance[0],distance[1],distance[2]])
    
        #move and apply constraints to target
        cmds.move(length,0,0,tgt, a = True, os = True)
        cmds.move(0,0,10,upLoc[0],os = True)
        cmds.parentConstraint(self.objectStart,posNull)
        cmds.pointConstraint(self.objectEnd,tgt[0])
        cmds.aimConstraint(tgt,aimLoc, aimVector = (1,0,0), upVector = (0,0,1), worldUpType = "object", worldUpObject = upLoc[0])
Ejemplo n.º 2
0
	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 )
Ejemplo n.º 3
0
    def makeSpring(self,*args):
        
        
        self.springRadius=mc.getAttr("{0}.springRadius".format(self.radCntrl[0]))
        
        #get diameter (width)
        self.upWidth=self.springRadius*2
        
        #create base spring mesh using polyHelix
        self.springBase=mc.polyHelix(c=20,h=4,w=self.upWidth, r=0.2,sa=24,sco=24,
                                     sc=0,ax=(0,1,0),rcp=0,cuv=3,ch=1,
                                     name="springGeo")
        
        mc.pointConstraint(self.baseLoc,self.topLoc,self.springBase[0])
        mc.aimConstraint(self.topLoc,self.springBase[0],aimVector=(0,1,0))
        
        #connect height attribute of helix to distance node
        mc.connectAttr("{0}.distance".format(self.dNode),"{0}.height".format(self.springBase[1]),  force=True)
        
        mc.delete(self.radCntrl)
       
        mc.select(self.baseLoc,self.topLoc,self.conCurve,self.springBase)
        #select all spring parts        
        self.selection=mc.ls(sl=True)

        #loop through the parts and rename them accordingly    
        for x in self.selection:
            mc.rename(x,(x+"_#"))
    
        #create a group for the springs
        self.springGrp=mc.group(name="spring_GRP_#")
        #delete tmp group
        mc.delete(self.tmpGrp)
        #add GRP elements to set
        mc.sets(self.springGrp, add=self.springSetName)
Ejemplo n.º 4
0
 def setCST(self, constrainttype = 'parent', source = '', weight = 1, mo = True, remove = False, skip = "none"):
     """This can be used instead of the constraint class to constrain the current superObject to something quickly.
     @param type: the type of constraint,valid options are point, parent, aim, scale, orient.
     @param source: what you want to constrain to. single source only
     @param weight: the weight of the constraint
     @param mo: maintain offset
     @param remove: remove from constraint
     @type type: string
     @type target: string
     @type weight: int
     @type mo: boolean
     @type remove: boolean
     """
     self.cstName = self.name + constrainttype + '_Constraint'
     self.cstType = constrainttype
     self.source = source
     cstTypes = ['point', 'orient', 'aim', 'parent', 'scale']
     if self.cstType not in cstTypes:
         print 'Invalid constraint type called for superObject %s, try again' % self.name
     elif self.cstType == 'point':
         cmds.pointConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName, skip = skip)
     elif self.cstType == 'parent':
         cmds.parentConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
     elif self.cstType == 'aim':
         cmds.aimConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
     elif self.cstType == 'scale':
         cmds.scaleConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
     elif self.cstType == 'orient':
         cmds.orientConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
Ejemplo n.º 5
0
 def setSpring(self,*args):
     
     self.springName="spring"
 
     #create a set to put all of the spring elements inside
     self.springSetName="spring_SET"
     if mc.objExists(self.springSetName):
         print (self.springSetName + " exists.")
     else:
         mc.sets(name=self.springSetName)
     
     #create guides
     self.set_connector(self.springName)
         
     #create radius circle
     self.radCntrl=mc.circle(name="radius_CTRL",c=(0,0,0), nr=(0,1,0), 
                             sw=360, r=3, d=3, ut=0, tol=0.01, s=8, ch=1)
     #create springRadius attribute
     mc.addAttr(self.radCntrl, sn="sr", ln="springRadius", k=1, defaultValue=3.0, min=0.1, max=15)
     
     #connect the springRadius attribute to the circle
     mc.connectAttr("radius_CTRL.springRadius", "{0}.radius".format(self.radCntrl[1]))
     
     #position radCntrl between locators and aim
     
     mc.pointConstraint(self.baseLoc, self.topLoc,self.radCntrl[0])
     mc.aimConstraint(self.topLoc,self.radCntrl[0],aimVector=(0,1,0))
     
     self.lockHide(self.radCntrl[0])
     
     #create tmp group for easy deletion
     mc.select(self.baseLoc,self.topLoc,self.conCurve,self.radCntrl)
     self.selSpringObjs=mc.ls(sl=True,type="transform")
     
     self.createTmp(self.selSpringObjs)
Ejemplo n.º 6
0
 def nullMeasurementRig(self,name):
 
     #finds starting position and orientation
     startPos = MeasuringTool.getPointLocation(self.objectStart)
     startOrient = cmds.xform(self.objectStart,q = True, ws = True, rotation = True)
     
     #create parent group
     parentGroup = cmds.group(empty = True, name = '%s_Stretch_Group'%name)
      
     #create main null
     mainNull = cmds.group(empty = True, parent  = parentGroup,name = '%s_Main_Null'%name)
     
     #creates starting null
     startNull = cmds.group(empty = True,parent = parentGroup, name = '%s_Start_Null'%(name))
     
     #creates end null
     endNull = cmds.group(empty = True, parent = startNull, name = '%s_End_Null'%(name))
     
     cmds.move(startPos[0], startPos[1], startPos[2],parentGroup)
     cmds.rotate(startOrient[0],startOrient[1],startOrient[2],parentGroup)
     
     #finds end location
     pointDistance = self.getPointDistanceBetween()
     length = MeasuringTool.getVectorLength(pointDistance)   
     cmds.move(length,0,0,endNull, a = True, os = True)
     cmds.move(length,0,0,mainNull, a = True, os = True)
     
     #create constraints
     cmds.aimConstraint(mainNull,startNull,aim = (1,0,0))
     cmds.pointConstraint(mainNull,endNull)
     
     return [startNull,endNull,mainNull,parentGroup]
Ejemplo n.º 7
0
	def _createBaseJoints(self, verteces, baseName, skipTips = False, baseGrp = None ):
		"""create based joints with the verteces and name it all with baseName"""
		#Create UP vector Locator
		upVecLoc = mn.Node( mc.spaceLocator( n = baseName + '_UP_LOC' )[0] )
		upVecLoc.shape.a.localScale.v = [self.SCALE]*3
		upVecLoc.a.t.v = [ self.center[0], self.center[1] + 1, self.center[2] ]
		upVecLoc.parent = baseGrp
		#GROUPS
		grp = mn.Node( mc.group( n = baseName + '_JNT_GRP', em = True ) )
		locgrp = mn.Node( mc.group( n = baseName + '_LOC_GRP', em = True ) )
		locs = []
		if skipTips:
			verteces = verteces[1: len( verteces ) - 1 ]
		for i,v in enumerate( verteces ):
			grp()
			baseJnt = mn.Node( mc.joint( n = baseName + "%i"%i + '_JNT', p = self.center ) )
			jnt = mn.Node( mc.joint( n = baseName + "%i"%i + '_SKN', p = v ) )
			mc.joint( baseJnt.name, e=True, zso=True, oj='xyz' )
			#create locator for AIM
			loc = mn.Node( mc.spaceLocator( n = baseName + "%i"%i + '_LOC' )[0] )
			loc.a.t.v = v
			loc.shape.a.localScale.v = [self.SCALE/6.0]*3
			loc.parent = locgrp
			locs.append( loc )
			mc.aimConstraint( loc.name, baseJnt.name, weight = 1, mo = True, aimVector = [1,0,0], upVector = [0,1,0], worldUpType = "object", wuo = upVecLoc.name )
		grp.parent = baseGrp
		locgrp.parent = baseGrp
		return locs
def CreateHydraulicRig(upDir):

    selection = cmds.ls(sl=True)
    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.
    const = cmds.aimConstraint(robo_lowarm_pistonrod_01_anim_sub, robo_lowarm_pistonrod_02_anim_sub, weight=1, mo=False, aimVector=(-1, 0, 0), upVector=(0, 0, upDir), worldUpType="object", worldUpVector=(0, 0, -1), worldUpObject=upObject)
    const = cmds.aimConstraint(robo_lowarm_pistonrod_02_anim_sub, robo_lowarm_pistonrod_01_anim_sub, weight=1, mo=False, aimVector=(1, 0, 0), upVector=(0, 0, upDir), worldUpType="object", worldUpVector=(0, 0, -1), worldUpObject=upObject)
Ejemplo n.º 9
0
def bdRigEye(side):
	#create IK handles for the bind joints, for now getting the joints based on the name
	bindJoints = cmds.ls(side + "*Lid_jnt_*")
	eyeJoint = cmds.ls(side + "*eye*jnt")[0]
	eyeAnim = cmds.ls(side + '_eye_anim')
	cmds.aimConstraint(eyeAnim[0],eyeJoint,offset = [0, 0, 0] ,weight=1 , aimVector =[1 ,0 ,0] ,upVector=[0, 1, 0] ,worldUpType="vector" ,worldUpVector= [0,1,0])

	blinkUpJnt = cmds.duplicate(eyeJoint,name = side + '_eye_upLid_blink_jnt',po=True)
	blinkLowJnt = cmds.duplicate(eyeJoint,name = side + '_eye_lowLid_blink_jnt',po=True)
	baseLidsJnt = cmds.ls(side + '*lids*base')
	cmds.parent([blinkUpJnt[0],blinkLowJnt[0]],baseLidsJnt[0])
	for joint in bindJoints:
		print joint
		endJoint = cmds.listRelatives(joint,c=True,type='joint')
		ikName = endJoint[0].replace('bnd_jnt','ikHandle')
		ctrlName = endJoint[0].replace('bnd_jnt','anim')

		bdRigUtils.bdAddIk(joint,endJoint[0],'ikSCsolver',ikName)
		bdRigUtils.bdBuildBoxController(endJoint[0],ctrlName,0.2)
		bdRigUtils.bdAddAttributeMinMax(ctrlName,['BlinkPosition'],'double',-5,5,1)
		cmds.parent(ikName,ctrlName)
		bdBuildJointStructure(joint,ctrlName,ikName)

	allAnimsGrps = cmds.ls(side + '*eye*CON_??',type='transform')
	globalAnimGrp = cmds.ls('controllers') 
	cmds.parent(allAnimsGrps,globalAnimGrp[0])

	bdAddEyeAttr(eyeAnim[0])
	bdCreateVerticalFollow(side)
	bdCreateSideFollow(side)
	bdCreateBlink(side)
Ejemplo n.º 10
0
    def RMCreateTwist(self, TwistJoint, LookAtObject,  NumberOfTB = 3, LookAtAxis = "Y"):
        #LookAtObject = cmds.listRelatives( TwistJoint,type = "transform",children=True)[]
    
        positionA = cmds.xform(TwistJoint ,q=True,ws=True,rp=True)
        positionB = cmds.xform(LookAtObject ,q=True,ws=True,rp=True)

        vectorA = om.MVector(positionA)
        vectorB = om.MVector(positionB)

        self.RMCreateBonesBetweenPoints(vectorA,vectorB,NumberOfTB, AlignObject = TwistJoint)

        Distance = RMRigTools.RMPointDistance( TwistJoint, LookAtObject)
        
        cmds.parentConstraint (TwistJoint,self.TwistResetJoints)

        resetPoint , control = RMRigShapeControls.RMCreateBoxCtrl(self.TwistJoints[0], Xratio = .1, Yratio = .1, Zratio = .1, customSize = Distance/5 ,name = "TwistOrigin" + self.NameConv.RMGetAShortName (TwistJoint).title())
        #control = self.NameConv.RMRenameBasedOnBaseName(TwistJoint , control,  NewName = self.NameConv.RMGetAShortName(control))
        #resetPoint = self.NameConv.RMRenameBasedOnBaseName(TwistJoint , resetPoint,  NewName = self.NameConv.RMGetAShortName(resetPoint))
        
        sign = 1
        MoveDistance = Distance/5
        if "-" in LookAtAxis:
            sign = -1
        if "Z" in LookAtAxis or "z" in LookAtAxis:
            MoveList = [0,0, MoveDistance * sign]
            WUV = [0,0,sign]
        elif "Y" in LookAtAxis or "y" in LookAtAxis:
            MoveList = [0,MoveDistance * sign,0 ]
            WUV = [0,sign,0]

        cmds.xform( resetPoint, os = True, relative=True,  t = MoveList)

        cmds.aimConstraint( LookAtObject,self.TwistJoints[0], aim = [1,0,0], worldUpVector = [0,0,1], worldUpType = "object", worldUpObject = control)

        TwistJointDivide = cmds.shadingNode( "multiplyDivide", asUtility = True, name = "TwistJoint" + self.NameConv.RMGetAShortName( TwistJoint).title())
        TwistJointDivide = self.NameConv.RMRenameBasedOnBaseName( TwistJoint , TwistJointDivide,  NewName = self.NameConv.RMGetAShortName( TwistJointDivide))


        TwistAddition = cmds.shadingNode( "plusMinusAverage", asUtility = True, name = "TwistJointAdd" + self.NameConv.RMGetAShortName( TwistJoint).title())
        TwistAddition = self.NameConv.RMRenameBasedOnBaseName( TwistJoint , TwistAddition,  NewName = self.NameConv.RMGetAShortName( TwistAddition))
        NegativeLookAtRotation = cmds.shadingNode( "multiplyDivide", asUtility = True, name = "NegativeLookAtRotation" + self.NameConv.RMGetAShortName( TwistJoint).title())
        NegativeLookAtRotation = self.NameConv.RMRenameBasedOnBaseName( TwistJoint , NegativeLookAtRotation,  NewName = self.NameConv.RMGetAShortName( NegativeLookAtRotation))
        cmds.connectAttr( LookAtObject + ".rotateX", NegativeLookAtRotation + ".input1X")
        cmds.setAttr(NegativeLookAtRotation + ".input2X", -1 )
        cmds.setAttr(NegativeLookAtRotation + ".operation", 1 )
        cmds.connectAttr(self.TwistJoints[0]+".rotateX", TwistAddition + ".input1D[0]")
        cmds.connectAttr( NegativeLookAtRotation + ".outputX", TwistAddition + ".input1D[1]")
        cmds.connectAttr(TwistAddition + ".output1D", TwistJointDivide + ".input1X")


        #cmds.connectAttr(self.TwistJoints[0]+".rotateX", TwistJointDivide + ".input1X") in this case the rotation of the lookatNode was not affecting
        cmds.setAttr(TwistJointDivide + ".input2X", -(len(self.TwistJoints) - 1))
        cmds.setAttr(TwistJointDivide + ".operation", 2 )

        for eachJoint in self.TwistJoints[1:]:
            cmds.connectAttr(TwistJointDivide+".outputX", eachJoint + ".rotateX")


        self.TwistControlResetPoint = resetPoint
        self.TwistControl = control
Ejemplo n.º 11
0
def _setupLights( domeRig, isSpot, lights, numLights, lightConstraint, lightLocator ):
    lightAttr = ( 'color', 'emitSpecular', 'coneAngle', 'penumbraAngle',
                  'dropoff', 'shadowColor', 'dmapResolution', 'dmapFilterSize',
                  'dmapBias', 'lightRadius', 'shadowRays', 'useDepthMapShadows',
                  'useRayTraceShadows' )

    # Create intensity MD to divide each light's intensity to sum the user's intensity
    intMD = cmds.shadingNode( 'multiplyDivide', asUtility=True, name=(domeRig + '_mdIntensity') )
    cmds.setAttr( (intMD + ".operation"), 2 )
    cmds.setAttr( (intMD + ".input2X"), numLights )
    cmds.connectAttr( (domeRig + '.intensity'), (intMD + '.input1X') )

    # Set up for individual lights in the rig
    for l in lights:
        # Connect intensity MD to each light's intensity
        cmds.connectAttr( (intMD + '.outputX'), (l + '.intensity') )

        # Constrain all lights to sphere
        lp = cmds.listRelatives(l, parent=True)
        cmds.geometryConstraint( lightConstraint, lp )

        # Set all lights to point at locator
        cmds.aimConstraint( lightLocator, lp[0], offset=[0,-90,0] )

        # Connect group's extra attributes to each light's attributes
        for attr in lightAttr:
            if isSpot or ( not isSpot and attr not in ['coneAngle', 'penumbraAngle', 'dropoff']):
                cmds.connectAttr( (domeRig + '.' + attr), (l + '.' + attr) )

    # Connect sphere and light rig keyable attributes
    attrs = cmds.listAttr(lightConstraint[0], keyable=True)
    for attr in attrs:
        cmds.setAttr( (lightConstraint[0] + '.' + attr), keyable=False, lock=True )
def joint(side, lowerJoint, upperJoint, useSphere=0, sharedUpper=0, sharedLower=0, show=1, heightScale=1):
    name = lowerJoint + "_" + upperJoint

    upperName = "SKEL_"
    if sharedUpper == 0:
        upperName += side + "_"
    upperName += upperJoint

    lowerName = "SKEL_"
    if sharedLower == 0:
        lowerName += side + "_"
    lowerName += lowerJoint

    print name
    cmds.spaceLocator(name="%s_%s" % (side, name))
    cmds.pointConstraint(lowerName, "%s_%s" % (side, name))
    cmds.pointConstraint(upperName, "%s_%s" % (side, name))
    cmds.aimConstraint(upperName, "%s_%s" % (side, name))
    if useSphere:
        cmds.sphere(name="%s_%s_C" % (side, name), radius=1)
    else:
        cmds.cylinder(name="%s_%s_C" % (side, name), radius=0.5, heightRatio=6 * heightScale)

    cmds.setAttr("%s_%s_C.doubleSided" % (side, name), 0)
    if show == 0:
        cmds.setAttr("%s_%s_C.primaryVisibility" % (side, name), 0)

        # cmds.rotate( 0, 0, 90, '%s_FOREARM_C' % (side) )
        # cmds.makeIdentity( '%s_FOREARM_C' % (side), apply = 1, rotate = 1 )
    cmds.select("%s_%s" % (side, name), "%s_%s_C" % (side, name))
    cmds.parentConstraint()
    return
Ejemplo n.º 13
0
 def build(self):
     
     shoulder = '%sShoulder%s' % (self.namespace,self.count)
     elbow    = '%sElbow%s' % (self.namespace,self.count)
     wrist    = '%sWrist%s' % (self.namespace,self.count)
     
     # orient arm joints
     cmds.parent(elbow,w=True)
     cmds.delete(cmds.aimConstraint(elbow,shoulder,mo=False,aim=[1,0,0],u=[0,0,1],wut='object',wuo='comp_%s%s:armUp' % (self.namespace,self.count))[0])
     cmds.parent(elbow,shoulder)
     
     cmds.parent(wrist,w=True)
     cmds.delete(cmds.aimConstraint(wrist,elbow,mo=False,aim=[1,0,0],u=[0,0,1],wut='object',wuo='comp_%s%s:armUp' % (self.namespace,self.count))[0])
     cmds.parent(wrist,elbow)
     
     children = cmds.listRelatives(wrist,c=True,s=False)
     cmds.parent(children,w=True)
     cmds.makeIdentity(wrist,a=True,t=False,r=True,s=False,n=False,jo=True)    
     cmds.parent(children,wrist)
     
     # orient fingers
     for finger in ['thumb','index','middle','pinky']:
         descendents = cmds.listRelatives('%s%sA%s' % (self.namespace,finger.title(),self.count),ad=True)
         for child in descendents:
             parent = cmds.listRelatives(child,p=True)[0]
             cmds.parent(child,w=True)
             cmds.delete(cmds.aimConstraint(child,parent,mo=False,aim=[1,0,0],u=[0,1,0],wut='objectrotation',wuo='comp_%s%s:R_%sOrient_ctl_0' % (self.namespace,self.count,finger))[0])
             cmds.parent(child,parent)
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)
Ejemplo n.º 15
0
 def execute(self):
     data = self.component_data()
     for constraint in data['constraints']:
         drivers = constraint['drivers']
         del constraint['drivers']
         driven = constraint['driven']
         del constraint['driven']
         cmds.aimConstraint(drivers, driven, **constraint)
Ejemplo n.º 16
0
 def surfCts(name, vertSets):
     '''
     jntsIks[0] = lists of 3 joint sets
     jntsIks[1] = list of ik handles, one for each three joint set
     '''
     #controllers, constraints
     geoParent = []
     j = 0
     for vSet in vertSets:
         i = 0
         setName = ["", "_aim", "_up"]
         rootCtGp = None
         aimCt = None
         upCt = None
         for point in vSet:
             if i < 3:
                 # controller
                 diamond = place.Controller(name + '_' + str(('%0' + str(2) + 'd') % (j)) + setName[i], point, False, 'diamond_ctrl', 5, 12, 8, 1, (0, 0, 1), True, True)
                 DiamondCt = diamond.createController()
                 place.cleanUp(DiamondCt[0], Ctrl=True)
                 cnst = cmds.pointOnPolyConstraint(point, DiamondCt[0])[0]
                 # convert vertex to uv
                 uv = cmds.polyListComponentConversion(point, fv=True, tuv=True)
                 # get uv space
                 space = cmds.polyEditUV(uv, q=True)
                 # set uv attrs on constraint
                 cmds.setAttr(cnst + '.' + point.rsplit('.')[0] + 'U0', space[0])
                 cmds.setAttr(cnst + '.' + point.rsplit('.')[0] + 'V0', space[1])
                 # append geoParent
                 if i == 0:
                     geoParent.append(DiamondCt[4])
                     rootCtGp = DiamondCt[1]
                 elif i == 1:
                     aimCt = DiamondCt[4]
                     cmds.setAttr(DiamondCt[0] + '.visibility', False)
                 elif i == 2:
                     upCt = DiamondCt[4]
                     cmds.setAttr(DiamondCt[0] + '.visibility', False)
                 # constraint
                 '''
                 if i==1:
                     ##ik
                     cmds.pointConstraint(DiamondCt[4], jntsIks[1][j])
                 else:
                     ##joint
                     cmds.pointConstraint(DiamondCt[4], jntsIks[0][j][i])
                     '''
             else:
                 # constrain joint to first controller of vert set list
                 cmds.parentConstraint(geoParent[j], point, mo=True)
             i = i + 1
         # aim constraint
         cmds.aimConstraint(aimCt, rootCtGp, mo=True,
                            aimVector=(0, 0, 1), upVector=(0, 1, 0),
                            worldUpType='object', worldUpObject=upCt)
         j = j + 1
     return geoParent
Ejemplo n.º 17
0
 def orient(self):
     constraint = cmds.aimConstraint(self.botHandle, self.topHandle,
                                     aimVector=[0, -1, 0],
                                     upVector=[1, 0, 0])
     cmds.delete(constraint)
     constraint = cmds.aimConstraint(self.topHandle, self.botHandle,
                                     aimVector=[0, 1, 0],
                                     upVector=[1, 0, 0])
     cmds.delete(constraint)
Ejemplo n.º 18
0
def psd_driver_display(psd_driver, mode=1):

    if psd_driver.find("_psd_driver_gr") == -1: # not found
        cmds.warning('PSD Driver is not selected, aborting...')
        return
    
    prefix = psd_driver.replace('_psd_driver_gr', '')    
    goal_pos = prefix + '_goal_pos'
    target_pos = prefix + '_goal_pos'
    
    display_object = prefix + "psd_driver_display"
    angle_mult = prefix + "_angle_mult"
    annotation = prefix + '_annotation'
    num_to_str = prefix + "_num_to_str"
    
    if mode == 0 : #delete
        try:
            cmds.delete(display_object, angle_mult)
        except:
            pass
        
        return

    if mode == 1 : #create
        
        if not cmds.objExists(display_object):
            cmds.spotLight(intensity=0, name = display_object)

            display_object_shape = cmds.listRelatives(display_object)[0]
            cmds.setAttr(display_object_shape + '.overrideEnabled', 1)
            cmds.setAttr(display_object_shape + '.overrideDisplayType', 2)        
    
            cmds.parent(display_object, psd_driver, relative=True)
            cmds.aimConstraint(goal_pos, display_object, aimVector=[0,0,-1])
            
            angle_mult = cmds.createNode('multDoubleLinear', name = angle_mult)
            cmds.connectAttr(psd_driver + ".startAngle", angle_mult + ".input1")
            cmds.setAttr(angle_mult + ".input2", 2)
            cmds.connectAttr(angle_mult + ".output", display_object + ".coneAngle")
            
            annotation_shape = cmds.annotate(display_object, text='temp', p=[0,0,0])
            print annotation_shape
            cmds.setAttr(annotation_shape + '.displayArrow', 0)
            annotationNode = cmds.listRelatives(annotation_shape, p=True)[0]
            cmds.parent(annotationNode, display_object, r=True)
            cmds.setAttr(annotationNode + ".translateZ", -1.0)
            
            cmds.createNode('numToStr', name=num_to_str)
            cmds.connectAttr(psd_driver + ".psdBlend", num_to_str + ".input")
            cmds.connectAttr(num_to_str + ".output", annotation_shape + ".text")
            
            #cmds.rename (annotationNode, annotation)
            
            
        return display_object
Ejemplo n.º 19
0
    def make_constraint(self, src, dst, constraint_type='aim', skip_translate='none', skip_rotate='none', maintain_offset=False, weight=1, aim_vec=[0,1,0], up_vec=[0,0,1], world_up_type='vector', world_up_vec=[0,0,1], world_up_object=None, keep_constraint_node = True, name = None):
        '''
        Desc:
        Make any contraint

        Parameter:
        src = source object object contraint from
        dst = destination object constraint to:
        constraintType = constraint type
        offset = mantaintOffset bool val

        Return:
        contraint str name
        '''
        # var for constraint name
        constraint = []
        type=''

        # Fix name
        name = str(name).replace("u'",'').replace('[',' ').replace(']',' ').replace("'",' ').replace(' ', '')

        # Parent constraint
        if constraint_type == 'parent':
            type='PAC'
            constraint = cmds.parentConstraint(src, dst, mo=maintain_offset, w=weight, st=skip_translate, name=name+'_'+type)

        # Point constraint
        elif constraint_type == 'point':
            type='PC'
            constraint = cmds.pointConstraint(src, dst, mo=maintain_offset, w=weight, sk=skip_translate, name=name+'_'+type)

        # Orient constraint
        elif constraint_type == 'orient':
            type='OC'
            constraint = cmds.orientConstraint(src, dst, mo=maintain_offset, w=weight, sk=skip_rotate, name=name+'_'+type)

        # Aim constraint, ToDo, optimize
        elif constraint_type == 'aim':
            type='AC'
            if world_up_type == 'object':
                if world_up_object == None:
                    KstOut.debug(KstMaya._debug, "Check object up variable, can't be set to None")
                else:
                    constraint = cmds.aimConstraint(src, dst, mo=maintain_offset, w=weight, sk=skip_rotate, aimVector=aim_vec, upVector=up_vec, worldUpType=world_up_type, worldUpVector=world_up_vec, worldUpObject=world_up_object, name=name+'_'+type)
            else:
                constraint = cmds.aimConstraint(src, dst, mo=maintain_offset, w=weight, sk=skip_rotate, aimVector=aim_vec, upVector=up_vec, worldUpType=world_up_type, worldUpVector=world_up_vec, name=name+'_'+type)

        #constraint = cmds.rename(constraint[0], '%s_%s' % (constraint[0], type))

        # Delete constraint node if needed
        if keep_constraint_node == False:
            cmds.delete(constraint)

        return constraint
Ejemplo n.º 20
0
 def aimTo(self, aimTo, mo = 0, upVector = (0.0,1.0,0.0), aimVector = (0.0,0.0,1.0)):
     """Aim superObject to object.
     @param aimTo: name of the transform you wish to aim to
     @param upVector: upVector
     @param aimVector: aimVector
     @type upVector: tuple float values
     @type aimVector: tuple float values
     """
     cmds.aimConstraint(aimTo, self.name, name = 'tmpAim', aim = aimVector, u = upVector, mo = mo)
     cmds.delete('tmpAim')
     return
Ejemplo n.º 21
0
def point_to_target():
    make_origin_target()
    
    cmds.select(cmds.listRelatives(cmds.ls(geometry=True), p=True, path=True), r=True)
    shapeList = cmds.ls(sl=True)
    shapeList.remove('pSphere1')
    
    for x in shapeList:
        print (x)
        cmds.select(x)
        cmds.xform(cp=True)
        cmds.aimConstraint('pSphere1',str(x))
Ejemplo n.º 22
0
 def setJoints(self,rootPos, endPos, ringPos,rConstLoc,bConstLoc,radius,jntName,pGroup):
     
     thickness = radius/3
     
     
     #clear selection
     mc.select(clear=True)
     #create joints
     joints=[]
     
     joints.append(mc.joint(position=rootPos,name=(jntName+"_root_JNT_#")))
     joints.append(mc.joint(position=ringPos,name=(jntName+"_end_JNT_#")))
    
     
     mc.joint(joints,edit=True,orientJoint="xyz",zeroScaleOrient=True,
              secondaryAxisOrient="yup")
     
     #create IKhandle
     self.pistonIK=mc.ikHandle(sj=joints[0], ee=joints[1], 
                               name=(jntName+"_IK_#"))
     
     #parent to locators
     mc.parent(joints[0],rConstLoc)
     
     #constrain to locators
     mc.pointConstraint(bConstLoc,self.pistonIK[0])
     
     
     #distance between 
     distance = sqrt( pow((rootPos[0]-ringPos[0]),2) + 
                      pow((rootPos[1]-ringPos[1]),2) + 
                      pow((rootPos[2]-ringPos[2]),2))
     
            
     #create pipe rod (polyPipe bug...must double the height)
     self.rod=mc.polyPipe(r=radius,t=thickness,h=(distance*2),
                          sa=20,ax=(0,1,0),cuv=3,ch=1,sc=0,
                          name=(jntName+"_geo_#"))
     #move pivot point to origin
     
     mc.xform(pivots=(0,(distance/-2),0))
     #aim and parent to joints
     mc.pointConstraint(joints[0],self.rod[0])
     mc.aimConstraint(joints[1],self.rod[0],aimVector=(0,1,0))
     
     #clear the list
     del joints[:]
     
     mc.select(self.pistonIK[0],self.rod[0])
     mc.ls(sl=True)[0]
     toGroup=mc.group(n=jntName+"_GRP_#")
     mc.parent(toGroup, pGroup)
Ejemplo n.º 23
0
 def execute(self):
     for container in self.constraints:
         drivers = container['drivers'].value()
         driven = container['driven'].value()
         skip = [x for x in 'xyz' if container['skip_{0}'.format(x)].value()]
         cmds.aimConstraint(drivers, driven,
                            maintainOffset=container['maintain_offset'].value(),
                            aimVector=container['aim_vector'].value(),
                            upVector=container['up_vector'].value(),
                            worldUpType=container['world_up_type'].value(),
                            worldUpVector=container['world_up_vector'].value(),
                            worldUpObject=container['world_up_object'].value(),
                            skip=skip)
Ejemplo n.º 24
0
def create_aimJointChain(aimLocators, centerLocator, upLocator):
    """
    create joint chain (start at rotation pivot, end at CV location)
    for every aimLocator, aim constraint joint chain to aimLocator
    """
    for aimLocator in aimLocators:
        cmds.select(clear=True)
        
        startJoint = cmds.joint(p = [0,0,0])
        endJoint = cmds.joint(p = [1,0,0])
        
        cmds.delete(cmds.pointConstraint(centerLocator, startJoint, mo=False))
        cmds.aimConstraint(aimLocator, startJoint, mo=False, aimVector = [1,0,0], upVector=[0,1,0], worldUpType='object', worldUpObject=upLocator)
        cmds.delete(cmds.pointConstraint(aimLocator, endJoint, mo=False))
Ejemplo n.º 25
0
def createSimpleRibbon(name='noodle', totalJoints=6):
    """ Creates a Ribbon system.
        Receives the total number of joints to create.
        Returns the ribbon nurbs plane, the joints groups and joints created.
    """
    # create a ribbonNurbsPlane:
    ribbonNurbsPlane = cmds.nurbsPlane(name=name+"RibbonNurbsPlane", constructionHistory=False, object=True, polygon=0, axis=(0, 1, 0), width=1, lengthRatio=8, patchesV=totalJoints)[0]
    # get the ribbonNurbsPlane shape:
    ribbonNurbsPlaneShape = cmds.listRelatives(ribbonNurbsPlane, shapes=True, children=True)[0]
    # make this ribbonNurbsPlane as template, invisible and not renderable:
    cmds.setAttr(ribbonNurbsPlane+".template", 1)
    cmds.setAttr(ribbonNurbsPlane+".visibility", 0)
    setNotRenderable([ribbonNurbsPlaneShape])
    # make this ribbonNurbsPlane as not skinable from dpAR_UI:
    cmds.addAttr(ribbonNurbsPlane, longName="doNotSkinIt", attributeType="bool", keyable=True)
    cmds.setAttr(ribbonNurbsPlane+".doNotSkinIt", 1)
    # create groups to be used as a root of the ribbon system:
    ribbonGrp = cmds.group(ribbonNurbsPlane, n=name+"_RibbonJoint_Grp")
    # create joints:
    jointList, jointGrpList = [], []
    for j in range(totalJoints+1):
        # create pointOnSurfaceInfo:
        infoNode = cmds.createNode('pointOnSurfaceInfo', name=name+"_POSI"+str(j))
        # setting parameters worldSpace, U and V:
        cmds.connectAttr(ribbonNurbsPlaneShape + ".worldSpace[0]", infoNode + ".inputSurface")
        cmds.setAttr(infoNode + ".parameterV", ((1/float(totalJoints))*j) )
        cmds.setAttr(infoNode + ".parameterU", 0.5)
        # create and parent groups to calculate:
        posGrp = cmds.group(n=name+"Pos"+str(j)+"_Grp", empty=True)
        upGrp  = cmds.group(n=name+"Up"+str(j)+"_Grp", empty=True)
        aimGrp = cmds.group(n=name+"Aim"+str(j)+"_Grp", empty=True)
        cmds.parent(upGrp, aimGrp, posGrp, relative=True)
        # connect groups translations:
        cmds.connectAttr(infoNode + ".position", posGrp + ".translate", force=True)
        cmds.connectAttr(infoNode + ".tangentU", upGrp + ".translate", force=True)
        cmds.connectAttr(infoNode + ".tangentV", aimGrp + ".translate", force=True)
        # create joint:
        cmds.select(clear=True)
        joint = cmds.joint(name=name+str(j)+"_Jnt")
        jointList.append(joint)
        cmds.addAttr(joint, longName='dpAR_joint', attributeType='float', keyable=False)
        # parent the joint to the groups:
        cmds.parent(joint, posGrp, relative=True)
        jointGrp = cmds.group(joint, name=name+"Joint"+str(j)+"_Grp")
        jointGrpList.append(jointGrp)
        # create aimConstraint from aimGrp to jointGrp:
        cmds.aimConstraint(aimGrp, jointGrp, offset=(0, 0, 0), weight=1, aimVector=(0, 1, 0), upVector=(0, 0, 1), worldUpType="object", worldUpObject=upGrp, n=name+"Ribbon"+str(j)+"_AimConstraint" )
        # parent this ribbonPos to the ribbonGrp:
        cmds.parent(posGrp, ribbonGrp, absolute=True)
    return [ribbonNurbsPlane, ribbonNurbsPlaneShape, jointGrpList, jointList]
Ejemplo n.º 26
0
def aimConstraintToLocator():
	"""
	creates a locator in joint's position and aim constraints the parent to this locator.
	these locators serve as controler for each joint of eye lid.
	works with multiple selection. 
	"""
	for s in sel:
		loc = cmds.spaceLocator()[0]
		pos = cmds.xform(s, q=1, ws=1, t=1)
		cmds.xform(loc, ws=1, t=pos)
		par = cmds.listRelatives(s, p=1)[0]
		cmds.aimConstraint(loc, par, mo=1, weight=1
							, aimVector=(1,0,0)	, upVector = (0,1,0)
							, worldUpType="object", worldUpObject = upv )
Ejemplo n.º 27
0
def setLocators(plane):
    cmds.select(plane)
    fn = cmds.polyInfo(fn=True)
    #get face normal direction
    fn_x = float(fn[0].split(" ")[7])
    fn_y = float(fn[0].split(" ")[8])
    fn_z = float(fn[0].split(" ")[9])

    #get face center position
    p0 = getVertexPosition(plane, 0)
    p1 = getVertexPosition(plane, 1)
    p2 = getVertexPosition(plane, 2)
    
    px = (p0[0]+p1[0]+p2[0])/3
    py = (p0[1]+p1[1]+p2[1])/3
    pz = (p0[2]+p1[2]+p2[2])/3
    
    p = [px,py,pz] 
    #p = np.average(np.array((p0,p1,p2)), axis = 0)

    #calc locator position
    lo_x = fn_x + p[0]
    lo_y = fn_y + p[1]
    lo_z = fn_z + p[2]

    #create normal aim locator
    cmds.spaceLocator(n = 'locator_normal_aim_' + plane)
    cmds.move(lo_x, lo_y, lo_z, 'locator_normal_aim_' + plane)
    cmds.scale(0.1,0.1,0.1,'locator_normal_aim_' + plane)

    #create locator center
    cmds.spaceLocator(n = 'locator_center_' + plane)
    cmds.move(p[0], p[1], p[2], 'locator_center_' + plane)
    cmds.scale(0.1,0.1,0.1,'locator_center_' + plane)

    #create world up object 
    #(todo : get front edge center)
    cmds.spaceLocator(n = 'locator_for_z_' + plane)
    vert = cmds.select(plane +'.vtx[0]')
    p = cmds.xform(vert, q=True, ws=True, t=True)
    cmds.move(p[0],p[1],p[2], 'locator_for_z_' + plane)
    cmds.scale(0.1,0.1,0.1,'locator_for_z_' + plane)

    #set aim constraint
    cmds.aimConstraint('locator_normal_aim_' + plane, 'locator_center_' + plane,
                       wut='object', wuo='locator_for_z_' + plane, 
                       n = 'aim_node_' + plane)

    cmds.parent(plane, 'aim_node_' + plane)
Ejemplo n.º 28
0
def triangulatePivot(posVerts, upvectorVert, locatorPivot=True, meshPivot=True):

    cmds.undoInfo(openChunk=True)

    posA = cmds.xform(posVerts[0], q=True, ws=True, translation=True)
    posB = cmds.xform(posVerts[1], q=True, ws=True, translation=True)
    posC = cmds.xform(upvectorVert, q=True, ws=True, translation=True)

    pivotPos = MidPosition(posA, posB)

    crs = mru.CrossProduct(posA, posB, posC)

    grp = cmds.group(empty=True)
    cmds.xform(grp, worldSpace=True, translation=posA)

    if locatorPivot:

        loc = cmds.spaceLocator()

        cmds.xform(loc, ws=True, translation=pivotPos)
        cmds.aimConstraint(grp, loc, worldUpType="vector", worldUpVector=crs)

    if meshPivot:

        posGrp = cmds.group(empty=True)

        cmds.xform(posGrp, ws=True, translation=pivotPos)
        cmds.aimConstraint(grp, posGrp, worldUpType="vector", worldUpVector=crs)

        pivotTranslate = cmds.xform(posGrp, q=True, ws=True, rotatePivot=True)

        shape = cmds.listRelatives(upvectorVert, parent=True)
        transform = cmds.listRelatives(shape, parent=True)
        parent = cmds.listRelatives(transform, parent=True)

        cmds.parent(transform, posGrp)
        cmds.makeIdentity(transform, a=True, t=True, r=True, s=True)
        cmds.xform(transform, ws=True, pivots=pivotTranslate)

        if parent != None:
            cmds.parent(transform, parent)
        else:
            cmds.parent(transform, w=True)

        cmds.delete(posGrp)

    cmds.delete(grp)

    cmds.undoInfo(closeChunk=True)
Ejemplo n.º 29
0
 def clusterPoint(self, _point, _control, _name, _constraint = cmds.parentConstraint, _aim = False):
     #pos = cmds.xform(_control, t=1, q=1, ws=1)
     #cmds.xform(_point, t=pos, ws=1)
     clusterResult = cmds.cluster(_point, n=_name)
     #cmds.setAttr(clusterResult[1]+".visibility", 0)
     rc.addToLayer(self.m_sceneData, "hidden", [clusterResult[1]])
     cmds.parent(clusterResult[1], self.m_group)
     _constraint(_control, clusterResult[1], mo=1)
     if _aim:
         cmds.aimConstraint(
             _aim,
             clusterResult[1],
             mo=True
             )
     return clusterResult[1]
Ejemplo n.º 30
0
	def createRig(self,*args):
		"""
		  Create Piston rig.
		"""
		prefix = mc.textFieldGrp(self.prefixFld,query=True,text=True)
		casingLoc = mc.textFieldButtonGrp(self.casingFld,query=True,text=True)
		rodLoc = mc.textFieldButtonGrp(self.rodFld,query=True,text=True)
		
		aim1 = mc.aimConstraint(rodLoc, casingLoc, weight=1, aimVector=(1,0,0), upVector=(0,1,0), worldUpType='vector', worldUpVector=(0,1,0), mo=False)
		aim2 = mc.aimConstraint(casingLoc, rodLoc, weight=1, aimVector=(1,0,0), upVector=(0,1,0), worldUpType='vector', worldUpVector=(0,1,0), mo=False)
		
		casingGrp = mc.group(casingLoc,n=casingLoc+'_buffer')
		rodGrp = mc.group(rodLoc,n=rodLoc+'_buffer')
		
		mc.group(casingGrp,rodGrp,n=prefix+'_grp')
Ejemplo n.º 31
0
    def setup(self):

        #handle which direction UPV will be in
        x = 5
        y = 0
        z = 0
        #control and grp frz creation

        #organize and place into groups
        #ctrlGroup
        self.ctrlGrp = cmds.createNode("transform",
                                       n="{0}_ctrl_grp".format(self.getName()))
        #Master Group
        self.masterGrp = cmds.createNode("transform",
                                         n="{0}_rbn_grp".format(
                                             self.getName()))

        for i in range(int(self.jointAmmount)):

            inc = i + 1
            #check if it's the MID!!!
            if i == self.middleList:
                #ctrl creation
                midCtrl = control.Control("{0}_ctrl{1}".format(
                    self.nameSpace, inc), (0, i, 0),
                                          shape="star")
                midCtrl.create()
                midCtrl.setColor(17)
                self.ribbonCtrls.append(midCtrl.getName())
                #joint creation
                midJnt = joint.Joint("{0}_{1}{2}".format(
                    self.nameSpace, nameSpace.JOINT, inc), (0, i, 0),
                                     parent=midCtrl.getName())
                midJnt.create()
                self.ribbonJnts.append(midJnt.getName())
                #midJnt.setPosition([0,i,0])
                #upv creation
                upvCtrl = control.Control("{0}_{1}{2}".format(
                    self.nameSpace, nameSpace.UPV, inc), (0, i, 0),
                                          shape="cross")
                upvCtrl.create()
                self.ribbonUpvs.append(upvCtrl.getName())
                cmds.select(upvCtrl.getZeroGroup1())
                cmds.move(x, y, z, r=True)
                cmds.parent(upvCtrl.getZeroGroup1(), self.masterGrp)
                #hide upvector. Animators don't need to see it!
                cmds.setAttr("{0}.visibility".format(upvCtrl.getName()), 0)

                self.ribbonZeros.append(midCtrl.getZeroGroup1())
                self.getMidCtrl = midCtrl.getName()
                self.getMidZeroGroup = midCtrl.getZeroGroup1()

                cmds.parent(midCtrl.getZeroGroup1(), self.ctrlGrp)

                #midLocator
                self.midLoc = control.Control("{0}_midpoint".format(
                    self.nameSpace), (0, i, 0),
                                              shape="cross")
                self.midLoc.create()
                #hide it
                cmds.setAttr("{0}.visibility".format(self.midLoc.getName()), 0)

            else:
                #ctrl creation
                ribbonCtrl = control.Control("{0}_ctrl{1}".format(
                    self.nameSpace, inc), (0, i, 0),
                                             shape="square")
                ribbonCtrl.create()
                self.ribbonCtrls.append(ribbonCtrl.getName())
                #loc creation
                ribbonLoc = cmds.spaceLocator(
                    n="{0}_loc{1}".format(self.nameSpace, inc))
                cmds.parent(ribbonLoc[0], ribbonCtrl.getName())
                self.ribbonLocs.append(ribbonLoc[0])
                cmds.setAttr("{0}.ty".format(ribbonLoc[0]), 0)
                #hide it
                cmds.setAttr("{0}.visibility".format(ribbonLoc[0]), 0)
                #joint creation
                ribbonJnt = joint.Joint("{0}_{1}{2}".format(
                    self.nameSpace, nameSpace.JOINT, inc), (0, i, 0),
                                        parent=ribbonCtrl.getName())
                ribbonJnt.create()
                self.ribbonJnts.append(ribbonJnt.getName())
                #upv creation
                upvCtrl = control.Control("{0}_{1}{2}".format(
                    self.nameSpace, nameSpace.UPV, inc), (0, i, 0),
                                          shape="cross")
                upvCtrl.create()
                self.ribbonUpvs.append(upvCtrl.getName())
                cmds.parent(upvCtrl.getZeroGroup1(), ribbonCtrl.getName())
                cmds.select(upvCtrl.getZeroGroup1())
                cmds.move(x, y, z, r=True)

                #hide upvector. Animators don't need to see it!
                cmds.setAttr("{0}.visibility".format(upvCtrl.getName()), 0)

                self.ribbonZeros.append(ribbonCtrl.getZeroGroup1())

                cmds.parent(ribbonCtrl.getZeroGroup1(), self.ctrlGrp)

                #orientControls. ribbons are default set to z-downaxis
                ribbonCtrl.setOrientation('z')
                #make them a little smaller too
                cmds.select("{0}.cv[*]".format(ribbonCtrl.getName()))
                cmds.scale(0.6, 0.6, 0.6, r=True)

        #aim contraint startLoc to midCtrl
        cmds.aimConstraint(self.ribbonCtrls[1],
                           self.ribbonLocs[0],
                           mo=True,
                           wut="object",
                           wuo=self.ribbonUpvs[0])

        #aim constraint endLoc to midCtrl
        cmds.aimConstraint(self.ribbonCtrls[1],
                           self.ribbonLocs[-1],
                           mo=True,
                           wut="object",
                           wuo=self.ribbonUpvs[-1])

        #parentConstraint start and end ctrls to midloc
        cmds.parentConstraint(self.ribbonCtrls[0], self.ribbonCtrls[-1],
                              self.midLoc.getName())

        #pointConstraint midZeroGrp to midLoc
        cmds.pointConstraint(self.midLoc.getName(), self.ribbonZeros[1])

        #aim midZero to startCtrl
        cmds.aimConstraint(self.ribbonCtrls[-1],
                           self.ribbonZeros[1],
                           wut="object",
                           wuo=self.ribbonUpvs[1],
                           mo=True)
        #parentConstraint startUpv and endUpv to midUpv
        cmds.parentConstraint(self.ribbonUpvs[-1], self.ribbonUpvs[0],
                              self.ribbonUpvs[1])
Ejemplo n.º 32
0
    def SetupEyes(self):

        if cmds.objExists("LEye") and cmds.objExists("REye"):
            cmds.group(em=True, name="ReyeOrientacion")
            cmds.joint(name="REyeJoint")
            cmds.group(em=True, name="ReyeBase")
            cmds.group(em=True, name="ReyeLookAt")
            cmds.group(em=True, name="ReyePointLookAt")

            cmds.group(em=True, name="LeyeOrientacion")
            cmds.joint(name="LEyeJoint")
            cmds.group(em=True, name="LeyeBase")
            cmds.group(em=True, name="LeyeLookAt")
            cmds.group(em=True, name="LeyePointLookAt")

            cmds.group(em=True, name="eyeOrientation")

            RMRigTools.RMAlign("LEye", "LeyeBase", 3)
            RMRigTools.RMAlign("LEye", "LeyeOrientacion", 3)
            RMRigTools.RMAlign("LEye", "LeyeLookAt", 3)
            RMRigTools.RMAlign("LEye", "LeyePointLookAt", 3)

            cmds.move(10, "LeyePointLookAt", moveZ=True)
            EyeParent = cmds.listRelatives("LEye", parent=True)
            cmds.parent("LeyeBase", EyeParent)
            cmds.parent("LeyeLookAt", "LeyeBase")
            cmds.parent("LeyeOrientacion", "LeyeLookAt")

            cmds.aimConstraint("LeyePointLookAt",
                               "LeyeLookAt",
                               aimVector=[0, 0, 1],
                               worldUpObject="eyeOrientation",
                               worldUpType="objectrotation")

            cmds.expression(name="LEyeExpresionX", unitConversion="none")
            script = "LeyeOrientacion.rotateY = (Character_LF_Ojo_Ctrl_fc.translateX * 4 + Character_MD_OjoRectangle_ctrl_fc.translateX * 4)/10"
            cmds.expression("LEyeExpresionX",
                            edit=True,
                            string=script,
                            unitConversion="none")
            cmds.expression(name="LEyeExpresionY", unitConversion="none")
            script = "LeyeOrientacion.rotateX = -(Character_LF_Ojo_Ctrl_fc.translateY * 4 + Character_MD_OjoRectangle_ctrl_fc.translateY * 4)/10"
            cmds.expression("LEyeExpresionY",
                            edit=True,
                            string=script,
                            unitConversion="none")

            RMRigTools.RMAlign("REye", "ReyeBase", 3)
            RMRigTools.RMAlign("REye", "ReyeOrientacion", 3)
            RMRigTools.RMAlign("REye", "ReyeLookAt", 3)
            RMRigTools.RMAlign("REye", "ReyePointLookAt", 3)

            cmds.move(10, "ReyePointLookAt", moveZ=True)
            EyeParent = cmds.listRelatives("REye", parent=True)
            cmds.parent("ReyeBase", EyeParent)
            cmds.parent("ReyeLookAt", "ReyeBase")
            cmds.parent("ReyeOrientacion", "ReyeLookAt")

            cmds.aimConstraint("ReyePointLookAt",
                               "ReyeLookAt",
                               aimVector=[0, 0, 1],
                               worldUpObject="eyeOrientation",
                               worldUpType="objectrotation")

            cmds.expression(name="REyeExpresionX", unitConversion="none")
            script = "ReyeOrientacion.rotateY = (Character_RH_Ojo_Ctrl_fc.translateX * 4 + Character_MD_OjoRectangle_ctrl_fc.translateX * 4)/10"
            cmds.expression("REyeExpresionX",
                            edit=True,
                            string=script,
                            unitConversion="none")

            cmds.expression(name="REyeExpresionY", unitConversion="none")
            script = "ReyeOrientacion.rotateX = -(Character_RH_Ojo_Ctrl_fc.translateY * 4 + Character_MD_OjoRectangle_ctrl_fc.translateY * 4)/10"
            cmds.expression("REyeExpresionY",
                            edit=True,
                            string=script,
                            unitConversion="none")

            RMRigTools.RMAlign(EyeParent, "eyeOrientation", 1)

            cmds.parent("eyeOrientation", EyeParent)

            # $LeyeBase.parent=$LEye.parent;
            # $ReyeBase.parent=$REye.parent;

            cmds.parent("LEye", "LeyeOrientacion")
            cmds.parent("REye", "ReyeOrientacion")
            '''if cmds.objExists("*REyeGeo*"):
                EyeGeo=cmds.ls("*REyeGeo*",type="transform")
                for geo in EyeGeo:
                    cmds.bindSkin(geo,"REyeJoint")

            if cmds.objExists("*LEyeGeo*"):
                EyeGeo=cmds.ls("*LEyeGeo*",type="transform")
                for geo in EyeGeo:
                    cmds.bindSkin(geo,"LEyeJoint")
            '''

            cmds.parent("OjosLookAt", EyeParent)

            cmds.parent("LeyePointLookAt", "OjosLookAt_L")
            cmds.parent("ReyePointLookAt", "OjosLookAt_R")
        else:
            print "No existen los objetos LEye y REye"
Ejemplo n.º 33
0
	def setAim(self):
		cmds.aimConstraint(self._target, self._obj, aim=[0, 1, 0], u=[0, 1, 0], wu=[0, 1, 0], o=[0, 0, 0], wut='vector')
Ejemplo n.º 34
0
    def bake_to_ctrls(start_frame, end_frame, frame_offset, crv_setup_d,
                      fk_chains):
        """
        Bake simulation movement to ctrls.

        :param start_frame: start frame
        :type start_frame: int

        :param end_frame: end frame
        :type end_frame: int

        :param crv_setup_d: hair related nodes by fk chain
        :type crv_setup_d: dict

        :param fk_chains: ctrls list by fk chain
        :type fk_chains: dict

        :param frame_offset: number of frame to offset
        :type frame_offset: int
        """
        # Loop in frames
        for frame in range(start_frame, end_frame + 1):
            mc.currentTime(frame)
            # Loop in fk chains : determine cv number
            for chain in crv_setup_d:
                out_crv_name = crv_setup_d[chain][3]
                out_crv_shape = mc.listRelatives(out_crv_name, c=True,
                                                 s=True)[0]
                out_crv_degree = mc.getAttr('%s.degree' % out_crv_shape)
                out_crv_span = mc.getAttr('%s.spans' % out_crv_shape)
                out_cv_number = out_crv_degree + out_crv_span
                # Loop in cvs : query world position, paste it on ctrl, query
                # local position of ctrl, key it on the corresponding frame
                for cv in range(1, out_cv_number):
                    cv_pos = mc.xform('%s.cv[%s]' % (out_crv_shape, cv),
                                      q=True,
                                      t=True,
                                      ws=True)

                    # ROTATE CALCULATION AND KEYING
                    # Create tmp transform and aim to it
                    tmp_cv = mc.createNode('transform',
                                           n='tmp_frame_%s_cv_%s' %
                                           (frame, cv))
                    mc.xform(tmp_cv, t=cv_pos, ws=True)
                    if ':r_' in chain or chain.startswith('r_'):
                        tmp_ct = mc.aimConstraint(tmp_cv,
                                                  fk_chains[chain][cv - 1],
                                                  aim=[0.0, -1.0, 0.0],
                                                  mo=False)
                    else:
                        tmp_ct = mc.aimConstraint(tmp_cv,
                                                  fk_chains[chain][cv - 1],
                                                  aim=[0.0, 1.0, 0.0],
                                                  mo=False)
                    # Get rotate values and clean nodes
                    rotate = mc.xform(fk_chains[chain][cv - 1],
                                      q=True,
                                      ro=True,
                                      os=True)

                    # Add keyframes
                    if mc.getAttr('%s.rx' % fk_chains[chain][cv - 1], k=True):
                        mc.setKeyframe(fk_chains[chain][cv - 1],
                                       at='rx',
                                       t=frame + frame_offset,
                                       v=rotate[0])
                    if mc.getAttr('%s.ry' % fk_chains[chain][cv - 1], k=True):
                        mc.setKeyframe(fk_chains[chain][cv - 1],
                                       at='ry',
                                       t=frame + frame_offset,
                                       v=rotate[1])
                    if mc.getAttr('%s.rz' % fk_chains[chain][cv - 1], k=True):
                        mc.setKeyframe(fk_chains[chain][cv - 1],
                                       at='rz',
                                       t=frame + frame_offset,
                                       v=rotate[2])

                    mc.delete(tmp_ct, tmp_cv)
Ejemplo n.º 35
0
                                                     chainIdx=k,
                                                     chainRoot=mainCtrl,
                                                     sf=3.0,
                                                     df=0.3)
    springNdCol.append(rtsN)
    spTargChain.append(tractTarg)

for tar in spTargChain:  #tar=spTargChain[0]
    targ = tar[:-1] + 'b'
    springNd = tar + '_sprn'
    _p = cmds.listRelatives(targ, parent=True)
    if (_p):
        _p_p = cmds.listRelatives(_p, parent=True)
        if (_p_p):
            # AimConst
            cmds.aimConstraint(springNd, _p, wuo=_p_p[0], u=[-1, 0, 0])
            # Parent
            cmds.parent(tar, _p_p[0])

# group sorting
mot = 'MotionSystem'
if (not cmds.objExists('MotionSystem')):
    mot = cmds.group(em=True, n="MotionSystem")
    cmds.setAttr("MotionSystem.tx", lock=True)
    cmds.setAttr("MotionSystem.ty", lock=True)
    cmds.setAttr("MotionSystem.tz", lock=True)
    cmds.setAttr("MotionSystem.rx", lock=True)
    cmds.setAttr("MotionSystem.ry", lock=True)
    cmds.setAttr("MotionSystem.rz", lock=True)
    cmds.setAttr("MotionSystem.sx", lock=True)
    cmds.setAttr("MotionSystem.sy", lock=True)
Ejemplo n.º 36
0
Archivo: poci.py Proyecto: mappp7/tools
    cs = cmds.listRelatives(i, s=1)[0]
    cmds.connectAttr(cs + '.worldSpace[0]', ci + '.inputCurve', f=1)
    clen = cmds.getAttr(ci + '.arcLength')
    clen_div = [x for x in xfrange(0, 1, 1.0 / num)]
    pj = None

    for y in clen_div:

        mpd = cmds.createNode('multDoubleLinear')
        cmds.connectAttr(ci + '.arcLength', mpd + '.input1', f=1)
        cmds.setAttr(mpd + '.input2', y)

        c2p = cmds.createNode('curveLength2ParamU')
        cmds.connectAttr(cs + '.worldSpace[0]', c2p + '.inputCurve', f=1)
        cmds.connectAttr(mpd + '.output', c2p + '.inputLength', f=1)

        poci = cmds.createNode('pointOnCurveInfo')
        cmds.connectAttr(cs + '.worldSpace[0]', poci + '.inputCurve', f=1)
        cmds.connectAttr(c2p + '.outputParamU', poci + '.parameter', f=1)
        cmds.select(cl=1)
        j = cmds.joint(n='C_Skin_horse' + '%s' % y + '_JNT')
        cmds.connectAttr(poci + '.position', j + '.translate', f=1)

        if pj:
            if y < 0.5:
                up = upLoc[0]
            else:
                up = upLoc[1]
            cmds.aimConstraint(pj, j, wut='object', wuo=up)
        pj = j
Ejemplo n.º 37
0
def run():
    """Builds Cambot animation rig"""

    cmds.file(force=True, new=True)

    #=========================
    # Import Build File
    #=========================
    cmds.file('{}scenes/{}'.format(PROJ_PATH, RIG_BUILD_FILE), i=True)

    #=========================
    # Top Rig Hierarchy
    #=========================
    top_node = cmds.group(name='{}_rig'.format(ASSET), empty=True)
    util.lock_unlock_channels(lock=True, attrs=['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])

    geo_node = util.create_category(top_node, 'geo')
    skl_node = util.create_category(top_node, 'skeleton')
    rig_node = util.create_category(top_node, 'rig')
    nox_node = util.create_category(top_node, 'noXform')

    cmds.parent('cn_root_jnt', skl_node)
    cmds.parent('cn_master_grp', rig_node)

    # Constrain root joint to master offset
    cmds.parentConstraint('cn_masterOffset_ctl', 'cn_root_jnt')
    cmds.scaleConstraint('cn_masterOffset_ctl', 'cn_root_jnt')

    #=========================
    # Body and Cog
    #=========================
    cmds.parentConstraint('cn_cog_ctl', 'cn_body_jnt', mo=True)

    #=========================
    # Head Rig Build
    #=========================
    connect_control_to_joint('cn_head_ctl', 'cn_head_jnt', connections=['rotateX'], connect_offset=True)

    # Head aim (simple version)
    cmds.aimConstraint('cn_headAim_ctl', 'cn_head_off', mo=True, aim=[0,0,1], u=[0,-1,0], wuo='cn_body_jnt', skip=['y','z'])
    cmds.pointConstraint('cn_cog_ctl', 'cn_head_grp', mo=True, skip=['x','y'])

    #=========================
    # Neck Rig Build
    #=========================
    connect_control_to_joint('cn_neck_ctl', 'cn_neck_jnt', connections=['rotateY'], connect_offset=True)

    #=========================
    # Shoulders/Legs Build
    #=========================
    legs.rig_legs()
    #legs.add_softIK()

    #=========================
    # Leg Pistons
    #=========================
    legs.rig_pistons()

    #=========================
    # Antenna Rig Build
    #=========================
    ant_up = antenna_setup('cn_antSide', 'cn_antSide_ctl', 'lf_antenna_jnt', aim=[0, 1, 0], up=[0, 0, 1])
    cmds.parent(ant_up, 'cn_head_ctl')

    ant_up = antenna_setup('cn_antRear', 'cn_antRear_ctl', 'lf_antennaRear_jnt', aim=[0, 1, 0], up=[0, 0, 1])
    cmds.parent(ant_up, 'cn_head_ctl')

    # add_antenna_jiggle()

    #=========================
    # Cable Rig Build
    #=========================
    # add_cable_rig()
    # add_cable_jiggle()

    #=========================
    # Import referenced model and remove model namespace
    #=========================
    import_references()
    remove_namespace('model')
    cmds.parent('{}_model'.format(ASSET), geo_node)

    #=========================
    # Skin model
    #=========================
    deform.skin_geo()

    #=========================
    # Cleanup scene
    #=========================
    lock_channels()

    #=========================
    # Set final display
    #=========================
    cmds.select(clear=True)
    cmds.viewFit()
    cmds.setAttr("hardwareRenderingGlobals.multiSampleEnable", 1)
    cmds.setAttr("hardwareRenderingGlobals.lineAAEnable", 1)

    cmds.setAttr("{}_rig.geo".format(ASSET), 2)
    cmds.setAttr("{}_rig.skeleton".format(ASSET), 0)
    cmds.setAttr("{}_rig.noXform".format(ASSET), 0)

    #=========================
    # Save final rig
    #=========================
    cmds.file(rename='{}scenes/{}'.format(PROJ_PATH, RIG_OUTPUT_FILE))
    cmds.file(save=True)

    LOG.info('Successfully built: {} Rig'.format(ASSET))
Ejemplo n.º 38
0
# aimAtLast.py

import maya.cmds as cmds

selectionList = cmds.ls(orderedSelection=True)

if len(selectionList) >= 2:

    print("Selected items %s" % selectionList)

    targetName = selectionList[len(selectionList) - 1]

    selectionList.remove(targetName)

    for objectName in selectionList:

        print("Constraining %s towards %s" % (objectName, targetName))

        cmds.aimConstraint(targetName, objectName, aimVector=[0, 1, 0])

else:

    print(" Please select two or more objects.")