Exemplo n.º 1
0
def createBlendshape(source, blendshape, AllP0, AllPDef):
    #------------MOTION VECTOR TRANSFER-------------#
    # create array of all vertices of the blendshape
    cmds.move(0,0,0, blendshape)
    cmds.select(clear=True)
    cmds.select(blendshape+".vtx[*]")
    AllPBlend = cmds.ls(sl=1, fl=True)
    #vertex list original source mesh
    O = getVtxPos( source )

    #vertex list source mesh blendshape
    B = getVtxPos( blendshape )

    # matrix of motion vectors from source to blendshape vertex positions
    MV = numpy.matrix(B)-numpy.matrix(O) 
    MV = numpy.asmatrix(MV)
    
    '''
    # rotating and scaling of motion vectors using these functions gives wrong results
    # and is not deforming the motion vectors like it should.
    # I have not been able to debug this in the given time and have therefore taken these parts out for the moment.
    # Simply using the motion vectors on the deformed source mesh results in acceptable blend shapes
    
    #-------------------------ROTATION-----------------------------#

    N0 = normalMatrix(AllP0) # normal matrix for source

    N1 = normalMatrix(AllPDef) # normal matrix for deformed source
    #------------

    # list of motion vector rotations
    R = []
    # find local source vertex coordinate systems before deformation, then after deformation
    for i in range(0, len(P0)):
        localOrig = findLocal(AllP0[i], N0[i])
        localDef = findLocal(AllPDef[i], N1[i])
        ODR = findRotationMatrix(localOrig, localDef)
        R.append(ODR)
    R = numpy.asarray(R)
        
    #--------------------------MAGNITUDE---------------------------#
        
    S = []
    for i in AllP0: 
        S.append(findScaleMatrix(i, AllP0, P0, R))
    S = numpy.asarray(S)

    #--------OVERALL MOTION VECTOR ROTATION AND MAGNITUDE ADJUSTMENT--------#
    '''
    # duplicate deformed source to make blendshape
    blendName = "target" + blendshape
    cmds.duplicate("sourceDeformed", n = blendName)
    cmds.select(clear=True)
    cmds.select(blendName+".vtx[*]")
    defBlend = cmds.ls(sl=1, fl=True)


    for i in range(0,len(AllP0)):
        cmds.move(float(MV[i, 0]), float(MV[i, 1]), float(MV[i, 2]), defBlend[i], r=True)
        '''
Exemplo n.º 2
0
    def _setup_wire_deformer(self, mesh, wire, wirebase, curve,
                             parent, complexity):
        """Setup the wire deformer. If complexity is 1 or higher call this
        function recursively to create a wire deformer on the nurbs surface.

        @param mesh(string): PolyMesh used to wire deform
        @param wire(string): Descriptive part of the name of the wire deformer
        @param wirebase(string): Descriptive part of the name of the base wire
        @param curve(string): Curve used for wireTool deformer
        @param parent(string): Parent node of the wire setup
        @param complexity(uint): complexity level value
        """
        w = wire
        wb = wirebase
        cmds.wire(mesh, w=curve, dds=[0, 10000], n=w, foc=False)
        cmds.rename(cmds.listConnections('%s.baseWire[0]' % w)[0], wb)
        if not cmds.listRelatives(curve, p=True) == [self.wire_grp]:
            cmds.parent(curve, wb, self.wire_grp)
        # end if
        wbs = cmds.listRelatives(wb, ad=True, type='shape')[0]
        cs = cmds.listRelatives(curve, ad=True, type='shape')[0]
        cmds.setAttr('%s.rotation' % w, 0)
        # connect to showHistory
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % w)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wb)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wbs)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % cs)
        if complexity:
            cmds.duplicate(self.curve, n=self.nrbcurve)
            return self._setup_wire_deformer(self.surface, self.nrbwire,
                                             self.nrbwirebase, self.nrbcurve,
                                             self.parent, 0)
Exemplo n.º 3
0
    def __setup_final_meshes(self):
        #--- this method setups the final meshes
        if 'FINAL' in self.mesh:
            if cmds.objExists(self.mesh):
                self.final_mesh = self.mesh
            else:
                self.final_mesh = cmds.duplicate(self.mesh)
                cmds.parent(self.final_mesh, self.sf_final_meshes)
                final_name = cmds.rename(self.final_mesh,
                                         self.mesh)
                self.final_mesh = final_name
        else:
            if cmds.objExists(self.mesh + 'FINAL'):
                self.final_mesh = self.mesh + 'FINAL'
            else:
                self.final_mesh = cmds.duplicate(self.mesh)
                cmds.parent(self.final_mesh, self.sf_final_meshes)
                final_name = cmds.rename(self.final_mesh,
                                         self.mesh + 'FINAL')
                self.final_mesh = final_name

        if cmds.objExists(self.mesh + '_BSP'):
            #--- setup blendShape deformer
            self.final_bsp = self.mesh + '_BSP'
            cmds.setAttr(self.final_bsp + '.' + self.mesh, 1)
            cmds.setAttr(self.mesh + '.v', 0)
        else:
            if 'FINAL' in self.mesh:
                self.mesh = self.mesh.split('FINAL')[0]
            self.final_bsp = cmds.blendShape(self.mesh,
                                             self.final_mesh,
                                             name = self.mesh + '_BSP')[0]
            cmds.setAttr(self.final_bsp + '.' + self.mesh, 1)
            cmds.setAttr(self.mesh + '.v', 0)
Exemplo n.º 4
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)
Exemplo n.º 5
0
def triangulateMesh(isObj, simplify, smoothe):
	if isObj and not cmds.objExists('triObj'):
		cmds.select(baseObject)
		cmds.duplicate(baseObject, name = "triObj")
		cmds.select('triObj')

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

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

		num_faces = cmds.polyEvaluate('triObj', f=True)
		
		print "Triangulating faces..."
		#iterate over faces
		face_i = 0
		while face_i < num_faces:
			if ((num_faces - face_i) % 5 == 0):
				print "Triangulate check: Approximately " + str(num_faces - face_i) + " faces remaining...."
			face = cmds.select('triObj.f['+ str(face_i)+']')		
			verts = getCorners(isObj,face_i)
			if not isCoplanar(verts):
				cmds.polyTriangulate('triObj.f['+ str(face_i)+']')
				num_faces = cmds.polyEvaluate('triObj', f=True)
			face_i +=1
Exemplo n.º 6
0
def symmetry():

    #getting nodes
    sel = cmds.ls(selection=True)
    if len(sel) == 1:
        cmds.warning('Select the edited mesh first, then the original mesh last!')
        return
    if len(sel) > 2:
        cmds.warning('Select the edited mesh first, then the original mesh last!')
        return

    edit = sel[0]
    original = sel[1]

    #creating symmetry mesh
    mirror = mirrorBlendshape([edit], original)[0]
    copy = cmds.duplicate(original)[0]
    bldShp = cmds.blendShape(edit, mirror, copy)[0]
    cmds.setAttr('%s.%s' % (bldShp, edit), 1)
    cmds.setAttr('%s.%s' % (bldShp, mirror), 1)
    symmetry = cmds.duplicate(copy)[0]
    symmetry = cmds.rename(symmetry, edit + '_symmetry')

    cmds.delete(copy, mirror)

    return symmetry
Exemplo n.º 7
0
    def prepare(self):
        """ preparing mirror corretiveShape """
        # default pose
        self.setDefaultPose()
        meshName = (name.getSide(self.mesh)+ "_" + name.getDescription(self.mesh) + "DUP" + "_" + name.getType(self.mesh))
        #make hierachy
        if not cmds.objExists(meshName): 
            dup = cmds.duplicate(self.mesh, rr=True, n=meshName)
            attribute.lockAll(dup[0], True)
            cmds.setAttr(dup[0] + ".visibility", 0)
            cmds.parent(dup, self.DupsName)
            self.wrapDeformer(dup, self.mesh)
            xform.zeroOut(dup[0], t = 1, r = 1, s = 1)
            self.dups.append(dup)
        #END if
        else:
            dup = meshName
            print "%s already exists!!!" % meshName
        #END else

        #pose copy
        eachPoseName = (name.getSide(self.mesh)+ "_" + name.getDescription(self.mesh) + self.description + "_" + name.getType(self.mesh))
        cmds.setAttr(self.control + ".rotate" + self.axis, self.angle)
        self.eachPose = cmds.duplicate(dup, rr=True, n=eachPoseName)
        cmds.parent(self.eachPose, self.TransName)
        xform.zeroOut(self.eachPose[0], t = 1, r = 1, s = 1)

        #neutral pose.        
        self.setDefaultPose()
Exemplo n.º 8
0
    def insertDots(self):

        # copy dot object
        # copy cutout object
        # run mesh difference
        # delete the layers
        # delete the groups
        # rename the cutout.

        for dot in self.dots:
            # Copy sphere object from the template object.
            newDot = cmds.duplicate(self.getTemplateObjectName(dot.templateName()))[0]

            for cutout in dot.cutouts:

                # Copy cutout object from the template object, and rotate it.
                newCutout = cmds.duplicate(self.getTemplateObjectName(cutout.shape))[0]
                cutoutDagPath = self.getDagPathFromPath(newCutout)
                mfnTransform = OpenMaya.MFnTransform(cutoutDagPath)

                mfnTransform.rotateBy(cutout.rotation, OpenMaya.MSpace.kTransform)

                # Mesh boolean combine, with 'difference' operator.
                boolOp = cmds.polyBoolOp(newDot, newCutout, op=2)

                # Update the dot copy name and remove history.
                newDot = boolOp[0]
                cmds.delete(newDot, constructionHistory=True)

            dotPath = "dot_{0}".format(dot.name())
            cmds.rename(newDot, dotPath)

            # Move the new dot onto the final grid for printing.
            self.positionDot(dotPath, dot.vertexId)
def makeRobot():
    MayaCmds.polyCube(name="head")
    MayaCmds.move(0, 4, 0, r=1)

    MayaCmds.polyCube(name="chest")
    MayaCmds.scale(2, 2.5, 1)
    MayaCmds.move(0, 2, 0, r=1)
    MayaCmds.polyCube(name="leftArm")
    MayaCmds.move(0, 3, 0, r=1)
    MayaCmds.scale(2, 0.5, 1, r=1)
    MayaCmds.duplicate(name="rightArm")
    MayaCmds.select("leftArm")
    MayaCmds.move(1.25, 0, 0, r=1)
    MayaCmds.rotate(0, 0, 32, r=1, os=1)
    MayaCmds.select("rightArm")
    MayaCmds.move(-1.25, 0, 0, r=1)
    MayaCmds.rotate(0, 0, -32, r=1, os=1)
    MayaCmds.select("rightArm", "leftArm", "chest", r=1)
    MayaCmds.group(name="body")

    MayaCmds.polyCube(name="bottom")
    MayaCmds.scale(2, 0.5, 1)
    MayaCmds.move(0, 0.5, 0, r=1)
    MayaCmds.polyCube(name="leftLeg")
    MayaCmds.scale(0.65, 2.8, 1, r=1)
    MayaCmds.move(-0.5, -1, 0, r=1)
    MayaCmds.duplicate(name="rightLeg")
    MayaCmds.move(1, 0, 0, r=1)
    MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1)
    MayaCmds.group(name="lower")

    MayaCmds.select("head", "body", "lower", r=1)
    MayaCmds.group(name="robot")
Exemplo n.º 10
0
Arquivo: mdc.py Projeto: 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
    def duplicate_button( self, *args  ):
        self.original_selected_objects = cmds.ls( selection=True )

        if( len(self.original_selected_objects) == 0 ):
            print "Nothing selected"
            return 0

        elif( len(self.original_selected_objects) == 1 ):
            self.relatives = cmds.listRelatives( children=True )

            if( len(self.relatives) == 1 ):
                print "Skip combine"
                cmds.duplicate( self.original_selected_objects, name=self.original_selected_objects[0] + "_Copy" )
                cmds.delete( constructionHistory=True )
                the_parent = cmds.listRelatives( parent=True )
                if( the_parent != None ):
                    cmds.parent( self.original_selected_objects[0] + "_Copy", world=True )

            else:
                self.combine()

        else:
            self.combine()

        self.newOriginCopy = cmds.ls( selection=True )[0]
        self.bbox = cmds.exactWorldBoundingBox( self.newOriginCopy )
        cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, self.newOriginCopy + ".scalePivot", self.newOriginCopy + ".rotatePivot", absolute=True)
        cmds.move( 0, 0, 0, self.newOriginCopy, rpr=True )
        cmds.makeIdentity( apply=True, t=1, r=1, s=1 )
        cmds.delete( constructionHistory=True )
Exemplo n.º 12
0
def geoCrowd() :
	# Import referenced characters
	# select geometries then run script
	sels = mc.ls( sl=True )
	ctrls = []

	for sel in sels :
		
		ns = sel.split( ':' )[0]
		
		if not ns in ctrls :
			
			ctrl = mc.circle( nr=(0,1,0) , ch=False )[0]
			grp = mc.group( ctrl )
			root = '%s:Root_Ctrl' % ns
			
			mc.delete( mc.parentConstraint( root , grp ) )
			
			ctrl = mc.rename( ctrl , ns )
			mc.rename( grp , '%s_grp' % ns )
			ctrls.append( ns )
			
		attrs = ('tx','ty','tz','rx','ry','rz','sx','sy','sz')
		for attr in attrs :
			
			if mc.getAttr( '%s.%s' % ( sel , attr ) , l=True ) :
				mc.setAttr( '%s.%s' % ( sel , attr ) , l=False )
		
		mc.select( sel , r=True )
		mc.duplicate( sel , rr=True )
		geo = mc.ls( sl=True , l=True )[0]
		mc.parent( geo , ctrl )
 def CreateCamera(self):
     print "Creating camera"
     
     #Array to store all objects in the scene
     cmds.select(None)
     
     #Copy from the current active camera
     cmds.duplicate( self.GetActiveCamera(), name = self.Camera)
     try:cmds.delete(self.Camera + "|CMForegroundPlane")
     except:pass
     try:cmds.delete(self.Camera + "|CMBackgroundPlane")
     except:pass
     i = 0
     while(cmds.objExists("shot_" + str(i))):
         try:cmds.delete(self.Camera + "|" + "shot_" + str(i) + "_ImagePlane")
         except:pass
         i = i + 1
     
     
     #Make the camera startup so that the user may not delete it directly
     #Enable the resolution gate
     cmds.camera(self.Camera, edit = True, startupCamera = True, displayResolution = True)
     
     #Make the camera hidden
     cmds.setAttr(self.Camera + ".visibility", False)
     
     #Add the attributes to define range and renderability
     cmds.select(self.Camera)
     cmds.addAttr(longName = 'CMRenderable', attributeType = 'bool', defaultValue = True)
     cmds.addAttr(longName = 'StartRange', attributeType = 'short', defaultValue = 0, min = 0, max = 35)
     cmds.addAttr(longName = 'StopRange' , attributeType = 'short', defaultValue = 35, min = 0, max = 35)
     cmds.select(None)
Exemplo n.º 14
0
def claw(ref):
    # duplicate geo
    selection = cmds.ls(sl=True)
    for locator in selection:
        split = locator.split("section_")
        name = "%sclaw_%s" % (split[0], split[1].replace("locator", "C"))
        bind = "bind_%s" % name

        old_name = "old_%s" % name
        old_bind = "old_%s" % bind

        cmds.rename(name, old_name)
        cmds.rename(bind, old_bind)

        cmds.duplicate(ref, rr=True, un=True, name=bind)
        cmds.duplicate(bind, name=name)

        shape = cmds.listRelatives(bind, s=True)[0]
        claw_bs = cmds.listConnections(shape, type="blendShape", s=True)[0]
        cmds.connectAttr(locator + ".parameter", claw_bs + ".tentacle_claw")

        cmds.scaleConstraint(locator, bind, maintainOffset=False)
        cmds.parentConstraint(locator, bind, maintainOffset=False)

        bs = cmds.blendShape(bind, name, origin="world")
        cmds.setAttr(bs[0] + ".w[0]", 1)

        cmds.parent(name, cmds.listRelatives(old_name, p=True)[0])
        cmds.parent(bind, cmds.listRelatives(old_bind, p=True)[0])

        cmds.delete(old_name, old_bind)
Exemplo n.º 15
0
def tip(ref):
    selection = cmds.ls(sl=True)
    for tip in selection:
        bind = tip
        name = tip.replace("bind_", "")

        old_name = "old_%s" % name
        old_bind = "old_%s" % bind

        cmds.rename(name, old_name)
        cmds.rename(bind, old_bind)

        cmds.duplicate(ref, rr=True, un=True, name=bind)
        cmds.duplicate(bind, name=name)

        bs = cmds.blendShape(bind, name, origin="world")
        cmds.setAttr(bs[0] + ".w[0]", 1)

        joint = cmds.listConnections(cmds.parentConstraint(old_bind, q=True), type="joint")[0]
        cmds.parentConstraint(joint, bind, maintainOffset=False)

        cmds.parent(name, cmds.listRelatives(old_name, p=True)[0])
        cmds.parent(bind, cmds.listRelatives(old_bind, p=True)[0])

        cmds.delete(old_name, old_bind)
Exemplo n.º 16
0
def cut_one_with_one(cutter, target):
  print 'Cutting 1:1 %s with %s' % (target, cutter)

  # Duplicate targets
  targetA = cmds.duplicate(target, returnRootsOnly=True)[0]
  targetB = cmds.duplicate(target, returnRootsOnly=True)[0]

  prep(targetA)
  prep(targetB)

  cmds.delete(target)

  # Set up cutters
  cutterA = cmds.duplicate(cutter, returnRootsOnly=True)[0]
  cutterB = cmds.duplicate(cutter, returnRootsOnly=True)[0]

  prep(cutterA)
  prep(cutterB)

  # Flip second cutter's normals
  cmds.polyNormal(cutterB, normalMode=0, userNormalMode=0, constructionHistory=0)

  # Perform intersections
  newTargetA = cmds.polyBoolOp(cutterA, targetA, op=3, constructionHistory=False)[0]
  newTargetB = cmds.polyBoolOp(cutterB, targetB, op=3, constructionHistory=False)[0]

  return [newTargetA, newTargetB]
Exemplo n.º 17
0
 def __init__(self, curve_sel, vertex_list):
     self.curve_sel = curve_sel
     self.verts = vertex_list
     self.find_length = Find_Out()
             
     self.link_length = self.find_length.edge_length(self.verts)
     self.chain_length = self.find_length.curve_length(self.curve_sel)
     self.link_total = int(self.chain_length/self.link_length)
     
     cmds.duplicate(self.curve_sel, n = 'buildCurve')
     cmds.rebuildCurve('buildCurve', ch = 1, rpo = 1, rt = 0, end = 1, kr = 2, kep = 1, kt = 0, kcp = 0, s = self.link_total/2, d = 3, tol = 0.01 )
     
     self.num_cv = int(cmds.getAttr ('buildCurve.degree'))+ (cmds.getAttr ('buildCurve.spans'))
     
     for dummy_cv in range(self.num_cv):
         dummy_cv_pos = (cmds.getAttr ('buildCurve.cv['+ str(dummy_cv) +']'))
         
         if dummy_cv == 0:
             cmds.joint(n=self.curve_sel+'_jointRoot',p = dummy_cv_pos[0])
         elif dummy_cv == self.num_cv - 1:
             cmds.joint(n=self.curve_sel+'_jointEnd', p = dummy_cv_pos[0])
         else:
             cmds.joint(n=self.curve_sel+'_joint_'+(str(dummy_cv)),p = dummy_cv_pos[0])    
     
     cmds.delete('buildCurve')        
     cmds.ikHandle( sj = (self.curve_sel+'_jointRoot'), ee = (self.curve_sel+'_jointEnd'), c = self.curve_sel,
             sol = 'ikSplineSolver', scv = 0, pcv = 0, ccv = 0, ns = 4)       
Exemplo n.º 18
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
Exemplo n.º 19
0
def add_blink(upperLidCurve, lowerLidCurve, upperLidCtrlCurve, lowerLidCtrlCurve):
# duplicate upLid HiRes curve for upLidBlink curve
# duplicate lowerLid HiRes curve for lowerLidBlink curve
    upperLidBlinkCurve = cmds.duplicate(upperLidCurve, name="%sBlink"%upperLidCurve)[0]
    lowerLidBlinkCurve = cmds.duplicate(lowerLidCurve, name="%sBlink"%lowerLidCurve)[0]
    
# duplicate upLid loRes curve for blinkCurve
    blinkCurve = cmds.duplicate(upperLidCtrlCurve, name="blinkCurve")[0]
    
# blendShape upLid loRes and lowerLid loRes into blinkCurve(0.7/0.3)
    bsNode = cmds.blendShape(upperLidCtrlCurve, lowerLidCtrlCurve, blinkCurve)[0]
     
# wireDeformer blinkCurve to upLidBlink at blendShape(1.0/0)
    cmds.blendShape(bsNode, e=True, w=[(0,1), (1,0)])
    upperWireNode, upperWire, upperWireBase = utils.wire_deformer(blinkCurve, upperLidBlinkCurve)
     
# wireDeformer blinkCurve to lowerLidBlink at blendShape(0/0.1)
    cmds.blendShape(bsNode, e=True, w=[(0,0), (1,1)])
    lowerWireNode, lowerWire, lowerWireBase = utils.wire_deformer(blinkCurve, lowerLidBlinkCurve)
     
# default blendshape setting
    cmds.blendShape(bsNode, e=True, w=[(0,0.5), (1,0.5)])
     
# blendShape upLidBlink into upLid hiRes
# blendShape lowerLidBlink into lowerLid hiRes
    cmds.blendShape(upperLidBlinkCurve, upperLidCurve)
    cmds.blendShape(lowerLidBlinkCurve, lowerLidCurve)
Exemplo n.º 20
0
        def runTest(self):
            try:
                import maya.cmds as cmds

                def getShape(trans):
                    return cmds.listRelatives(trans, children=True, shapes=True)[0]

                cmds.file(new=1, f=1)
                shapeTransform = cmds.polyCube(name='singleShapePoly')[0]
                origShape = getShape(shapeTransform)
                dupeTransform1 = cmds.duplicate(origShape, parentOnly=1)[0]
                cmds.parent(origShape, dupeTransform1, shape=True, addObject=True, relative=True)
                dupeTransform2 = cmds.duplicate(dupeTransform1)[0]
                cmds.delete(dupeTransform1)
                dupeShape = getShape(dupeTransform2)

                # In maya 2014, this raises:
                # Error: Connection not made: 'singleShapePolyShape2.instObjGroups[1]' -> 'initialShadingGroup.dagSetMembers[2]'. Source is not connected.
                # Connection not made: 'singleShapePolyShape2.instObjGroups[1]' -> 'initialShadingGroup.dagSetMembers[2]'. Destination attribute must be writable.
                # Connection not made: 'singleShapePolyShape2.instObjGroups[1]' -> 'initialShadingGroup.dagSetMembers[2]'. Destination attribute must be writable.
                # Traceback (most recent call last):
                # File "<maya console>", line 13, in <module>
                # RuntimeError: Connection not made: 'singleShapePolyShape2.instObjGroups[1]' -> 'initialShadingGroup.dagSetMembers[2]'. Source is not connected.
                # Connection not made: 'singleShapePolyShape2.instObjGroups[1]' -> 'initialShadingGroup.dagSetMembers[2]'. Destination attribute must be writable.
                # Connection not made: 'singleShapePolyShape2.instObjGroups[1]' -> 'initialShadingGroup.dagSetMembers[2]'. Destination attribute must be writable. #

                cmds.parent(dupeShape, shapeTransform, shape=True, addObject=True, relative=True)
            except Exception:
                pass
            else:
                self.fail("ShapeParentInstance bug fixed!")
Exemplo n.º 21
0
def cleanDuplicate(targetObj):
    """
    arguments:
    targetObj - name of mesh that you want to duplicate
    
    todo:
    1. check that targetObj is a valid mesh
    2. currently resets deformer envelopes to 1... need to remember original value?
    3. cleanup intermediate object(s), possibly by obj export/import.
    
    """
    
    # get list of deformers on targetObj
    allDeformers = meval('findRelatedDeformer("%s")'%targetObj)
    
    # disable all deformers by setting envelope to 0
    for eachDfm in allDeformers:
        print eachDfm
        mc.setAttr('%s.envelope'%eachDfm, 0)
    
    # make duplicate    
    mc.duplicate(targetObj, n='%s_cleanDuplicate'%targetObj)
    
    # re-enable all deformers by setting envelope to 1
    for eachDfm in allDeformers:
        mc.setAttr('%s.envelope'%eachDfm, 1)
Exemplo n.º 22
0
def ctrl_pointer():
	mel.eval('curve -d 1 -p -1 0 0 -p 1 0 0 -p 1 1 0 -p 1 2 0 -p 1 3 0 -p 2 3 0 -p 0 5 0 -p -2 3 0 -p -1 3 0 -p -1 2 0 -p -1 1 0 -p -1 0 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11')
	ctrl = cmds.ls(sl=True)
	cmds.duplicate(rr=True)
	ctrl2 = cmds.ls(sl=True)
	cmds.setAttr(ctrl2[0] + '.rotateY', 90)
	print 'Curves have been positioned.'
	
	cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
	print 'Freezing transforms on curves.'
	
	cmds.select(ctrl, r=True)
	cmds.pickWalk(d='Down')
	cmds.select(ctrl2, add=True)
	cmds.parent(r=True, s=True)
	print 'Curves have been parented into single curve.'
	
	
	cmds.select(ctrl, r=True)
	mel.eval('doDelete')
	print 'Unsuded groups have been deleted.'
	
	cmds.select(ctrl2)
	mel.eval('CenterPivot')
	print 'Curve has been selected and its pivot has been centered.'
Exemplo n.º 23
0
def extractSplits():
    
    splits = cmds.ls(sl=True)
    bshp = "{0}_BSHP".format(splits[0])
    
    # first target should be set to 1, but just in case reset them all
    targets = getTargets(bshp)
    for target in targets:
        blendName = "{0}.{1}".format(bshp, target)
        cmds.setAttr( blendName, 0 )
    
    for target in targets:
        blendName = "{0}.{1}".format(bshp, target)
        cmds.setAttr( blendName, 1 )
        
        # duplicate each split
        for i, split in enumerate(splits):
            cmds.select(split)
            
            # name extraction
            extract = target.split("_")
            name = ("{0}_{1}{2}_{3}".format(extract[0], extract[1], str(i+1), extract[2]))
            
            cmds.duplicate(n=name)
        
        cmds.setAttr( blendName, 0)
Exemplo n.º 24
0
def getMeshVertexData( mesh ):
  returnData = []
  exportObject = 'bwExportObject'
  cmds.duplicate( mesh, n=exportObject )
  cmds.polyTriangulate(exportObject)
  numOfFaces = cmds.polyEvaluate(exportObject,  f=True )
  for i in xrange(0, numOfFaces):
    faceSelect = exportObject + '.f[' + str(i) + ']'
    fVertices = [] 
    fVertices = cmds.polyListComponentConversion(faceSelect, ff = True, tvf = True)
    fVertices = cmds.filterExpand(fVertices, sm = 70, ex = True)
    print fVertices
    for vertex in fVertices:
      faceDict = {}
      vName = cmds.polyListComponentConversion(vertex, fvf = True, tv = True)
      xyz = []
      xyz = cmds.xform(vName, q = True, os = True, t = True)
      faceDict['x'] = round(xyz[0], 2)
      faceDict['y'] = round(xyz[1], 2)
      faceDict['z'] = round(xyz[2], 2)
      normal = []
      normal = cmds.polyNormalPerVertex(vertex, q = True, xyz = True)
      faceDict['xN'] = round(normal[0], 2)
      faceDict['yN'] = round(normal[1], 2)
      faceDict['zN'] = round(normal[2], 2)
      # vuv = []
      # vuv = cmds.polyListComponentConversion(vertex, fvf = True, tuv = True)
      # uvCoords = []
      # uvCoords = cmds.polyEditUV(vuv[0], q = True, u = True, v = True)
      # faceDict['u'] = round(uvCoords[0], 2)
      # faceDict['v'] = round(uvCoords[0], 2)
      returnData.append(faceDict)
  cmds.delete(exportObject)
  return json.dumps(returnData)
Exemplo n.º 25
0
def mirror_shape(path):
    """In addition to mirroring transforms, also mirror shapes

    Arguments:
        path (str): Path to transform with shapes to mirror

    Returns:
        Path to mirrored transform

    """

    mirrored_transform = mirror_transform(path)
    mirrored_original = cmds.duplicate(path,
                                       name=path + "_duplicate")
    mirrored_group = cmds.createNode('transform',
                                     name=path + "_transform")
    cmds.parent(mirrored_original[0], mirrored_group)
    cmds.setAttr(mirrored_group + ".sx", -1)

    blendshape = cmds.blendShape((mirrored_original[0], mirrored_transform),
                                 origin='world')
    cmds.setAttr(blendshape[0] + "." + mirrored_original[0], 1)
    mirrored_with_shape = cmds.duplicate(mirrored_transform,
                                         inputConnections=True,
                                         returnRootsOnly=True)

    cmds.delete([mirrored_transform, mirrored_group])

    cmds.select(mirrored_with_shape, replace=True)

    return mirror_transform
Exemplo n.º 26
0
    def duplicateObject(self, objName, modifiedName, *args):

        # ベースオブジェクトを選択
        cmds.select(str(objName), r=True)

        # 複製しXMLと合致しなかった名前にリネーム
        cmds.duplicate(n=modifiedName, rr=True)
Exemplo n.º 27
0
def buildPlanes(block):
    buildings = []
    faces = block.faceList
    drop = block.dropRate
    i = 0
    sidewalkHeight = max(block.heightRange)/160.0
    for f in faces:
        if(random.random() >= block.dropRate):
            height = 1.0*random.choice(block.heightRange)
            levels = random.choice(block.levelRange)
            #get the midpoint of the current face
            verts = makeVertList(cmds.xform(f, q=True, t=True))
            midpoint = getMidpoint(verts, True)
            #make a duplicate of the parent plane
            cmds.select(block.parentPlane)
            dupName = block.name + "building_"+str(i)
            dupFace = dupName + ".f[0]"
            cmds.duplicate(name=dupName)
            cmds.xform(t=midpoint)
            #create building and add it to building list
            makeBuilding(dupFace, levels, height, sidewalkHeight)
            buildings += [dupName]
            i += 1
        if(not updateProgressWindow(i, len(faces))):
            break
    cmds.group(buildings, name=block.name + "_buildings")
    killProgressWindow()
Exemplo n.º 28
0
def splitShapeSetup():

    # create 3 splitOutput meshes that will be painted
    # start with creating the splitters
    selection = cmds.ls(sl=True)
    meshList = selection[:-1]
    base = selection[-1]
    
    splitters = []
    blends = []
    meshes = ["A", "B", "C"]
    inputMeshList = meshList

    # first target plays an important role, this is the one we're going to default turn on and align to in tx
    first = meshList[0]
    for i, letter in enumerate(meshes):
        # create splitters
        split = "{0}_split{1}".format(base, letter)
        cmds.duplicate(base, n=split)
        cmds.delete(cmds.parentConstraint(first, split))
        # how far to move the dup
        dist = (int(i) + 1) * 10
        cmds.move(dist, 0, 0, split, r=True)

        blend = "{0}_BSHP".format(split)
        cmds.select(split)
        cmds.blendShape(n=blend)
        splitters.append(split)
        blends.append(blend)


    # add blends and set them too yada yada
    blendDrivers = []
    blendDrivers = blendDrivers + meshList
    for i, split in enumerate(splitters):

        # connections?
        cmds.select(blendDrivers)
        cmds.select(split, tgl=True)
        mel.eval("performBlendShapeAdd 0;")
        blendDrivers.append(split)

        # if a splitter, set to -1
        for s in splitters:
            splitBshp = "{0}.{1}".format(blends[i], s)
            if cmds.objExists(splitBshp):
                cmds.setAttr(splitBshp, -1)

    # Turn on the first. Just as a default
    for blend in blends:
        cmds.setAttr("{0}.{1}".format(blend, first), 1)

        # connect all meshList input shapes to each other
        for i, target in enumerate(inputMeshList):
            print inputMeshList
            if blend != blends[0]:
                cmds.connectAttr(
                    "{0}.{1}".format(blends[0], target),
                    "{0}.{1}".format(blend, target)
                )
def LoadDelta(Args):

    global adress    
    # Open dialog window to choose directory to load delta        
    folder = cmds.fileDialog2( cap='Choose directory to load Delta', fm=3, dialogStyle=1 )
    adress = folder[0]+"\\"
    pathList_cleared = []    
    targetBlendDict = {}
    named_targetBlendDict = {}
    print "Loading Delta :)"
    # Getting .bsp files from choosen folder
    pathList = os.listdir( adress )
    if len(pathList) == 0:
        print "Folder is empty"
    for element in pathList:
        if '.bsp' in element:
            pathList_cleared.append( element )
        else:
            print 'wrong type - ', element
    pathList = pathList_cleared
    
    headObj = cmds.ls( sl=True )
    object_qnty_check(headObj)
    headObject = headObj[0]
    
    step = 25
    for i in range( len(pathList) ):
        start_time = timeit.default_timer()
        named_targetBlendDict.clear()
        path_name = open( adress+pathList[i],'r' )
        DeltaDict = pickle.load( path_name )
        targetBlendDict.clear()
        new_name = pathList[i].split('.')[0]
        cmds.duplicate( headObj[0], n=headObject+'_' + new_name )
        cmds.select( headObject+'_'+new_name )
        cmds.move( step, 0, 0 )
        step += 25
        for key in compOpacities:
            weight = compOpacities.get(key)
            x =  baseVertDict[key][0] + (DeltaDict[key][0] * weight)
            y =  baseVertDict[key][1] + (DeltaDict[key][1] * weight)
            z =  baseVertDict[key][2] + (DeltaDict[key][2] * weight)
            targetBlendDict[key] = [x, y, z]
        copy_headObj = cmds.ls( sl=True )
        for head in copy_headObj:
            for i in targetBlendDict:
                 named_targetBlendDict[head+'.vtx' + str(i)] = targetBlendDict[i]
        for head in copy_headObj:
           for vert, value in named_targetBlendDict.iteritems():
               cmds.xform( vert, t=value )
        print "Loading time - ", head, ( timeit.default_timer() - start_time )
    cmds.softSelect( sse=1 )
    names = cmds.listAttr( "blendShape1", m=True, k=True )[1:]
    fullNames = []
    for i in names:
    	fullNames.append( headObj[0] + '_' + i )
    cmds.blendShape( fullNames, headObj )
    cmds.delete( fullNames )

    return adress
Exemplo n.º 30
0
    def buildPlanes(self):
        """
        Creates buildings on new planes with probability of 1-SPAWN_CHANCE
        """
        buildings = []
        i = 0
        sidewalkHeight = self.maxHeight/160.0
        for f in self.faceList:
            if(random.random() >= self.dropRate):
                height = self.minHeight +\
                         random.random()*(self.maxHeight-self.minHeight)
                levels = random.choice(self.levelRange)

                #get the midpoint of the current face
                verts = makeVertList(cmds.xform(f, q=True, t=True))
                midpoint = getMidpoint(verts, True)

                #make a duplicate of the parent plane
                dupName = self.name + "building_"+str(i)
                dupFace = dupName + ".f[0]"
                cmds.duplicate(self.sourcePlane, name=dupName)
                cmds.xform(t=midpoint)

                #create building and add it to building list
                self.makeBuilding(dupFace, levels, height, sidewalkHeight)
                buildings += [dupName]
                i += 1
            if(not updateProgressWindow(i, len(self.faceList))):
                break
        cmds.group(buildings, name=self.name + "_buildings")
        killProgressWindow()
Exemplo n.º 31
0
    def ThreeJointSetup(self, RKarmSels):

        RKarmSels = RKarmSels
        FKJoints = cmds.duplicate(RKarmSels, name=RKarmSels[0] + "_FK")
        IKJoints = cmds.duplicate(RKarmSels, name=RKarmSels[0] + "_IK")

        for RKJoint in RKarmSels:
            cmds.select(RKJoint)
            cmds.addAttr(attributeType="float",
                         longName='IK_Weight',
                         defaultValue=1,
                         minValue=0,
                         maxValue=1,
                         hidden=False,
                         readable=True,
                         keyable=True)

            cmds.addAttr(attributeType="float",
                         longName='FK_Weight',
                         defaultValue=1,
                         minValue=0,
                         maxValue=1,
                         hidden=False,
                         readable=True,
                         keyable=True)

        # -- FK setup -- #
        def FKJointSetup(self, fKtoSetup):

            ctrlGroupArray = []
            ctrlArray = []

            for object in fKtoSetup:
                self.objectPOS = cmds.xform(object, q=1, t=1, ws=True)
                self.objectROT = cmds.xform(object, q=1, ro=1, ws=True)

                self.ctrlName = object + "_Ctrl"
                self.ourControl = cmds.circle(c=(0, 0, 0), n=self.ctrlName)
                self.ourControlGrp = cmds.group(n=(object + "_Ctrl_Grp"),
                                                em=True)
                cmds.move(self.objectPOS[0], self.objectPOS[1],
                          self.objectPOS[2], self.ourControlGrp)
                cmds.rotate(self.objectROT[0], self.objectROT[1],
                            self.objectROT[2], self.ourControlGrp)
                cmds.parent(self.ctrlName, self.ourControlGrp)
                cmds.move(0, 0, 0, self.ourControl, ls=True)
                cmds.rotate(0, 0, 0, self.ourControl)

                cmds.parentConstraint(self.ourControl, object, mo=True)
                cmds.scaleConstraint(self.ourControl, object, mo=True)
                ctrlArray.append(self.ourControl)
                ctrlGroupArray.append(self.ourControlGrp)

            cmds.parentConstraint(ctrlArray[0], ctrlGroupArray[1], mo=True)
            cmds.parentConstraint(ctrlArray[1], ctrlGroupArray[2], mo=True)

        # -- IK setup -- #

        def StretchyIkSetup(self, armSels):

            if hasattr(armSels, '__getitem__'):

                #declare variables for the various joints
                self.firstJointPos = cmds.xform(armSels[0], q=1, ws=1, t=1)
                self.secondJointPos = cmds.xform(armSels[1], q=1, ws=1, t=1)
                self.lastJointPos = cmds.xform(armSels[2], q=1, ws=1, t=1)
                self.lastJointRot = cmds.xform(armSels[2], q=1, ws=1, ro=1)
                self.secondJointPosLocal = cmds.xform(armSels[1], q=1, t=1)
                self.lastJointPosLocal = cmds.xform(armSels[2], q=1, t=1)

                #Create an IK handle on first and last Joints.
                self.tempIKName = str(armSels[0]) + "IK_Hndl"
                self.ikName = cmds.ikHandle(ee=armSels[2],
                                            sj=armSels[0],
                                            n=self.tempIKName)

                #Create locators for the first and last joint.
                self.jnt1Loc = cmds.spaceLocator(p=(0, 0, 0))
                cmds.move(self.firstJointPos[0], self.firstJointPos[1],
                          self.firstJointPos[2])
                self.jnt2Loc = cmds.spaceLocator(p=(0, 0, 0))
                cmds.move(self.lastJointPos[0], self.lastJointPos[1],
                          self.lastJointPos[2])
                self.jnt1LocShape = cmds.listRelatives(self.jnt1Loc, s=1)
                self.jnt2LocShape = cmds.listRelatives(self.jnt2Loc, s=1)

                #create a control for the IK handle, give it a stretchy attribute.
                self.ikCtrlTempName = str(armSels[0]) + "_IK_Ctrl"
                self.ikJointControl = cmds.circle(c=(0, 0, 0),
                                                  n=self.ikCtrlTempName)
                cmds.addAttr(ln="Stretchy", at="float", keyable=True)
                self.ourControlGrp = cmds.group(n=(str(armSels[0]) +
                                                   "_IK_Ctrl_Grp"),
                                                em=True)
                cmds.move(self.lastJointPos[0],
                          self.lastJointPos[1],
                          self.lastJointPos[2],
                          self.ourControlGrp,
                          ws=1)
                cmds.rotate(self.lastJointRot[0],
                            self.lastJointRot[1],
                            self.lastJointRot[2],
                            self.ourControlGrp,
                            ws=1)
                cmds.parent(self.ikCtrlTempName, self.ourControlGrp)
                cmds.move(0, 0, 0, self.ikJointControl, ls=True)
                cmds.rotate(0, 0, 0, self.ikJointControl)

                #create a "Distance between" Node for... well. getting the distance between the two nodes.
                self.distanceTest = str(
                    cmds.shadingNode('distanceBetween', asUtility=1))

                #create all of these nodes for all the different things we need to set up for the system.
                self.arm01DistanceNode = str(
                    cmds.shadingNode('multiplyDivide', asUtility=1))
                cmds.setAttr((self.arm01DistanceNode + ".input1X"),
                             self.secondJointPosLocal[0])
                self.arm02DistanceNode = str(
                    cmds.shadingNode('multiplyDivide', asUtility=1))
                cmds.setAttr((self.arm02DistanceNode + ".input1X"),
                             self.lastJointPosLocal[0])
                self.chainLengthPMA = str(
                    cmds.shadingNode('plusMinusAverage', asUtility=1))
                self.distanceScalar = str(
                    cmds.shadingNode('multiplyDivide', asUtility=1))
                cmds.setAttr((self.distanceScalar + ".operation"), 2)
                self.stretchCondition = str(
                    cmds.shadingNode('condition', asUtility=1))
                cmds.setAttr((self.stretchCondition + ".operation"), 2)
                self.colorBlendNode = str(
                    cmds.shadingNode('blendColors', asUtility=1))
                cmds.setAttr((self.colorBlendNode + ".color2R"), 1)
                self.arm01ScaleMD = str(
                    cmds.shadingNode('multiplyDivide', asUtility=1))
                self.arm02ScaleMD = str(
                    cmds.shadingNode('multiplyDivide', asUtility=1))

                #connect them attributes
                self.LinkConstraints(self.jnt1LocShape[0], "worldPosition[0]",
                                     self.distanceTest, "point1")
                self.LinkConstraints(self.jnt2LocShape[0], "worldPosition[0]",
                                     self.distanceTest, "point2")
                self.LinkConstraints(self.arm01DistanceNode, "outputX",
                                     self.chainLengthPMA, "input1D[0]")
                self.LinkConstraints(self.arm02DistanceNode, "outputX",
                                     self.chainLengthPMA, "input1D[1]")
                self.LinkConstraints(self.chainLengthPMA, "output1D",
                                     self.distanceScalar, "input2X")
                self.LinkConstraints(self.distanceTest, "distance",
                                     self.distanceScalar, "input1X")
                self.LinkConstraints(self.distanceTest, "distance",
                                     self.stretchCondition, "firstTerm")
                self.LinkConstraints(self.chainLengthPMA, "output1D",
                                     self.stretchCondition, "secondTerm")
                self.LinkConstraints(self.distanceScalar, "outputX",
                                     self.stretchCondition, "colorIfTrueR")
                self.LinkConstraints(self.stretchCondition, "outColorR",
                                     self.colorBlendNode, "color1R")
                self.LinkConstraints(self.arm01DistanceNode, "outputX",
                                     self.arm01ScaleMD, "input1X")
                self.LinkConstraints(self.arm02DistanceNode, "outputX",
                                     self.arm02ScaleMD, "input1X")
                self.LinkConstraints(self.colorBlendNode, "outputR",
                                     self.arm01ScaleMD, "input2X")
                self.LinkConstraints(self.colorBlendNode, "outputR",
                                     self.arm02ScaleMD, "input2X")
                self.LinkConstraints(self.arm01ScaleMD, "outputX", armSels[1],
                                     "translateX")
                self.LinkConstraints(self.arm02ScaleMD, "outputX", armSels[2],
                                     "translateX")
                self.LinkConstraints((str(armSels[0]) + "_IK_Ctrl"),
                                     "Stretchy", self.colorBlendNode,
                                     "blender")
                cmds.parentConstraint(self.ikCtrlTempName,
                                      self.tempIKName,
                                      mo=True)
                cmds.parentConstraint(self.ikCtrlTempName,
                                      self.jnt2Loc,
                                      mo=True)
                cmds.scaleConstraint(self.ikCtrlTempName,
                                     self.tempIKName,
                                     mo=True)
                cmds.scaleConstraint(self.ikCtrlTempName,
                                     self.jnt2Loc,
                                     mo=True)

            else:
                print("Generic Error Message")
                return

        # ---------------------- RK Initalizer ----------------
        def RKInitalizer(
            self,
            IKChain,
            FKChain,
            RKChain,
        ):
            #setup initial joint chain for RK
            i = 0
            for chain in RKChain:
                RKTempString = str(RKChain[i])
                IKTempString = str(IKChain[i])
                FKTempString = str(FKChain[i])
                print(RKTempString, IKTempString)
                constraintNumber = cmds.parentConstraint(IKChain[i],
                                                         FKChain[i],
                                                         RKChain[i],
                                                         name=str(RKChain[i]) +
                                                         "_Parent_Constraint")
                print(str(RKChain[i]) + "_Parent_Constraint")
                # LinkConstraints(self, RKChain[i], 'FK_Weight', constraintNumber,FKChain[i] + "W" +[i])
                cmds.connectAttr((str(RKTempString) + "." + 'IK_Weight'),
                                 (str(RKChain[i]) + "_Parent_Constraint" +
                                  "." + str(IKTempString) + "W0"),
                                 f=1)
                cmds.connectAttr((str(RKTempString) + "." + 'FK_Weight'),
                                 (str(RKChain[i]) + "_Parent_Constraint" +
                                  "." + str(FKTempString) + "W1"),
                                 f=1)
                i = i + 1

            # -- Function Calls -- #

        # TESTING, OK!! ----
        FKJointSetup(self, FKJoints)
        StretchyIkSetup(self, IKJoints)
        RKInitalizer(self, IKJoints, FKJoints, RKarmSels)
Exemplo n.º 32
0
def HandControls(*args): 

    cmds.select ("L_Palm_CC")
    cmds.parent (w = True)
    cmds.mirrorJoint ("L_Palm_CC", searchReplace = ("L_", "R_"), mirrorYZ = True, mirrorBehavior = True )
    
    if cmds.objExists ('L_arm_4'):
        cmds.parent ("L_Palm_CC","L_arm_4")
        cmds.parent ("R_Palm_CC","R_arm_4")
        
    cmds.delete ("HandPosition")
    
   
#Fingers Controls    

    radio = 1
    
    if cmds.objExists ('L_Thumb01_JJ'):
        for Thumb in range (1,4):  
                    
            cmds.circle (n = "L_Thumb0" + str (Thumb) + "_CC", nr = (1,0,0), r = radio)
            cmds.group (n= 'L_Thumb0' + str (Thumb) + '_CC' + 'GRP')
            cmds.pointConstraint ('L_Thumb0' + str (Thumb) + '_JJ', 'L_Thumb0' + str (Thumb) + '_CC' + 'GRP')
            cmds.orientConstraint ('L_Thumb0' + str (Thumb) + '_JJ', 'L_Thumb0' + str (Thumb) + '_CC'+ 'GRP', mo = False )
            cmds.delete ("L_Thumb0" + str (Thumb)+"_CCGRP_pointConstraint1", "L_Thumb0" + str (Thumb)+"_CCGRP_orientConstraint1")
            cmds.orientConstraint ('L_Thumb0' + str (Thumb) + '_CC', 'L_Thumb0' + str (Thumb) + '_JJ')
            cmds.setAttr('L_Thumb0' + str (Thumb) + '_CC' + "Shape.overrideEnabled", True )
            cmds.setAttr('L_Thumb0' + str (Thumb) + '_CC' + "Shape.overrideColor", 6 )
        
        cmds.parent ('L_Thumb02_CCGRP','L_Thumb01_CC')
        cmds.parent ('L_Thumb03_CCGRP','L_Thumb02_CC')



    if cmds.objExists ('L_Index01_JJ'):            
        for Index in range (1,5):  
                    
            cmds.circle (n = "L_Index0" + str (Index) + "_CC", nr = (1,0,0), r = radio)
            cmds.group (n= 'L_Index0' + str (Index) + '_CC' + 'GRP')
            cmds.pointConstraint ('L_Index0' + str (Index) + '_JJ', 'L_Index0' + str (Index) + '_CC' + 'GRP')
            cmds.orientConstraint ('L_Index0' + str (Index) + '_JJ', 'L_Index0' + str (Index) + '_CC'+ 'GRP', mo = False )
            cmds.delete ("L_Index0" + str (Index)+"_CCGRP_pointConstraint1", "L_Index0" + str (Index)+"_CCGRP_orientConstraint1")
            cmds.orientConstraint ('L_Index0' + str (Index) + '_CC', 'L_Index0' + str (Index) + '_JJ')
            cmds.setAttr('L_Index0' + str (Index) + '_CC' + "Shape.overrideEnabled", True )
            cmds.setAttr('L_Index0' + str (Index) + '_CC' + "Shape.overrideColor", 6 )
        
        cmds.parent ('L_Index02_CCGRP','L_Index01_CC')
        cmds.parent ('L_Index03_CCGRP','L_Index02_CC')
        cmds.parent ('L_Index04_CCGRP','L_Index03_CC')


    if cmds.objExists ('L_Middle01_JJ'):     
        for Middle in range (1,5):  
                    
            cmds.circle (n = "L_Middle0" + str (Middle) + "_CC", nr = (1,0,0), r = radio)
            cmds.group (n= 'L_Middle0' + str (Middle) + '_CC' + 'GRP')
            cmds.pointConstraint ('L_Middle0' + str (Middle) + '_JJ', 'L_Middle0' + str (Middle) + '_CC' + 'GRP')
            cmds.orientConstraint ('L_Middle0' + str (Middle) + '_JJ', 'L_Middle0' + str (Middle) + '_CC'+ 'GRP', mo = False )
            cmds.delete ("L_Middle0" + str (Middle)+"_CCGRP_pointConstraint1", "L_Middle0" + str (Middle)+"_CCGRP_orientConstraint1")
            cmds.orientConstraint ('L_Middle0' + str (Middle) + '_CC', 'L_Middle0' + str (Middle) + '_JJ')
            cmds.setAttr('L_Middle0' + str (Middle) + '_CC' + "Shape.overrideEnabled", True )
            cmds.setAttr('L_Middle0' + str (Middle) + '_CC' + "Shape.overrideColor", 6 )

        cmds.parent ('L_Middle02_CCGRP','L_Middle01_CC')
        cmds.parent ('L_Middle03_CCGRP','L_Middle02_CC')
        cmds.parent ('L_Middle04_CCGRP','L_Middle03_CC')


    if cmds.objExists ('L_Ring01_JJ'): 
        for Ring in range (1,5):  
                    
            cmds.circle (n = "L_Ring0" + str (Ring) + "_CC", nr = (1,0,0), r = radio)
            cmds.group (n= 'L_Ring0' + str (Ring) + '_CC' + 'GRP')
            cmds.pointConstraint ('L_Ring0' + str (Ring) + '_JJ', 'L_Ring0' + str (Ring) + '_CC' + 'GRP')
            cmds.orientConstraint ('L_Ring0' + str (Ring) + '_JJ', 'L_Ring0' + str (Ring) + '_CC'+ 'GRP', mo = False )
            cmds.delete ("L_Ring0" + str (Ring)+"_CCGRP_pointConstraint1", "L_Ring0" + str (Ring)+"_CCGRP_orientConstraint1")
            cmds.orientConstraint ('L_Ring0' + str (Ring) + '_CC', 'L_Ring0' + str (Ring) + '_JJ')
            cmds.setAttr('L_Ring0' + str (Ring) + '_CC' + "Shape.overrideEnabled", True )
            cmds.setAttr('L_Ring0' + str (Ring) + '_CC' + "Shape.overrideColor", 6 )

        cmds.parent ('L_Ring02_CCGRP','L_Ring01_CC')
        cmds.parent ('L_Ring03_CCGRP','L_Ring02_CC')
        cmds.parent ('L_Ring04_CCGRP','L_Ring03_CC')

    if cmds.objExists ('L_Pinky01_JJ'):        
        for Pinky in range (1,5):  
                    
            cmds.circle (n = "L_Pinky0" + str (Pinky) + "_CC", nr = (1,0,0), r = radio)
            cmds.group (n= 'L_Pinky0' + str (Pinky) + '_CC' + 'GRP')
            cmds.pointConstraint ('L_Pinky0' + str (Pinky) + '_JJ', 'L_Pinky0' + str (Pinky) + '_CC' + 'GRP')
            cmds.orientConstraint ('L_Pinky0' + str (Pinky) + '_JJ', 'L_Pinky0' + str (Pinky) + '_CC'+ 'GRP', mo = False )
            cmds.delete ("L_Pinky0" + str (Pinky)+"_CCGRP_pointConstraint1", "L_Pinky0" + str (Pinky)+"_CCGRP_orientConstraint1")
            cmds.orientConstraint ('L_Pinky0' + str (Pinky) + '_CC', 'L_Pinky0' + str (Pinky) + '_JJ')
            cmds.setAttr('L_Pinky0' + str (Pinky) + '_CC' + "Shape.overrideEnabled", True )
            cmds.setAttr('L_Pinky0' + str (Pinky) + '_CC' + "Shape.overrideColor", 6 )

        cmds.parent ('L_Pinky02_CCGRP','L_Pinky01_CC')
        cmds.parent ('L_Pinky03_CCGRP','L_Pinky02_CC')
        cmds.parent ('L_Pinky04_CCGRP','L_Pinky03_CC')        

    cmds.select (clear = True)
    cmds.group (n = 'L_HandControls_GRP', em = True)
    cmds.parent ('L_Thumb01_CCGRP','L_Index01_CCGRP','L_Middle01_CCGRP','L_Ring01_CCGRP','L_Pinky01_CCGRP','L_HandControls_GRP' )   
    cmds.xform ('L_HandControls_GRP', piv = (0,0,0) ,ws=True)   
    cmds.duplicate ('L_HandControls_GRP', n= 'R_HandControls_GRP')
    cmds.setAttr ("R_HandControls_GRP.scaleX", -1)
    cmds.makeIdentity ('R_HandControls_GRP',a = True, t = 1, r = 1)

    cmds.select ('R_HandControls_GRP')
    cmds.expression ( s= "searchReplaceNames \"L_\" \"R_\" \"hierarchy\";" , n = "Rename" , o = "" , ae= 0)
    cmds.delete ("Rename")
    
    
    #RightHand_CC.orient
    
    if cmds.objExists ('R_Thumb01_JJ'):            
        for RThumb in range (1,4): 
            cmds.orientConstraint ('R_Thumb0' + str (RThumb) + '_CC', 'R_Thumb0' + str (RThumb) + '_JJ', mo = True)
            cmds.setAttr('R_Thumb0' + str (RThumb) + '_CC' + "Shape.overrideColor", 13 )
            
    if cmds.objExists ('R_Index01_JJ'):            
        for RIndex in range (1,5): 
            cmds.orientConstraint ('R_Index0' + str (RIndex) + '_CC', 'R_Index0' + str (RIndex) + '_JJ', mo = True)            
            cmds.setAttr('R_Index0' + str (RIndex) + '_CC' + "Shape.overrideColor", 13 )
            
    if cmds.objExists ('R_Middle01_JJ'):            
        for RMiddle in range (1,5): 
            cmds.orientConstraint ('R_Middle0' + str (RMiddle) + '_CC', 'R_Middle0' + str (RMiddle) + '_JJ', mo = True)  
            cmds.setAttr('R_Middle0' + str (RMiddle) + '_CC' + "Shape.overrideColor", 13 )
                  
    if cmds.objExists ('R_Ring01_JJ'):            
        for RRing in range (1,5): 
            cmds.orientConstraint ('R_Ring0' + str (RRing) + '_CC', 'R_Ring0' + str (RRing) + '_JJ', mo = True) 
            cmds.setAttr('R_Ring0' + str (RRing) + '_CC' + "Shape.overrideColor", 13 )  
            
    if cmds.objExists ('R_Pinky01_JJ'):            
        for RPinky in range (1,5): 
            cmds.orientConstraint ('R_Pinky0' + str (RPinky) + '_CC', 'R_Pinky0' + str (RPinky) + '_JJ', mo = True) 
            cmds.setAttr('R_Pinky0' + str (RPinky) + '_CC' + "Shape.overrideColor", 13 )
    
    
    cmds.parent ('L_HandControls_GRP','L_Palm_CC')
    cmds.parent ('R_HandControls_GRP','R_Palm_CC')
          

    cmds.select ('L_Palm_CC', 'L_Thumb01_JJ', 'L_Thumb02_JJ', 'L_Thumb03_JJ', 'L_Index01_JJ', 'L_Index02_JJ', 'L_Index03_JJ', 'L_Index04_JJ', 'L_Middle01_JJ', 'L_Middle02_JJ', 'L_Middle03_JJ', 'L_Middle04_JJ', 'L_Ring01_JJ', 'L_Ring02_JJ', 'L_Ring03_JJ', 'L_Ring04_JJ', 'L_Pinky01_JJ', 'L_Pinky02_JJ', 'L_Pinky03_JJ', 'L_Pinky04_JJ', 'R_Palm_CC', 'R_Thumb01_JJ', 'R_Thumb02_JJ', 'R_Thumb03_JJ', 'R_Index01_JJ', 'R_Index02_JJ', 'R_Index03_JJ', 'R_Index04_JJ', 'R_Middle01_JJ', 'R_Middle02_JJ', 'R_Middle03_JJ', 'R_Middle04_JJ', 'R_Ring01_JJ', 'R_Ring02_JJ', 'R_Ring03_JJ', 'R_Ring04_JJ', 'R_Pinky01_JJ', 'R_Pinky02_JJ', 'R_Pinky03_JJ', 'R_Pinky04_JJ' )           
    cmds.sets (n= 'BindThisToHands')    

    print ('DONE')
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---------------------------------------"
Exemplo n.º 34
0
"""one ctrl for all objects selected, select ctrl first"""

import maya.cmds as cmds

sel = cmds.ls(sl=True)

origCtrl = "ctrl"
print origCtrl
cPos = cmds.xform(origCtrl, q=True, ws=True, rp=True)
cRot = cmds.xform(origCtrl, q=True, ws=True, ro=True)
ctrl = cmds.duplicate(origCtrl, n="{}Ctrl".format(obj))[0]
#grp = cmds.group(em=True, n="{}Grp".format(ctrl))
#cmds.xform(grp, ws=True, t=cPos)
#cmds.xform(grp, ws=True, ro=cRot)
    
#cmds.parent(ctrl, grp)
objPosList = []
objRotList = []

for x in range(0, len(sel)):
    obj = sel[x]    
    pos = cmds.xform(obj, q=True, ws=True, rp=True)
    rot = cmds.xform(obj, q=True, ws=True, ro=True)
    objPosList.append(pos)
    objRotList.append(rot)
    
#xPosList = [x[0] for x in objPosList]
#yPosList = [x[1] for x in objPosList]
#zPosList = [x[2] for x in objPosList]

#xRotList = [x[0] for x in objRotList]
Exemplo n.º 35
0
def get_splitValues(surface=None,
                    values=[],
                    mode='u',
                    knotIndices=[],
                    insertMin=False,
                    insertMax=False,
                    preInset=None,
                    postInset=None,
                    offset=None,
                    curvesCreate=False,
                    curvesConnect=False,
                    connectionPoints=9):
    """
    Function to split a surface
    
    :parameters:
        'curve'(None)  -- Curve to split
        
        
        curvesCreate(bool) - create new curves from the new values
        curvesConnect(bool) - whether to connect the first and last curves
        connectionPoints(int) - how many points of connection to use
    :returns
        list of values(list)
        
    hat tip: http://ewertb.soundlinker.com/mel/mel.074.php
    """
    _str_func = 'get_splitValues'
    log.debug("|{0}| >>  ".format(_str_func) + '-' * 80)
    _shape = SHAPES.get_nonintermediate(surface)
    if mode == 'u':
        l_base = get_dat(_shape, uKnots=True)['uKnots']
        minKnot = ATTR.get(_shape, 'minValueU')
        maxKnot = ATTR.get(_shape, 'maxValueU')
    else:
        l_base = get_dat(_shape, vKnots=True)['vKnots']
        minKnot = ATTR.get(_shape, 'minValueV')
        maxKnot = ATTR.get(_shape, 'maxValueV')

    l_sets = []

    log.debug("|{0}| >>  l_base: {1}".format(_str_func, l_base))

    if knotIndices:
        values = [l_base[v] for v in knotIndices]

    for i, v in enumerate(values):
        log.debug("|{0}| >>  Processing: {1} | {2}".format(_str_func, i, v) +
                  "-" * 40)
        _last = False
        if v == values[-1]:
            log.debug("|{0}| >>  last...".format(_str_func))
            _last = True

        if preInset:
            v += preInset
            log.debug("|{0}| >>  preinset: {1}".format(_str_func, v))

        _l = [v]

        _stop = False
        for knot in l_base:
            if _stop or MATH.is_float_equivalent(knot, v) == v: continue
            log.debug("|{0}| >>  checking knot: {1}".format(_str_func, knot))
            if _last:
                if knot > v:
                    _stop = True
                    _l.append(knot)

            if knot > v or knot < v:
                if _last != True and knot < values[i + 1] and knot > v:
                    _l.append(knot)
            log.debug("|{0}| >>  knot add: {1}".format(_str_func, _l))
            """
            if v == values[-1]:
                if knot < maxKnot:
                    _l.append(knot)
            elif _last != True and knot < values[i+1]:
                _l.append(knot)"""

        if _last and insertMax:
            l_add = []
            for v2 in l_base:
                if v2 > _l[-1]:
                    l_add.append(v2)
            for v2 in l_add:
                _l.append(v2)
            _l.append(maxKnot)

        if _last != True:
            _l.append(values[i + 1])

        if insertMin and i == 0:
            _l.insert(0, minKnot)

        if postInset:
            vPost = _l[-1] + postInset
            if vPost < _l[-2]:
                log.debug("|{0}| >>  alternate postInset".format(_str_func))
                vPost = _l[-2] + postInset

            log.debug("|{0}| >>  postInset: {1} | new: {2}".format(
                _str_func, _l[-1], vPost))
            if len(_l) > 1:
                if vPost > max(_l[:-1]):
                    log.debug(
                        "|{0}| >>  v post creater the max".format(_str_func))
                    _l[-1] = vPost
                else:
                    _l = _l[:-1]
            else:
                _l.append(vPost)
            """
            if _last != True:
                for v2 in _l:
                    if v2 > v:
                        _l.remove(v2)"""

        _l = LISTS.get_noDuplicates(_l)
        _l.sort()

        l_sets.append(_l)
        log.debug("|{0}| >>  result: {1} | {2} | {3}".format(
            _str_func, i, v, _l))

    l_pre = copy.copy(l_sets)
    #pprint.pprint(vars())

    if not curvesCreate:
        return l_sets

    log.debug("|{0}| >>  creating curves...".format(_str_func))

    l_newCurves = []
    d_curves = {}
    l_finalCurves = []

    def getCurve(uValue, l_newCurves):
        _crv = d_curves.get(uValue)
        if _crv: return _crv
        _crv = mc.duplicateCurve("{0}.{1}[{2}]".format(_shape, mode, uValue),
                                 ch=0,
                                 rn=0,
                                 local=0)[0]
        if offset:
            DIST.offsetShape_byVector(_crv, offset, component='cv')
        d_curves[uValue] = _crv
        log.debug("|{0}| >> created: {1} ...".format(_str_func, _crv))
        l_newCurves.append(_crv)
        return _crv

    for i, uSet in enumerate(l_sets):
        _loftCurves = [getCurve(uValue, l_newCurves) for uValue in uSet]
        """
        if len(uSet)<2:
            l_finalCurves.append(mc.duplicate(_loftCurves[0])[0])
            continue"""

        log.debug("|{0}| >> {1} | u's: {2}".format(_str_func, i, uSet))
        """
                            if i == 0 and str_start:
                                _pair = [str_start,c,l_newCurves[i+1]]
                            else:
                                _pair = [c,l_newCurves[i+1]]"""

        if len(_loftCurves) == 1:
            l_mainCurves = [mc.duplicate(_loftCurves[0])[0]]

        else:
            crvBase = mc.duplicate(_loftCurves[0])[0]
            crvEnd = mc.duplicate(_loftCurves[-1])[0]

            l_mainCurves = [crvBase, crvEnd]

            if curvesConnect:
                log.debug("|{0}| >> {1} | Making connectors".format(
                    _str_func, i))
                d_epPos = {}

                for i, crv in enumerate(_loftCurves):
                    _l = CURVES.getUSplitList(crv,
                                              connectionPoints,
                                              rebuild=True,
                                              rebuildSpans=30)[:-1]
                    for ii, p in enumerate(_l):
                        if not d_epPos.get(ii):
                            d_epPos[ii] = []
                        _l = d_epPos[ii]
                        _l.append(p)

                for k, points in d_epPos.iteritems():
                    log.debug("|{0}| >> {1} | k: {1} | points: {2}".format(
                        _str_func, k, points))
                    try:
                        crv_connect = mc.curve(d=1, ep=points, os=True)

                        #CURVES.create_fromList(posList=points)
                        l_mainCurves.append(crv_connect)
                    except Exception, err:
                        print err

        for crv in l_mainCurves[1:]:
            CORERIG.shapeParent_in_place(l_mainCurves[0], crv, False)

        #ml_shapes.append(cgmMeta.validateObjArg(l_mainCurves[0]))
        l_finalCurves.append(l_mainCurves[0])
Exemplo n.º 36
0
def retreive_all_data(filename):
    # read in the csv file
    pose_rig(filename)

    # TODO: model is posed randomly
    # need to extract other information like mesh info
    curr_data = {}
    connectionMap = {}
    anchorIndex = []
    joint_dict = {}

    curr_data['anchorPoints'] = {}
    curr_data['differentialOffset'] = {}
    curr_data['worldPos'] = {}
    curr_data['worldOffset'] = {}
    curr_data['localOffset'] = {}
    curr_data['jointWorldMatrix'] = {}
    curr_data['jointWorldQuaternion'] = {}
    curr_data['jointLocalMatrix'] = {}
    curr_data['jointLocalQuaternion'] = {}

    # Read in the connection map
    f = open(topology_path, 'r')
    reader = csv.reader(f)
    content = list(reader)
    for line in content:
        if len(line) > 1:
            connectionMap[int(line[0])] = [int(c) for c in line[1:]]
        else:
            connectionMap[int(line[0])] = []
    f.close()

    # Read in the anchor points
    f = open(anchor_path, 'r')
    reader = csv.reader(f)
    content = list(reader)
    anchorIndex = [int(line[0]) for line in content[1:]]
    f.close()

    # Read in the joint relations
    f = open(joint_path, 'r')
    reader = csv.reader(f)
    content = list(reader)
    for line in content:
        joint_dict[line[1]] = line[2]
    f.close()

    # Get the joint worldMatrix and worldQuaternion
    world_mats = {}
    for jnt in joint_dict:
        world_mat = mc.getAttr(jnt + '.worldMatrix[0]')
        world_mats[jnt] = world_mat

        wm = om.MTransformationMatrix(om.MMatrix(world_mat))
        quaternion = wm.rotation(asQuaternion=True)

        temp = [
            world_mat[0], world_mat[1], world_mat[2], world_mat[4],
            world_mat[5], world_mat[6], world_mat[8], world_mat[9],
            world_mat[10], world_mat[12], world_mat[13], world_mat[14]
        ]
        curr_data['jointWorldMatrix'][jnt] = [
            round(i, PRECISION) for i in temp
        ]

        temp = [
            quaternion[0], quaternion[1], quaternion[2], quaternion[3],
            world_mat[12], world_mat[13], world_mat[14]
        ]
        curr_data['jointWorldQuaternion'][jnt] = [
            round(i, PRECISION) for i in temp
        ]

    # Get the joint local matrix and local quaternion
    for jnt in joint_dict:
        parent = joint_dict[jnt]
        local_mat = None
        if parent:
            parent_mat = om.MMatrix(world_mats[parent])
            world_mat = om.MMatrix(world_mats[jnt])
            local_mat = world_mat * parent_mat.inverse()
        else:
            local_mat = om.MMatrix(world_mats[jnt])

        lm = om.MTransformationMatrix(local_mat)
        quaternion = lm.rotation(asQuaternion=True)

        temp = [
            local_mat[0], local_mat[1], local_mat[2], local_mat[4],
            local_mat[5], local_mat[6], local_mat[8], local_mat[9],
            local_mat[10], local_mat[12], local_mat[13], local_mat[14]
        ]
        curr_data['jointLocalMatrix'][jnt] = [
            round(i, PRECISION) for i in temp
        ]

        temp = [
            quaternion[0], quaternion[1], quaternion[2], quaternion[3],
            local_mat[12], local_mat[13], local_mat[14]
        ]
        curr_data['jointLocalQuaternion'][jnt] = [
            round(i, PRECISION) for i in temp
        ]

    # Get the mesh vertex world information throuth following steps
    meshShape, positions, curr_data['worldPos'] = get_worldPos(MESH, PRECISION)
    # Create a duplicate
    duplicate = mc.duplicate(MESH,
                             name=MESH + 'Dup',
                             upstreamNodes=False,
                             returnRootsOnly=True)[0]
    # Create deformers
    deformers = prep_mesh(MESH)
    deformer_env_dict = {}
    # shutdown all deformers except for skin clusters
    for deformer in deformers:
        dtype = mc.nodeType(deformer)
        if dtype not in SKIN_TYPES:
            deformer_env_dict[deformer] = mc.getAttr(deformer + '.envelope')
            mc.setAttr(deformer + '.envelope', 0.0)
    # Get mesh linear postions
    linear_pos, curr_data['worldOffset'] = get_worldOffset(
        MESH, PRECISION, meshShape, positions)

    # Get local offset before linear skin blending
    offsets = get_localOffset(MESH, duplicate, TEMP_BS_NODE, TEMP_TARGET)
    vertex_count = len(curr_data['worldPos'])
    for i in range(vertex_count):
        offset = offsets.get(i, [0.0, 0.0, 0.0])
        curr_data['localOffset'][i] = [
            round(data, PRECISION) for data in offset
        ]

    # Generate the differential offset data
    for i in range(len(connectionMap)):
        neighbors = connectionMap[i]
        valence = float(len(neighbors))
        new_coord = offsets.get(i, [0.0, 0.0, 0.0])
        neighbor_values = [0.0, 0.0, 0.0]
        for neighbor in neighbors:
            nb_coord = offsets.get(neighbor, [0.0, 0.0, 0.0])
            neighbor_values[0] += nb_coord[0]
            neighbor_values[1] += nb_coord[1]
            neighbor_values[2] += nb_coord[2]

        x = new_coord[0] - neighbor_values[0] / valence
        y = new_coord[1] - neighbor_values[1] / valence
        z = new_coord[2] - neighbor_values[2] / valence

        offset = [x, y, z]
        curr_data['differentialOffset'][i] = [
            round(data, PRECISION) for data in offset
        ]

    # Get the anchor points data
    for anchor in anchorIndex:
        offset = offsets.get(anchor, [0.0, 0.0, 0.0])
        curr_data['anchorPoints'][anchor] = [
            round(data, PRECISION) for data in offset
        ]

    # Restore the rig
    for deformer in deformers:
        dtype = mc.nodeType(deformer)
        if dtype not in SKIN_TYPES:
            mc.setAttr(deformer + '.envelope', deformer_env_dict[deformer])
    mc.delete(duplicate)

    retreive_data(curr_data, filename)
Exemplo n.º 37
0
def invert(base=None, corrective=None, progressBar=None, name=None):
    if not cmds.pluginInfo('cvShapeInverter.py', query=True, loaded=True):
        cmds.loadPlugin('%s/cvShapeInverter.py' % scriptTool.getScriptPath())
    # end if
    cmds.undoInfo(openChunk=True)
    if not base or not corrective:
        sel = cmds.ls(sl=True)
        if not sel or len(sel) != 2:
            cmds.undoInfo(closeChunk=True)
            raise RuntimeError, 'Select base then corrective'
        # end if
        base, corrective = sel
    # end if

    # Get points on base mesh
    basePoints = getPoints(base)
    numPoints = basePoints.length()

    # Get points on corrective mesh
    correctivePoints = getPoints(corrective)

    # Get the intermediate mesh
    shapes = cmds.listRelatives(base, children=True, shapes=True, path=True)
    for s in shapes:
        if cmds.getAttr('%s.intermediateObject' % s) and cmds.listConnections(
                '%s.worldMesh' % s, source=False):
            origMesh = s
            break
        # end if
    else:
        cmds.undoInfo(closeChunk=True)
        raise RuntimeError('No intermediate shape found for %s.' % base)
    # end for

    # Get the component offset axes
    origPoints = getPoints(origMesh)
    xPoints = OpenMaya.MPointArray(origPoints)
    yPoints = OpenMaya.MPointArray(origPoints)
    zPoints = OpenMaya.MPointArray(origPoints)

    for i in range(numPoints):
        xPoints[i].x += 1.0
        yPoints[i].y += 1.0
        zPoints[i].z += 1.0
    # end for
    setPoints(origMesh, xPoints)
    xPoints = getPoints(base)
    setPoints(origMesh, yPoints)
    yPoints = getPoints(base)
    setPoints(origMesh, zPoints)
    zPoints = getPoints(base)
    setPoints(origMesh, origPoints)

    # Create the mesh to get the inversion deformer
    if not name:
        name = '%s_inverted' % corrective
    # end if

    invertedShape = cmds.duplicate(base, name=name)[0]
    # Delete the unnessary shapes
    shapes = cmds.listRelatives(invertedShape, children=True, shapes=True)
    for s in shapes:
        if cmds.getAttr('%s.intermediateObject' % s):
            cmds.delete(s)
        # end if
    # end for
    setPoints(invertedShape, origPoints)
    # Unlock the transformation attrs
    for attr in 'trs':
        for x in 'xyz':
            cmds.setAttr('%s.%s%s' % (invertedShape, attr, x), lock=False)
        # end for
    # end for
    cmds.setAttr('%s.visibility' % invertedShape, 1)
    deformer = cmds.deformer(invertedShape, type='cvShapeInverter')[0]

    # Calculate the inversion matrices
    if progressBar:
        progressBar.setMaximum(numPoints)

    oDeformer = getMObject(deformer)
    fnDeformer = OpenMaya.MFnDependencyNode(oDeformer)
    plugMatrix = fnDeformer.findPlug('inversionMatrix', False)
    fnMatrixData = OpenMaya.MFnMatrixData()
    for i in range(numPoints):
        matrix = OpenMaya.MMatrix()
        setMatrixRow(matrix, xPoints[i] - basePoints[i], 0)
        setMatrixRow(matrix, yPoints[i] - basePoints[i], 1)
        setMatrixRow(matrix, zPoints[i] - basePoints[i], 2)
        matrix = matrix.inverse()
        oMatrix = fnMatrixData.create(matrix)

        plugMatrixElement = plugMatrix.elementByLogicalIndex(i)
        plugMatrixElement.setMObject(oMatrix)

        if progressBar:
            progressBar.setValue(i)

    if progressBar:
        progressBar.setMinimum(0)
        progressBar.setValue(0)
        progressBar.setMaximum(1)
    # end for

    # Store the base points.
    fnPointData = OpenMaya.MFnPointArrayData()
    oPointData = fnPointData.create(basePoints)
    plugDeformedPoints = fnDeformer.findPlug('deformedPoints', False)
    plugDeformedPoints.setMObject(oPointData)

    cmds.connectAttr('%s.outMesh' % getShape(corrective),
                     '%s.correctiveMesh' % deformer)
    cmds.setAttr('%s.activate' % deformer, True)

    cmds.undoInfo(closeChunk=True)

    return invertedShape
Exemplo n.º 38
0
def execute(*args):
    mySel = cmds.ls(sl=True)
    D = cmds.intFieldGrp(Density, q=True, value1=True)
    angle = cmds.intFieldGrp(Angle, q=True, value1=True)
    if D > 100: D = 100
    if D < 0: D = 0
    clonedItems = []

    startingPointItem = mySel[0]
    endingPointItem = mySel[1]
    startingPoint = cmds.objectCenter(mySel[0])
    endingPoint = cmds.objectCenter(mySel[1])

    #This ensure that the starting point is always the highest object selected
    if startingPoint[1] < endingPoint[1]:
        temp = startingPointItem
        startingPointItem = endingPointItem
        endingPointItem = temp
        startingPoint = cmds.objectCenter(startingPointItem)
        endingPoint = cmds.objectCenter(endingPointItem)

    time = 0
    distance = math.sqrt(((endingPoint[0] - startingPoint[0])**2) +
                         (endingPoint[2] - startingPoint[2])**2)
    initialSpeed = (distance / math.cos(math.radians(angle))) * math.sqrt(
        9.8 /
        (2 * distance * math.tan(math.radians(angle)) + 2 * startingPoint[1]))
    flightTime = distance / (initialSpeed * math.cos(math.radians(angle)))

    print "START HEIGHT: ", math.sin(math.radians(2 * angle))

    print "DISTANCE: ", distance

    print "SPEED: ", initialSpeed
    print "TIME: ", flightTime

    print distance

    deltaX = endingPoint[0] - startingPoint[0]
    deltaZ = endingPoint[2] - startingPoint[2]

    if deltaZ != 0:
        directionAngle = math.atan(deltaX / deltaZ)
    else:
        if deltaX > 0:
            directionAngle = (math.pi) / 2
        else:
            directionAngle = (-math.pi) / 2
    print "Angle2: ", directionAngle
    if deltaX < 0 and deltaZ < 0:
        directionAngle = directionAngle + math.pi
    elif deltaX >= 0 and deltaZ < 0:
        directionAngle = directionAngle + math.pi

    while time <= flightTime:

        newClone = cmds.duplicate(startingPointItem)
        x = startingPoint[0] + initialSpeed * math.cos(
            math.radians(angle)) * math.sin(directionAngle) * time
        y = -0.5 * 9.8 * (time**2) + initialSpeed * math.sin(
            math.radians(angle)) * time + startingPoint[1]
        z = startingPoint[2] + initialSpeed * math.cos(
            math.radians(angle)) * math.cos(directionAngle) * time
        print "time: ", time
        print "X: ", x, "Y: ", y, "Z: ", z
        cmds.move(x, y, z, newClone, absolute=True)

        time = time + 0.3
Exemplo n.º 39
0
    def processGroup(self, group, parent):
        import System.groupSelected as groupSelected
        reload(groupSelected)

        tempGroup = cmds.duplicate(group,
                                   parentOnly=True,
                                   inputConnections=True)[0]
        emptyGroup = cmds.group(empty=True)
        cmds.parent(tempGroup, emptyGroup, absolute=True)

        scaleAxis = ".scaleX"
        if self.mirrorPlane == "XZ":
            scaleAxis = ".scaleY"
        elif self.mirrorPlane == "XY":
            scaleAxis = ".scaleZ"

        cmds.setAttr(emptyGroup + scaleAxis, -1)
        instance = groupSelected.GroupSelected()
        groupSuffix = group.partition("__")[2]  #all partitions __ not more 2
        newGroup = instance.createGroupAtSpecified(groupSuffix + "_mirror",
                                                   tempGroup, parent)
        cmds.lockNode("Group__container", lock=False, lockUnpublished=False)
        cmds.delete(emptyGroup)

        for moduleLink in ((group, newGroup), (newGroup, group)):
            attributeValue = moduleLink[1] + "__"
            if self.mirrorPlane == "YZ":
                attributeValue += "X"
            elif self.mirrorPlane == "XZ":
                attributeValue += "Y"
            elif self.mirrorPlane == "XY":
                attributeValue += "Z"
            cmds.select(moduleLink[0])
            cmds.addAttr(dt="string", longName="mirrorLinks", k=False)
            cmds.setAttr(moduleLink[0] + ".mirrorLinks",
                         attributeValue,
                         type="string")

        cmds.select(clear=True)
        children = cmds.listRelatives(group, children=True)
        children = cmds.ls(children, transforms=True)  #85

        for child in children:
            if child.find("Group__") == 0:
                self.processGroup(child, newGroup)
            else:
                childNamespaces = utils.stripAllNamespaces(child)
                if childNamespaces != None and childNamespaces[
                        1] == "module_transform":
                    for module in self.moduleInfo:
                        if childNamespaces[0] == module[0]:
                            moduleContainer = module[1] + ":module_container"
                            cmds.lockNode(moduleContainer,
                                          lock=False,
                                          lockUnpublished=False)
                            moduleTransform = module[1] + ":module_transform"
                            cmds.parent(moduleTransform,
                                        newGroup,
                                        absolute=True)
                            cmds.lockNode(moduleContainer,
                                          lock=True,
                                          lockUnpublished=True)
Exemplo n.º 40
0
def freezeCombo(combo):
    """ Freeze a combo so you can change the upstream combos and shapes
    without affecting the result that you sculpted for the given combo

    In practice, this snapshots the combo, then live-reads the upstream
    shapes from the main blendshape and builds an up-to-date combo. The
    difference between these two meshes is added back into the combo shape
    """
    simplex = combo.simplex

    tweakShapeGroups = []
    fullGeos = []
    ppFilter = []

    # disconnect the controller from the operator
    with disconnected(simplex.DCC.op) as sliderCnx:

        for shapeIdx, pp in enumerate(combo.prog.pairs):
            tVal = pp.value
            freezeShape = pp.shape
            if freezeShape.isRest:
                continue

            # zero all the sliders
            cnx = sliderCnx[simplex.DCC.op]
            for a in cnx.itervalues():
                cmds.setAttr(a, 0.0)

            # set the combo values
            for pair in combo.pairs:
                cmds.setAttr(cnx[pair.slider.thing], pair.value * tVal)

            tweakPairs = []
            for shape in simplex.shapes[1:]:  # skip the restShape
                shapeVal = cmds.getAttr(shape.thing)
                if abs(shapeVal) > 0.0001:
                    tweakPairs.append((shape, shapeVal))

            # Extract this fully-on shape
            fullGeo = cmds.duplicate(
                simplex.DCC.mesh, name="{0}_Freeze".format(freezeShape.name)
            )[0]
            fullGeos.append(fullGeo)

            # Clean any orig shapes for now
            interObjs = cmds.ls(
                cmds.listRelatives(fullGeo, shapes=True), intermediateObjects=True
            )
            cmds.delete(interObjs)

            tweakShapeGroups.append(tweakPairs)
            ppFilter.append(pp)

    simplex.DCC.primeShapes(combo)

    shapePlugFmt = (
        ".inputTarget[{meshIdx}].inputTargetGroup[{shapeIdx}].inputTargetItem[6000]"
    )
    endPlugs = [
        ".inputRelativePointsTarget",
        ".inputRelativeComponentsTarget",
        ".inputPointsTarget",
        ".inputComponentsTarget",
        "",
    ]
    shapeNode = simplex.DCC.shapeNode
    helpers = []
    for geo, tweakPairs, pp in zip(fullGeos, tweakShapeGroups, ppFilter):

        # build the basicBS node
        bbs = cmds.deformer(geo, type="basicBlendShape")[0]
        helpers.append(bbs)
        idx = 0

        for shape, val in tweakPairs:
            if shape == freezeShape:
                continue
            # connect the output shape.thing to the basicBS

            # Create an empty shape. Do it like this to get the automated renaming stuff
            gDup = cmds.duplicate(geo, name="{0}_DeltaCnx".format(shape.name))[0]
            # The 4th value must be 1.0 so the blendshape auto-names
            cmds.blendShape(bbs, edit=True, target=(geo, idx, gDup, 1.0))
            cmds.blendShape(bbs, edit=True, weight=(idx, -val))
            cmds.delete(gDup)

            # Connect the shape plugs
            inPlug = bbs + shapePlugFmt
            inPlug = inPlug.format(meshIdx=0, shapeIdx=idx)

            shapeIdx = simplex.DCC.getShapeIndex(shape)
            outPlug = shapeNode + shapePlugFmt
            outPlug = outPlug.format(meshIdx=0, shapeIdx=shapeIdx)

            # Must connect the individual child plugs rather than the top
            # because otherwise the input geometry plug overrides these deltas
            for ep in endPlugs:
                cmds.connectAttr(outPlug + ep, inPlug + ep)

            idx += 1

        # Connect the basicBS back into freezeShape
        freezeShapeIdx = simplex.DCC.getShapeIndex(pp.shape)
        freezeShapeTarget = shapeNode + shapePlugFmt + ".inputGeomTarget"
        freezeShapeTarget = freezeShapeTarget.format(meshIdx=0, shapeIdx=freezeShapeIdx)
        cmds.connectAttr(geo + ".outMesh", freezeShapeTarget)

        gShapes = cmds.listRelatives(geo, shapes=True)
        if True:
            # Hide the frozen shapenode under the ctrl as an intermediate shape
            for gs in gShapes:
                cmds.setAttr(gs + ".intermediateObject", 1)
                nn = cmds.parent(gs, simplex.DCC.ctrl, shape=True, relative=True)
                helpers.extend(nn)

            # Get rid of the extra transform object
            cmds.delete(geo)
        else:
            helpers.extend(cmds.listRelatives(geo, shapes=True))

    # keep track of the shapes under the ctrl object
    combo.freezeThing = helpers
Exemplo n.º 41
0
def doSDKs(SDKnodes, target, search, replace, i, iterExec, specialIter,
           SDKResults, BWNResults, mode, createDriverAttr, drAttrSearch,
           drAttrReplace):
    ''' This is the procedure that actually performs the SDK replication
    '''

    # Declare search direction of connectionInfo command, based of tool mode.
    if mode:
        conInfoLambda = lambda node: cmds.listConnections(
            '%s.input' % node[0], d=False, s=True, p=True, scn=True)
    else:
        conInfoLambda = lambda node: cmds.listConnections(
            '%s.output' % node[0], d=True, s=False, p=True, scn=True)

    for node in SDKnodes:

        # Check what's connected to SDK nodes and see if the target nodes
        # have the same attributes as the source node, if no reults or
        # no matching attributes, continue.
        connections = conInfoLambda(node)
        if not connections or (
                not createDriverAttr and
            (not cmds.attributeQuery(
                node[1].replace(drAttrSearch, drAttrReplace),
                node=target,
                ex=True) and not cmds.attributeQuery(
                    node[1].split('[')[0].replace(drAttrSearch, drAttrReplace),
                    node=target,
                    ex=True))):
            print 'CONTINUED', node  # delete me
            continue

        # If createDriverAttr is set to True and the driver attribute
        # doesn't exist, try to create it on the new driver.
        elif (not cmds.attributeQuery(
                node[1].replace(drAttrSearch,
                                drAttrReplace), node=target, ex=True)
              and not cmds.attributeQuery(node[1].split('[')[0].replace(
                  drAttrSearch, drAttrReplace),
                                          node=target,
                                          ex=True)):
            if mode or not createDriverAttr:
                continue
            sourceDriver = cmds.listConnections('%s.input' % node[0],
                                                d=False,
                                                s=True,
                                                p=False,
                                                scn=True)[0]
            createDriverAttrFunc(sourceDriver, target, node[1].split('[')[0],
                                 drAttrSearch, drAttrReplace)

        if isinstance(connections, str):
            connections = [connections]

        # Duplicate keyframe node and mirror if asked.
        newKeyNode = cmds.duplicate(node[0])[0]
        if node[2]:
            mirrorKeys(newKeyNode)

        # Go through all the connections.
        for curNode in connections:

            # If in driver mode, check to see if node connected to keyframe
            # is a blendWeighted node.
            origBW = ''
            if not mode:
                nodeType = cmds.ls(curNode.split('.')[0], st=True)[1]
                if nodeType == 'blendWeighted':
                    origBW = curNode
                    connections2 = cmds.listConnections('%s.output' %
                                                        curNode.split('.')[0],
                                                        d=True,
                                                        s=False,
                                                        p=True,
                                                        scn=True)
                else:
                    connections2 = [curNode]
            else:
                connections2 = [curNode]

            # Connect the duplicated keyframes
            # to their respective target connections.
            for curNode2 in connections2:
                if search or not mode:
                    # regex search pattern section.
                    curRegexer = re.search(search, curNode2)
                    errorCheck = False
                    print(replace, iterExec, curNode, curNode2, mode,
                          newKeyNode, origBW)  # delete me
                    if hasattr(curRegexer, 'group'):
                        repPattern = curRegexer.group(0)
                        if repPattern:
                            (errorCheck, newConn) = \
                                connectToConn(replace, iterExec, curNode,
                                              curNode2, repPattern, mode, newKeyNode, origBW)
                        else:
                            errorCheck = True
                    else:
                        errorCheck = True

                    if errorCheck:
                        if mode:
                            print(
                                '\nFailure to find a driver for node %s '
                                'based on search criteria %s for driver node %s .'
                                % (target, search, curNode2.split('.')[0]))
                            cmds.delete(newKeyNode)
                        else:
                            print(
                                '\nFailure to find a driven for nodes %s '
                                'based on search criteria %s for driven node %s .'
                                % (target, search, curNode2.split('.')[0]))
                        continue

                elif mode:
                    cmds.connectAttr(curNode2, '%s.input' % newKeyNode, f=True)
                    newConn = curNode2

                # Connect the new SDK's to the new driver attrs.
                if mode:
                    cmds.connectAttr('%s.output' % newKeyNode,
                                     '%s.%s' % (target, node[1]),
                                     f=True)
                else:
                    cmds.connectAttr(
                        '%s.%s' %
                        (target, node[1].replace(drAttrSearch, drAttrReplace)),
                        '%s.input' % newKeyNode,
                        f=True)

                SDKResults.append(
                    'Connected Driver node %s.%s.output to '
                    'Driven node %s.%s .' % (newConn, '.'.join(
                        curNode2.split('.')[1:]), target, node[1]))
Exemplo n.º 42
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
         # 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'
             cmds.select(clear=True)
             # declare guide:
             self.guide = side + self.userGuideName + "_Guide_JointLoc1"
             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 + "_Jnt",
                                   scaleCompensate=False)
             cmds.addAttr(self.jnt,
                          longName='dpAR_joint',
                          attributeType='float',
                          keyable=False)
             utils.setJointLabel(self.jnt, s + jointLabelAdd, 18,
                                 self.userGuideName)
             # create a control:
             if not self.getHasIndirectSkin():
                 if self.curveDegree == 0:
                     self.curveDegree = 1
             # work with curve shape and rotation cases:
             indirectSkinRot = (0, 0, 0)
             if self.langDic[
                     self.langName]['c058_main'] in self.userGuideName:
                 ctrlTypeID = "id_054_SingleMain"
                 if len(sideList) > 1:
                     if self.langDic[self.langName][
                             'c041_eyebrow'] in self.userGuideName:
                         indirectSkinRot = (0, 0, -90)
                     else:
                         indirectSkinRot = (0, 0, 90)
             else:
                 ctrlTypeID = "id_029_SingleIndSkin"
                 if self.langDic[
                         self.langName]['c045_lower'] in self.userGuideName:
                     indirectSkinRot = (0, 0, 180)
                 elif self.langDic[self.langName][
                         'c043_corner'] in self.userGuideName:
                     if "00" in self.userGuideName:
                         indirectSkinRot = (0, 0, 90)
                     else:
                         indirectSkinRot = (0, 0, -90)
             self.singleCtrl = self.ctrls.cvControl(
                 ctrlTypeID,
                 side + self.userGuideName + "_Ctrl",
                 r=self.ctrlRadius,
                 d=self.curveDegree,
                 rot=indirectSkinRot)
             utils.originedFrom(objName=self.singleCtrl,
                                attrString=self.base + ";" + self.guide +
                                ";" + self.cvEndJoint + ";" +
                                self.radiusGuide)
             # position and orientation of joint and control:
             cmds.delete(
                 cmds.parentConstraint(self.guide,
                                       self.jnt,
                                       maintainOffset=False))
             cmds.delete(
                 cmds.parentConstraint(self.guide,
                                       self.singleCtrl,
                                       maintainOffset=False))
             # zeroOut controls:
             zeroOutCtrlGrp = utils.zeroOut([self.singleCtrl],
                                            offset=True)[0]
             # hide visibility attribute:
             cmds.setAttr(self.singleCtrl + '.visibility', keyable=False)
             # fixing flip mirror:
             if s == 1:
                 if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleX", -1)
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleY", -1)
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleZ", -1)
             if not self.getHasIndirectSkin():
                 cmds.addAttr(self.singleCtrl,
                              longName='scaleCompensate',
                              attributeType="bool",
                              keyable=False)
                 cmds.setAttr(self.singleCtrl + ".scaleCompensate",
                              1,
                              channelBox=True)
                 cmds.connectAttr(self.singleCtrl + ".scaleCompensate",
                                  self.jnt + ".segmentScaleCompensate",
                                  force=True)
             if self.getHasIndirectSkin():
                 # create fatherJoints in order to zeroOut the skinning joint:
                 cmds.select(clear=True)
                 jxtName = self.jnt.replace("_Jnt", "_Jxt")
                 jxt = cmds.duplicate(self.jnt, name=jxtName)[0]
                 utils.clearDpArAttr([jxt])
                 cmds.makeIdentity(self.jnt, apply=True, jointOrient=False)
                 cmds.parent(self.jnt, jxt)
                 attrList = [
                     'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'
                 ]
                 for attr in attrList:
                     cmds.connectAttr(self.singleCtrl + '.' + attr,
                                      self.jnt + '.' + attr)
                 if self.getHasHolder():
                     cmds.delete(self.singleCtrl + "0Shape", shape=True)
                     self.singleCtrl = cmds.rename(
                         self.singleCtrl, self.singleCtrl + "_" +
                         self.langDic[self.langName]['c046_holder'] +
                         "_Grp")
                     self.ctrls.setLockHide([self.singleCtrl], [
                         'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy',
                         'sz'
                     ])
                     self.jnt = cmds.rename(
                         self.jnt,
                         self.jnt.replace(
                             "_Jnt", "_" +
                             self.langDic[self.langName]['c046_holder'] +
                             "_Jis"))
                     self.ctrls.setLockHide([self.jnt], [
                         'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy',
                         'sz'
                     ], True, True)
                 else:
                     if self.getHasSDKLocator():
                         if not self.langDic[self.langName][
                                 'c058_main'] in self.userGuideName:
                             # this one will be used to receive inputs from sdk locator:
                             sdkJisName = self.jnt.replace(
                                 "_Jnt", "_SDK_Jis")
                             sdkJis = cmds.duplicate(self.jnt,
                                                     name=sdkJisName)[0]
                             # sdk locator:
                             sdkLoc = cmds.spaceLocator(
                                 name=sdkJis.replace("_Jis", "_Loc"))[0]
                             sdkLocGrp = cmds.group(sdkLoc,
                                                    name=sdkLoc + "_Grp")
                             cmds.delete(
                                 cmds.parentConstraint(
                                     self.singleCtrl,
                                     sdkLocGrp,
                                     maintainOffset=False))
                             cmds.parent(sdkLocGrp,
                                         self.singleCtrl,
                                         relative=True)
                             sdkLocMD = cmds.createNode("multiplyDivide",
                                                        name=sdkLoc + "_MD")
                             cmds.addAttr(sdkLoc,
                                          longName="intensityX",
                                          attributeType="float",
                                          defaultValue=-1,
                                          keyable=False)
                             cmds.addAttr(sdkLoc,
                                          longName="intensityY",
                                          attributeType="float",
                                          defaultValue=-1,
                                          keyable=False)
                             cmds.addAttr(sdkLoc,
                                          longName="intensityZ",
                                          attributeType="float",
                                          defaultValue=-1,
                                          keyable=False)
                             cmds.connectAttr(sdkLoc + ".translateX",
                                              sdkLocMD + ".input1X",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".translateY",
                                              sdkLocMD + ".input1Y",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".translateZ",
                                              sdkLocMD + ".input1Z",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".intensityX",
                                              sdkLocMD + ".input2X",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".intensityY",
                                              sdkLocMD + ".input2Y",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".intensityZ",
                                              sdkLocMD + ".input2Z",
                                              force=True)
                             cmds.connectAttr(sdkLocMD + ".outputX",
                                              sdkLocGrp + ".translateX",
                                              force=True)
                             cmds.connectAttr(sdkLocMD + ".outputY",
                                              sdkLocGrp + ".translateY",
                                              force=True)
                             cmds.connectAttr(sdkLocMD + ".outputZ",
                                              sdkLocGrp + ".translateZ",
                                              force=True)
                             cmds.addAttr(self.singleCtrl,
                                          longName="displayLocator",
                                          attributeType="bool",
                                          keyable=False)
                             cmds.setAttr(self.singleCtrl +
                                          ".displayLocator",
                                          0,
                                          channelBox=True)
                             cmds.connectAttr(self.singleCtrl +
                                              ".displayLocator",
                                              sdkLoc + ".visibility",
                                              force=True)
                             cmds.setAttr(sdkLoc + ".visibility", lock=True)
                             for attr in attrList:
                                 cmds.connectAttr(sdkLoc + '.' + attr,
                                                  sdkJis + '.' + attr)
                             cmds.setAttr(sdkLocGrp + ".rotateX", 0)
                             cmds.setAttr(sdkLocGrp + ".rotateY", 0)
                             cmds.setAttr(sdkLocGrp + ".rotateZ", 0)
                     # rename indirectSkinning joint from Jnt to Jis:
                     self.jnt = cmds.rename(
                         self.jnt, self.jnt.replace("_Jnt", "_Jis"))
                 # fix mirror issue:
                 if s == 1:
                     if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                         cmds.setAttr(jxt + ".scaleX", -1)
                         cmds.setAttr(jxt + ".scaleY", -1)
                         cmds.setAttr(jxt + ".scaleZ", -1)
             else:  # like a fkLine
                 # create parentConstraint from ctrl to jnt:
                 cmds.parentConstraint(self.singleCtrl,
                                       self.jnt,
                                       maintainOffset=False,
                                       name=self.jnt + "_PaC")
                 # create scaleConstraint from ctrl to jnt:
                 cmds.scaleConstraint(self.singleCtrl,
                                      self.jnt,
                                      maintainOffset=True,
                                      name=self.jnt + "_ScC")
             # create end joint:
             cmds.select(self.jnt)
             self.endJoint = cmds.joint(name=side + self.userGuideName +
                                        "_JEnd",
                                        radius=0.5)
             cmds.delete(
                 cmds.parentConstraint(self.cvEndJoint,
                                       self.endJoint,
                                       maintainOffset=False))
             self.mainJisList.append(self.jnt)
             # create a masterModuleGrp to be checked if this rig exists:
             self.toCtrlHookGrp = cmds.group(
                 side + self.userGuideName + "_Ctrl_Zero_0_Grp",
                 name=side + self.userGuideName + "_Control_Grp")
             if self.getHasIndirectSkin():
                 locScale = cmds.spaceLocator(
                     name=side + self.userGuideName +
                     "_Scalable_DO_NOT_DELETE_PLEASE_Loc")[0]
                 cmds.setAttr(locScale + ".visibility", 0)
                 self.toScalableHookGrp = cmds.group(
                     locScale,
                     name=side + self.userGuideName + "_IndirectSkin_Grp")
                 jxtGrp = cmds.group(side + self.userGuideName + "_Jxt",
                                     name=side + self.userGuideName +
                                     "_Joint_Grp")
                 self.toStaticHookGrp = cmds.group(
                     jxtGrp,
                     self.toScalableHookGrp,
                     self.toCtrlHookGrp,
                     name=side + self.userGuideName + "_Grp")
             else:
                 self.toScalableHookGrp = cmds.group(
                     side + self.userGuideName + "_Jnt",
                     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 or scalable 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")
             self.aStaticGrpList.append(self.toStaticHookGrp)
             self.aCtrlGrpList.append(self.toCtrlHookGrp)
             # 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)
         # check mirror indirectSkin bug in Maya2018:
         if (int(cmds.about(version=True)[:4]) == 2018):
             if self.mirrorAxis != 'off':
                 if self.getHasIndirectSkin():
                     meshList = cmds.ls(selection=False, type="mesh")
                     if meshList:
                         self.detectedBug = True
         # finalize this rig:
         self.integratingInfo()
         cmds.select(clear=True)
     # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
     self.deleteModule()
Exemplo n.º 43
0
def copySDK(curAttrs=[],
            mirrorAttrs=[],
            source='',
            targets=[],
            search='',
            replace='',
            specialIter=[],
            sort=False,
            mode='driven',
            drAttrSearch='',
            drAttrReplace='',
            createDriverAttr=False):
    '''This definition is used to copy SDK setups from one node
to another node/s in Maya.  With no declarations, the script works by getting
the selection list. The first selected object is the source, everything else
is a target. The script will copy SDKs from the source and replicate it
on the targets.   SDKs will be linked to the original source driver by default.


Node and attribute options

curAttrs    - string or string list     - is for explicitly declaring
                        which attributes to copy SDKs from.  If you
                        don't declare it, the script will search for SDKs
                        on all keyable attributes of the source.

mirrorAttrs - string or string list     - is to tell the script
                        which attributes on the source object will receive
                        a negative value in their keyframes.

source      - string                    - is to explicitly declare
                        the source node to copy.  If this is declared, targets
                        must also be declared. If not declared, the selection
                        list is used and the first selected object
                        is the source.
                                        - if mode is set to driven, source
                        represents the source driven node, when mode is set
                        to driver, source represents the source driver node.

targets     - string or string list     - is to explicitly declare target nodes
                        to apply SDKs to.  If this is declared, source
                        must also be declared. If not declared, the selection
                        list is used and all other objects other than the first
                        comprise the targets list.
                                        - if mode is set to driven, targets
                        represents the destination driven node/s, when mode
                        is set to driver, targets represents the destination
                        driver node/s.



String search options for driver nodes:

search      - string                    - when mode is set to Driven, is used
                        for pattern searching in Driver names.  search
                        and replace both have to be declared. If not declared,
                        the SDK's are connected to the original driver node
                        attributes.  This attribute accepts regex
                        search strings.
                                        - when mode is set to Driver, this is
                        used instead to search for Driven object names. search
                        and replace MUST be declared in case of Driver-centric
                        operations.

replace     - string                    - when mode is set to Driven, is used
                        for pattern searching in Driver names, to look for
                        alternate Driver nodes. This provides the
                        replace string to use when looking for Driver nodes.
                        The replace string can use the special %s character
                        to provide more flexibility with choosing different
                        Drivers for multiple Driven nodes.
                                        - when mode is set to Driver, this
                        is used instead to search for Driven object names.
                        search and replace MUST be declared in case of
                        Driver-centric operations.

specialIter - int or string list or list of lists  - is used when you want to
                        provide a list or an iteratable object to use when you
                        want more flexibility in naming your driver object.
                        Your replace variable must contain a replace string
                        with %s, and that will get swapped by what you
                        enter here.
                                        - You can use a single list
                        ['a', 'b', 'c'], lists within lists for multiple %s's
                        [['a', 'b', 'c'], [1, 2, 3]], or python techniques
                        such as range e.g., range(0,12).
                                        - The only rule is that the lists
                        have to be as long as the number of targets.

sort        - boolean                   - Sort the target list alphabetically.
                        Helps to reorganize the targets list if you're using
                        the specialIter function.

mode        - string 'driver', 'driven' or 'guess' - Decides whether the script
                        operates via selecting a driven node, or a driver node.
                        Default is set to driven, meaning you have to select
                        the driven object you want to mirror over as your
                        first selection.  Options are either 'driver',
                        'driven', or 'guess' (if set to guess, will find
                        whether it has more outgoing or incomming
                        sdk keyframes), and the default is driven.
                                        - In driven mode, script wil find the
                        original driver from the driven node and seek out
                        alternate driver names via the search and replace
                        variables if declared, else it will use
                        the original driver/s.
                                        - In driver mode, script will seek out
                        all driven nodes and search for the alternate driven
                        node names based off the search and replace variables.
                        In driver mode, search and replace declaration
                        is required.

drAttrSearch  - string                  - If declared, search for this string
                        component in a source driver attribute, for
                        the purpose of replacing this string in
                        a target driver attribute.

drAttrReplace - string                  - If declared, use this string
                        to replace a found attrSearch component in a source
                        driver attr when looking for a target driver attr.

createDriverAttr - boolean              - Create the driver attribute on
                        a found target node if it did not already exist,
                        Default is False.  This only works in 'driver' mode.
'''
    # Make sure all variables are correct
    if not source.strip() or not targets:
        curlist = cmds.ls(sl=True, ap=True)
        if not curlist or len(curlist) < 2:
            print('\nPlease select at least two objects.')
            return 1
        source = curlist[0]
        targets = curlist[1:]
    elif isinstance(targets, str) and targets.strip():
        targets = [targets]
    if sort:
        targets.sort()
    if curAttrs:

        if isinstance(curAttrs, str) and curAttrs.strip():
            curAttrs = [curAttrs]

        attrs = [
            cmds.attributeQuery(x, node=source, ln=True) for x in curAttrs
            if cmds.attributeQuery(x, node=source, ex=True)
        ]
        if not attrs:
            print('Specified attributes %s, do not exist on driver %s .' %
                  (', '.join(attrs), source))
            return 1
    else:
        attrs = cmds.listAttr(source, k=True)

    if mirrorAttrs:
        if isinstance(mirrorAttrs, str):
            mirrorAttrs = [mirrorAttrs]
        tempMirrorAttrs = []
        for attr in mirrorAttrs:
            if not cmds.attributeQuery(attr, node=source, ex=True):
                continue
            tempMirrorAttrs.append(
                cmds.attributeQuery(attr, node=source, ln=True))
        tempMirrorAttrs = list(set(tempMirrorAttrs))
        if tempMirrorAttrs:
            mirrorAttrs = tempMirrorAttrs
        else:
            print(
                'Specified attributes to be mirrored %s, do not exist '
                'on source node %s .' % (', '.join(mirrorAttrs), source))
            mirrorAttrs = []

    if mode.strip().lower() == 'driven':
        mode = True
    elif mode.strip().lower() == 'driver':
        mode = False
    elif mode.lower() == 'guess':
        driverNodes = []
        drivenNodes = []

        drivenNodes, blendWeightedNodes = \
            findSDKNodes(mirrorAttrs, source, attrs, True)
        if blendWeightedNodes:
            for node in blendWeightedNodes:
                SDKN2, SKN, ON = searchBWNodes(node)
                if SDKN2:
                    a = set(drivenNodes + SDKN2)
                    drivenNodes = list(a)
        driverNodes, blendWeightedNodes = \
            findSDKNodes(mirrorAttrs, source, attrs, False)

        if len(drivenNodes) >= len(driverNodes):
            mode = True
        else:
            mode = False
    else:
        print('\nUnrecognized mode argument: "' + str(mode) +
              '", use either "driver", "driven", or "guess".')
        return 1

    # Determine special iteration parameters if there is a %s in the replace
    # variable. Used for complex Driver name searching, if each of your targets
    # has a different driver object.
    SDKResults = []
    BWNResults = []
    iterExec = None
    if (not search or not replace) and mode:
        search = None
        replace = None
    elif (not search or not replace) and not mode:
        print(
            '\nPlease "declare" search and "replace" variables '
            'when in driver mode.')
        return 1
    elif replace.count('%s') and not specialIter:
        print(
            '\nWhen using the "%s" character, you must declare '
            'a specialIter list')
        return 1
    elif replace.count('%s'):
        if (isinstance(specialIter[0], list)
                or isinstance(specialIter[0], tuple)):
            numArgs = len(specialIter)
            iterExec = 'feeder = ('
            iterScratch = []
            for x in range(0, numArgs):
                if len(specialIter[x]) != len(targets):
                    print('\nspecialIter item ' + str(x) + ' length (' +
                          str(len(specialIter[x])) +
                          ') must be the same as target'
                          ' length (' + str(len(targets)) + ') .')
                    return 1
                iterScratch.append('specialIter[%s][i]' % str(x))

            iterExec += ', '.join(iterScratch) + ' )'
        else:
            if len(specialIter) != len(targets):
                print('\nspecialIter length (' + str(len(specialIter)) +
                      ') must be the same as target length (' +
                      str(len(targets)) + ') .')
                return 1
            iterExec = 'feeder = specialIter[i]'

    # Acquire SDK and blendweighted nodes from source
    SDKnodes, blendWeightedNodes = \
        findSDKNodes(mirrorAttrs, source, attrs, mode)

    # Go through all the targets and mirror SDK nodes and
    # blendWeighted nodes with SDK from source.
    i = 0
    for target in targets:
        if SDKnodes:
            doSDKs(SDKnodes, target, search, replace, i, iterExec, specialIter,
                   SDKResults, BWNResults, mode, createDriverAttr,
                   drAttrSearch, drAttrReplace)

        if blendWeightedNodes and mode:
            for node in blendWeightedNodes:

                SDKnodes2, SKnodes, otherNodes = searchBWNodes(node)

                if SDKnodes2:
                    newBlendNode = cmds.duplicate(node[0])[0]
                    doSDKs(SDKnodes2, newBlendNode, search, replace, i,
                           iterExec, specialIter, SDKResults, BWNResults, True,
                           createDriverAttr, drAttrSearch, drAttrReplace)
                    if SKnodes:
                        for node2 in SKnodes:
                            newKeyNode = cmds.duplicate(node2[0])[0]
                            if node2[2]:
                                mirrorKeys(newKeyNode)
                            cmds.connectAttr('%s.output' % newKeyNode,
                                             '%s.%s' %
                                             (newBlendNode, node2[1]),
                                             f=True)
                    cmds.connectAttr('%s.output' % newBlendNode,
                                     '%s.%s' % (target, node[1]),
                                     f=True)
                    BWNResults.append('Connected Blend Weighted node '
                                      '%s.output to Driven node %s.%s' %
                                      (newBlendNode, target, node[1]))
                else:
                    print('\nNo SDK nodes connected to blendWeighted node ' +
                          node[0] + ', skipping...')
        i += 1

    return 0
Exemplo n.º 44
0
def createWheel():
    # query UI choice
    createTire = cmds.radioButtonGrp('wheelTire', q=True, sl=True)
    createHub = cmds.radioButtonGrp('wheelHub', q=True, sl=True)

    # create a tire
    if (createTire == 1):
        # name
        nsTmp = "Tire" + str(rnd.randint(1000, 9999))
        cmds.select(clear=True)
        cmds.namespace(add=nsTmp)
        cmds.namespace(set=nsTmp)
        # query colour from UI
        rgb = cmds.colorSliderGrp('tireColour', q=True, rgbValue=True)
        # create cylinder for the base
        tire = cmds.polyCylinder(r=3.5, h=3.5, sx=36)
        # add a smaller sphere to round up the tire
        tmp = cmds.polySphere(r=3.35, sy=15, sx=36)
        cmds.scale(1.1, scaleY=True)
        # remove non intersecting parts
        tire = cmds.polyCBoolOp(tire, tmp, op=3, ch=False)
        # Add texture:
        # create cylinder as the base for texture at 1 side
        texture1 = cmds.polyCylinder(r=2.8, h=1.75, sx=36)
        # move it up
        cmds.move(1.75 / 2, moveY=True, a=True)
        # in range of subdivisions
        for i in range(35):
            #for all even numbers
            if (i % 2 == 0):
                cmds.select(texture1[0] + ".f[" + str(i) + "]")
                # local translate on Z and scale x
                cmds.polyExtrudeFacet(ltz=1, lsx=1.35)
        # duplicate texture 1 for the 2nd side
        texture2 = cmds.duplicate(texture1)
        cmds.select(texture2)
        cmds.move(-1.75 / 2, moveY=True, a=True)
        cmds.rotate(10, rotateY=True, a=True)
        # combine textures 1 and 2
        texture = cmds.polyCBoolOp(texture1, texture2, op=1, ch=False)
        # add a smaller sphere to round up the texture
        tmp = cmds.polySphere(r=3.7, sy=13, sx=36)
        # remove non intersecting parts
        texture = cmds.polyCBoolOp(texture, tmp, op=3, ch=False)
        cmds.polyMergeVertex(d=0.05, ch=False)
        # create another cylinder for the hole
        tmp = cmds.polyCylinder(r=2, h=3.5)
        # remove it
        tire = cmds.polyCBoolOp(tire, tmp, op=2, ch=False)
        tmp = cmds.polyCylinder(r=2, h=3.5)
        texture = cmds.polyCBoolOp(texture, tmp, op=2, ch=False)

        # add material
        myShader = cmds.shadingNode('lambert', asShader=True, name="blckMat")
        cmds.setAttr(nsTmp + ":blckMat.color",
                     rgb[0],
                     rgb[1],
                     rgb[2],
                     type='double3')
        cmds.polyUnite((nsTmp + ":*"), n=nsTmp, ch=False)
        cmds.rotate(90, rotateX=True, a=True)
        cmds.rotate(90, rotateY=True, a=True)
        cmds.move(3.466, moveY=True, a=True)

        cmds.delete(ch=True)

        cmds.hyperShade(assign=(nsTmp + ":blckMat"))
        cmds.namespace(removeNamespace=":" + nsTmp,
                       mergeNamespaceWithParent=True)

    # create a hub
    if (createHub == 1):
        # name
        nsTmp = "Hub" + str(rnd.randint(1000, 9999))
        cmds.select(clear=True)
        cmds.namespace(add=nsTmp)
        cmds.namespace(set=nsTmp)
        # query colour from UI
        rgb = cmds.colorSliderGrp('hubColour', q=True, rgbValue=True)

        # base
        hub = cmds.polyCylinder(r=2.1, h=2.8)
        # outline
        tmp = cmds.polyCylinder(r=1.6, h=2.8)
        hub = cmds.polyCBoolOp(hub, tmp, op=2, ch=False)
        # inner part of the hub
        hubIn = cmds.polyCylinder(r=1.6, h=1.8)
        # center
        hubCenter = cmds.polyCylinder(r=0.3, h=2.4)
        hubIn = cmds.polyCBoolOp(hubIn, hubCenter, op=2, ch=False)

        # decor parts
        d1 = cmds.polyCylinder(r=0.4, h=2.8)
        cmds.move(-0.85, moveX=True, a=True)
        cmds.move(-0.03, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d1, op=1, ch=False)
        # subtract smaller cylinder inside
        d1c = cmds.polyCylinder(r=0.3, h=2.9)
        cmds.move(-0.85, moveX=True, a=True)
        cmds.move(-0.03, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d1c, op=2, ch=False)

        d3 = cmds.polyCylinder(r=0.4, h=2.8)
        cmds.move(-0.422, moveX=True, a=True)
        cmds.move(0.648, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d3, op=1, ch=False)
        # subtract smaller cylinder inside
        d3c = cmds.polyCylinder(r=0.3, h=2.9)
        cmds.move(-0.422, moveX=True, a=True)
        cmds.move(0.648, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d3c, op=2, ch=False)

        d4 = cmds.polyCylinder(r=0.4, h=2.8)
        cmds.move(0.416, moveX=True, a=True)
        cmds.move(0.627, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d4, op=1, ch=False)
        # subtract smaller cylinder inside
        d4c = cmds.polyCylinder(r=0.3, h=2.9)
        cmds.move(0.416, moveX=True, a=True)
        cmds.move(0.627, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d4c, op=2, ch=False)

        d5 = cmds.polyCylinder(r=0.4, h=2.8)
        cmds.move(0.835, moveX=True, a=True)
        cmds.move(-0.049, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d5, op=1, ch=False)
        # subtract smaller cylinder inside
        d5c = cmds.polyCylinder(r=0.3, h=2.9)
        cmds.move(0.835, moveX=True, a=True)
        cmds.move(-0.049, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d5c, op=2, ch=False)

        d6 = cmds.polyCylinder(r=0.4, h=2.8)
        cmds.move(0.431, moveX=True, a=True)
        cmds.move(-0.692, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d6, op=1, ch=False)
        # subtract smaller cylinder inside
        d6c = cmds.polyCylinder(r=0.3, h=2.9)
        cmds.move(0.431, moveX=True, a=True)
        cmds.move(-0.692, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d6c, op=2, ch=False)

        d7 = cmds.polyCylinder(r=0.4, h=2.8)
        cmds.move(-0.384, moveX=True, a=True)
        cmds.move(-0.734, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d7, op=1, ch=False)
        # subtract smaller cylinder inside
        d7c = cmds.polyCylinder(r=0.3, h=2.9)
        cmds.move(-0.384, moveX=True, a=True)
        cmds.move(-0.734, moveZ=True, a=True)
        hubIn = cmds.polyCBoolOp(hubIn, d7c, op=2, ch=False)

        # add material
        myShader = cmds.shadingNode('lambert', asShader=True, name="blckMat")
        cmds.setAttr(nsTmp + ":blckMat.color",
                     rgb[0],
                     rgb[1],
                     rgb[2],
                     type='double3')

        cmds.polyUnite((nsTmp + ":*"), n=nsTmp, ch=False)
        cmds.rotate(90, rotateX=True, a=True)
        cmds.rotate(90, rotateY=True, a=True)
        cmds.move(3.466, moveY=True, a=True)
        cmds.delete(ch=True)

        cmds.hyperShade(assign=(nsTmp + ":blckMat"))
        cmds.namespace(removeNamespace=":" + nsTmp,
                       mergeNamespaceWithParent=True)
Exemplo n.º 45
0
	def setUpNcloth(cls, *args):
		"""
		Main method.
		"""

		solverName = cmds.textFieldGrp(cls.widgets['solverNameTxtFldGrp'], q=True, text=True)
		nClothGeoList = cmds.textScrollList(cls.widgets['nClothGeoTxtScrLs'], q=True, allItems=True)
		colliderGeoList = cmds.textScrollList(cls.widgets['colliderGeoTxtScrLs'], q=True, allItems=True)

		# Create new solver
		if not cmds.objExists(solverName + '_nucleus'):
			solver = cmds.createNode('nucleus', n=solverName + '_nucleus')
			cmds.setAttr('%s.subSteps' % solver, 10)
			cmds.setAttr('%s.maxCollisionIterations' % solver, 10)
			cmds.setAttr('%s.timeScale' % solver, 1.0)
			cmds.setAttr('%s.spaceScale' % solver, 0.01)
			cmds.setAttr('%s.visibility' % solver, 0)
			cmds.connectAttr('time1.outTime', solver + '.currentTime', f=True)
		else:
			solver = solverName + '_nucleus'

		# Clean up outliner
		if not cmds.objExists(solverName + '_dyn_grp'):
			allGrp = cmds.createNode('transform', n=solverName + '_dyn_grp')
		else:
			allGrp = solverName + '_dyn_grp'

		if not cmds.objExists(solverName + '_collider_grp'):
			colliderGrp = cmds.createNode('transform', n=solverName + '_collider_grp')
		else:
			colliderGrp = solverName + '_collider_grp'

		try:
			cmds.parent(solver, colliderGrp, allGrp)
		except:
			pass

		# Collider set up
		if colliderGeoList:
			for colliderGeo in colliderGeoList:
				cmds.select(colliderGeo, r=True)
				nRgdShp = mel.eval('makeCollideNCloth;')
				nRgdTrsf = cmds.listRelatives(nRgdShp, p=True)[0]
				newNRgdName = cmds.rename(nRgdTrsf, colliderGeo + '_nRigid')

				# Get assigned solver to cloth
				newNRgdShp = cmds.listRelatives(newNRgdName, s=True)
				solverAssignedRgdShp = cmds.listConnections(newNRgdShp, s=False, d=True)

				cmds.select(newNRgdName, r=True)
				mel.eval('assignNSolver "%s";' % solver)

				# If auto created solver exists delete
				# if not solverAssignedRgdShp == solver:
				# 	cmds.delete(solverAssignedRgdShp)

				cmds.parent(newNRgdName, colliderGeo, colliderGrp)

			# Connect time node outTime attribute to solver currentTime attribute
			newNRgdShp = cmds.listRelatives(newNRgdName, s=True)[0]
			timeNode = cmds.listConnections('%s.currentTime' % newNRgdShp)[0]
			try:
				cmds.connectAttr('%s.outTime' % timeNode, '%s.currentTime' % solver)
			except:
				pass

		if nClothGeoList:
			for clothGeo in nClothGeoList:
				# Duplicate geo for 'Attract to Matching Mesh' nConstraint
				clothName = clothGeo.split('_dyn')[0]
				goalGeo = cmds.duplicate(clothGeo, n=clothName + '_goal_geo')[0]

				# Clean up gaolGeo and transfer skin from clothGeo
				cmds.select(goalGeo, r=True)
				tak_cleanUpModel.delHis()
				tak_cleanUpModel.delInterMediObj()
				cmds.select(clothGeo, goalGeo, r=True)
				tak_misc.TransSkinWeights()

				# Create nCloth
				cmds.select(clothGeo, r=True)
				origNclothShp = mel.eval('createNCloth 0;')
				nClothTrsf = cmds.listRelatives(origNclothShp, p=True)[0]
				newClothName = cmds.rename(nClothTrsf, clothName + '_nCloth')

				# Get assigned solver to cloth
				nClothShp = cmds.ls(cmds.listHistory(newClothName), type='nCloth')
				solverAssignedNcloth = list(set(cmds.ls(cmds.listConnections(nClothShp), type='nucleus')))[0]

				# Change solver
				cmds.select(newClothName, r=True)
				mel.eval('assignNSolver "%s";' % solver)

				# If auto created solver exists delete
				if not solverAssignedNcloth == solver:
					cmds.delete(solverAssignedNcloth)

				# Attract to Matching Mesh nConstraint
				cmds.select(goalGeo, clothGeo, r=True)
				goalCnstNodes = mel.eval('createNConstraint match 0;')
				cmds.setAttr('%s.constraintMethod' % goalCnstNodes[1], 0)

				goalCnstNRgdPrnt = cmds.listRelatives(goalCnstNodes[0], p=True)[0]
				goalCnstNRgd = cmds.rename(goalCnstNRgdPrnt, clothName + '_goal_cnst_nRigid')

				goalCnstDynCnstPrnt = cmds.listRelatives(goalCnstNodes[1], p=True)[0]
				goalCnstDynCnst = cmds.rename(goalCnstDynCnstPrnt, clothName + '_goal_dynCnst')

				# Clean up outliner
				clothGrp = cmds.createNode('transform', n=clothName + '_nCloth_grp')
				nCnstGrp = cmds.createNode('transform', n=clothName + '_nCnst_grp')
				cmds.setAttr('%s.visibility' % nCnstGrp, 0)

				cmds.parent(clothGeo, newClothName, clothGrp)
				cmds.parent(goalGeo, goalCnstNRgd, goalCnstDynCnst, nCnstGrp)
				cmds.parent(nCnstGrp, clothGrp)
				cmds.parent(clothGrp, allGrp)
Exemplo n.º 46
0
def connectToConn(replace, iterExec, curNode, curNode2, repPattern, mode,
                  newKeyNode, origBW):
    ''' Connect the newKeyNode basked on she search/replace
    parameters specified.
    '''

    errorCheck = False
    if replace.count('%s'):
        currentRep = replace
        exec(iterExec) in locals()
        currentRep = currentRep % feeder
        newConn = curNode2.split('.')[0].replace(repPattern, currentRep)
    else:
        newConn = curNode2.split('.')[0].replace(repPattern, replace)

    if cmds.objExists(newConn) and \
            cmds.attributeQuery(
                '.'.join(curNode2.split('.')[1:]), node=newConn, ex=True) and \
            mode:
        cmds.connectAttr('%s.%s' %
                         (newConn, '.'.join(curNode2.split('.')[1:])),
                         '%s.input' % newKeyNode,
                         f=True)

    # In driver mode, check for blendWeighted nodes. If the target
    # has a blendWeighted node, check to see if it has the same number
    # of input multi attrs, otherwise make a new one.
    elif cmds.objExists(newConn) and (
                cmds.attributeQuery(
                    '.'.join(curNode2.split('.')[1:]), node=newConn, ex=True) or
                cmds.attributeQuery(
                    curNode2.split('.')[1].split('[')[0], node=newConn, ex=True)) \
            and not mode:

        targetCon = cmds.listConnections(
            '%s.%s' % (newConn, '.'.join(curNode2.split('.')[1:])),
            s=True,
            d=False,
            p=True,
            scn=True)
        makeNewBW = False
        if targetCon:
            nodeType = cmds.ls(targetCon[0].split('.')[0], st=True)[1]
            if nodeType == 'blendWeighted':
                targetBWInSize = len(
                    cmds.listAttr('%s.input' % targetCon[0].split('.')[0],
                                  multi=True))
                origBWInSize = len(
                    cmds.listAttr('%s.input' % origBW.split('.')[0],
                                  multi=True))
                if targetBWInSize == origBWInSize:
                    cmds.connectAttr('%s.output' % newKeyNode,
                                     '%s.%s' %
                                     (targetCon[0].split('.')[0], '.'.join(
                                         curNode.split('.')[1:])),
                                     f=True)
                else:
                    makeNewBW = True
            else:
                makeNewBW = True
        else:
            makeNewBW = True

        if makeNewBW and origBW:
            newBW = cmds.duplicate(origBW.split('.')[0])[0]
            cmds.connectAttr('%s.output' % newKeyNode,
                             '%s.%s' %
                             (newBW, '.'.join(curNode.split('.')[1:])),
                             f=True)
            cmds.connectAttr('%s.output' % newBW,
                             '%s.%s' %
                             (newConn, '.'.join(curNode2.split('.')[1:])),
                             f=True)
        else:
            cmds.connectAttr('%s.output' % newKeyNode,
                             '%s.%s' %
                             (newConn, '.'.join(curNode2.split('.')[1:])),
                             f=True)

    elif mode and cmds.objExists(newConn) and \
            not cmds.attributeQuery(
                '.'.join(curNode2.split('.')[1:]), node=newConn, ex=True):
        print('\nDriver node %s does not have the attribute %s .' %
              (newConn, '.'.join(curNode2.split('.')[1:])))
        cmds.delete(newKeyNode)

    else:
        errorCheck = True

    return errorCheck, newConn
Exemplo n.º 47
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
            self.currentStyle = cmds.getAttr(self.moduleGrp + ".style")
            # 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:
                        for axis in self.mirrorAxis:
                            cmds.setAttr(
                                side + self.userGuideName + '_' +
                                self.mirrorGrp + '.scale' + axis, -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)
                # re-rename grp:
                cmds.rename(self.mirrorGrp,
                            self.userGuideName + '_' + self.mirrorGrp)
            # 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'
                # get the number of joints to be created:
                self.nJoints = cmds.getAttr(self.base + ".nJoints")
                # create controls:
                self.hipsA = ctrls.cvBox(
                    ctrlName=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c_hips'] + "A_Ctrl",
                    r=self.ctrlRadius,
                    h=(self.ctrlRadius * 0.25))
                self.hipsB = \
                cmds.circle(name=side + self.userGuideName + "_" + self.langDic[self.langName]['c_hips'] + "B_Ctrl",
                            ch=False, o=True, nr=(0, 1, 0), d=1, s=8, radius=self.ctrlRadius)[0]
                self.chestA = ctrls.cvBox(
                    ctrlName=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c_chest'] + "A_Ctrl",
                    r=self.ctrlRadius,
                    h=(self.ctrlRadius * 0.25))
                self.chestB = \
                cmds.circle(name=side + self.userGuideName + "_" + self.langDic[self.langName]['c_chest'] + "B_Ctrl",
                            ch=False, o=True, nr=(0, 1, 0), d=1, s=8, radius=self.ctrlRadius)[0]
                cmds.addAttr(self.hipsA,
                             longName=side + self.userGuideName + '_' +
                             self.langDic[self.langName]['c_volumeVariation'],
                             attributeType="float",
                             defaultValue=1,
                             keyable=True)
                cmds.addAttr(self.hipsA,
                             longName=side + self.userGuideName + '_active_' +
                             self.langDic[self.langName]['c_volumeVariation'],
                             attributeType="float",
                             defaultValue=1,
                             keyable=True)
                cmds.addAttr(self.hipsA,
                             longName=side + self.userGuideName +
                             '_masterScale_' +
                             self.langDic[self.langName]['c_volumeVariation'],
                             attributeType="float",
                             defaultValue=1,
                             keyable=True)
                ctrls.setLockHide(
                    [self.hipsA, self.hipsB, self.chestA, self.chestB], ['v'],
                    l=False)
                self.aHipsAList.append(self.hipsA)
                self.aChestAList.append(self.chestA)
                self.aVolVariationAttrList.append(
                    side + self.userGuideName + '_' +
                    self.langDic[self.langName]['c_volumeVariation'])
                self.aActVolVariationAttrList.append(
                    side + self.userGuideName + '_active_' +
                    self.langDic[self.langName]['c_volumeVariation'])
                self.aMScaleVolVariationAttrList.append(
                    side + self.userGuideName + '_masterScale_' +
                    self.langDic[self.langName]['c_volumeVariation'])

                # Setup axis order
                if self.rigType == Base.RigType.quadruped:
                    cmds.setAttr(self.hipsA + ".rotateOrder", 1)
                    cmds.setAttr(self.hipsB + ".rotateOrder", 1)
                    cmds.setAttr(self.chestA + ".rotateOrder", 1)
                    cmds.setAttr(self.chestB + ".rotateOrder", 1)
                else:
                    cmds.setAttr(self.hipsA + ".rotateOrder", 3)
                    cmds.setAttr(self.hipsB + ".rotateOrder", 3)
                    cmds.setAttr(self.chestA + ".rotateOrder", 3)
                    cmds.setAttr(self.chestB + ".rotateOrder", 3)

                # Keep a list of ctrls we want to colorize a certain way
                self.aFkCtrl.append([self.hipsB, self.chestB])
                self.aIkCtrl.append([self.hipsA, self.chestA])

                # organize hierarchy:
                cmds.parent(self.hipsB, self.hipsA)
                cmds.parent(self.chestB, self.chestA)
                if self.currentStyle == 0:  #default
                    cmds.rotate(-90, 0, 0, self.hipsA, self.chestA)
                    cmds.makeIdentity(self.hipsA,
                                      self.chestA,
                                      apply=True,
                                      rotate=True)
                # position of controls:
                bottomLocGuide = side + self.userGuideName + "_Guide_JointLoc1"
                topLocGuide = side + self.userGuideName + "_Guide_JointLoc" + str(
                    self.nJoints)
                # snap controls to guideLocators:
                cmds.delete(
                    cmds.parentConstraint(bottomLocGuide,
                                          self.hipsA,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(topLocGuide,
                                          self.chestA,
                                          maintainOffset=False))

                # change axis orientation for biped stype
                if self.currentStyle == 1:  #biped
                    cmds.rotate(0, 0, 0, self.hipsA, self.chestA)
                    cmds.makeIdentity(self.hipsA,
                                      self.chestA,
                                      apply=True,
                                      rotate=True)
                cmds.parent(self.chestA, self.hipsA)

                # zeroOut transformations:
                utils.zeroOut([self.hipsA, self.chestA])
                # modify the pivots of chest controls:
                upPivotPos = cmds.xform(side + self.userGuideName +
                                        "_Guide_JointLoc" +
                                        str(self.nJoints - 1),
                                        query=True,
                                        worldSpace=True,
                                        translation=True)
                cmds.move(
                    upPivotPos[0], upPivotPos[1], upPivotPos[2],
                    self.chestA + ".scalePivot", self.chestA + ".rotatePivot"
                )  # , self.chestB+".scalePivot", self.chestB+".rotatePivot")
                # add originedFrom attributes to hipsA, hipsB and chestB:
                utils.originedFrom(objName=self.hipsA, attrString=self.base)
                utils.originedFrom(objName=self.hipsB,
                                   attrString=bottomLocGuide)
                utils.originedFrom(objName=self.chestB, attrString=topLocGuide)
                # create a simple spine ribbon:
                returnedRibbonList = ctrls.createSimpleRibbon(
                    name=side + self.userGuideName,
                    totalJoints=(self.nJoints - 1))
                rbnNurbsPlane = returnedRibbonList[0]
                rbnNurbsPlaneShape = returnedRibbonList[1]
                rbnJointGrpList = returnedRibbonList[2]
                self.aRbnJointList = returnedRibbonList[3]
                # position of ribbon nurbs plane:
                cmds.setAttr(rbnNurbsPlane + ".tz", -4)
                cmds.move(0, 0, 0, rbnNurbsPlane + ".scalePivot",
                          rbnNurbsPlane + ".rotatePivot")
                cmds.rotate(90, 90, 0, rbnNurbsPlane)
                cmds.makeIdentity(rbnNurbsPlane,
                                  apply=True,
                                  translate=True,
                                  rotate=True)
                downLocPos = cmds.xform(side + self.userGuideName +
                                        "_Guide_JointLoc1",
                                        query=True,
                                        worldSpace=True,
                                        translation=True)
                upLocPos = cmds.xform(side + self.userGuideName +
                                      "_Guide_JointLoc" + str(self.nJoints),
                                      query=True,
                                      worldSpace=True,
                                      translation=True)
                cmds.move(downLocPos[0], downLocPos[1], downLocPos[2],
                          rbnNurbsPlane)
                # create up and down clusters:
                downCluster = \
                cmds.cluster(rbnNurbsPlane + ".cv[0:3][0:1]", name=side + self.userGuideName + '_Down_Cls')[1]
                upCluster = \
                cmds.cluster(rbnNurbsPlane + ".cv[0:3][" + str(self.nJoints) + ":" + str(self.nJoints + 1) + "]",
                             name=side + self.userGuideName + '_Up_Cls')[1]
                # get positions of joints from ribbon nurbs plane:
                startRbnJointPos = cmds.xform(side + self.userGuideName +
                                              "_00_Jnt",
                                              query=True,
                                              worldSpace=True,
                                              translation=True)
                endRbnJointPos = cmds.xform(side + self.userGuideName +
                                            "_%02d_Jnt" % (self.nJoints - 1),
                                            query=True,
                                            worldSpace=True,
                                            translation=True)
                # move pivots of clusters to start and end positions:
                cmds.move(startRbnJointPos[0], startRbnJointPos[1],
                          startRbnJointPos[2], downCluster + ".scalePivot",
                          downCluster + ".rotatePivot")
                cmds.move(endRbnJointPos[0], endRbnJointPos[1],
                          endRbnJointPos[2], upCluster + ".scalePivot",
                          upCluster + ".rotatePivot")
                # snap clusters to guideLocators:
                tempDel = cmds.parentConstraint(bottomLocGuide,
                                                downCluster,
                                                maintainOffset=False)
                cmds.delete(tempDel)
                tempDel = cmds.parentConstraint(topLocGuide,
                                                upCluster,
                                                maintainOffset=False)
                cmds.delete(tempDel)
                # rotate clusters to compensate guide:
                upClusterRot = cmds.xform(upCluster,
                                          query=True,
                                          worldSpace=True,
                                          rotation=True)
                downClusterRot = cmds.xform(downCluster,
                                            query=True,
                                            worldSpace=True,
                                            rotation=True)
                cmds.xform(upCluster,
                           worldSpace=True,
                           rotation=(upClusterRot[0] + 90, upClusterRot[1],
                                     upClusterRot[2]))
                cmds.xform(downCluster,
                           worldSpace=True,
                           rotation=(downClusterRot[0] + 90, downClusterRot[1],
                                     downClusterRot[2]))
                # scaleY of the clusters in order to avoid great extremity deforms:
                rbnHeight = ctrls.distanceBet(
                    side + self.userGuideName + "_Guide_JointLoc" +
                    str(self.nJoints),
                    side + self.userGuideName + "_Guide_JointLoc1",
                    keep=False)[0]
                cmds.setAttr(upCluster + ".sy", rbnHeight / 10)
                cmds.setAttr(downCluster + ".sy", rbnHeight / 10)
                # parent clusters in controls (up and down):
                cmds.parentConstraint(self.hipsB,
                                      downCluster,
                                      maintainOffset=True,
                                      name=downCluster + "_ParentConstraint")
                cmds.parentConstraint(self.chestB,
                                      upCluster,
                                      maintainOffset=True,
                                      name=upCluster + "_ParentConstraint")
                # organize a group of clusters:
                clustersGrp = cmds.group(name=side + self.userGuideName +
                                         "_Rbn_Clusters_Grp",
                                         empty=True)
                self.aClusterGrp.append(clustersGrp)
                if hideJoints:
                    cmds.setAttr(clustersGrp + ".visibility", 0)
                cmds.parent(downCluster, upCluster, clustersGrp, relative=True)
                # make ribbon joints groups scalable:
                for r, rbnJntGrp in enumerate(rbnJointGrpList):
                    if ((r > 0) and (r < (len(rbnJointGrpList) - 1))):
                        scaleGrp = cmds.group(rbnJntGrp,
                                              name=rbnJntGrp.replace(
                                                  "_Grp", "_Scale_Grp"))
                        ctrls.directConnect(scaleGrp, rbnJntGrp, ['sx', 'sz'])
                        cmds.scaleConstraint(clustersGrp,
                                             scaleGrp,
                                             maintainOffset=True,
                                             name=rbnJntGrp + "_Scale")
                    else:
                        cmds.scaleConstraint(clustersGrp,
                                             rbnJntGrp,
                                             maintainOffset=True,
                                             name=rbnJntGrp + "_Scale")
                # calculate the distance to volumeVariation:
                arcLenShape = cmds.createNode('arcLengthDimension',
                                              name=side + self.userGuideName +
                                              "_Rbn_ArcLenShape")
                arcLenFather = cmds.listRelatives(arcLenShape, parent=True)[0]
                arcLen = cmds.rename(arcLenFather,
                                     side + self.userGuideName + "_Rbn_ArcLen")
                arcLenShape = cmds.listRelatives(arcLen,
                                                 children=True,
                                                 shapes=True)[0]
                cmds.setAttr(arcLen + '.visibility', 0)
                # connect nurbsPlaneShape to arcLength node:
                cmds.connectAttr(rbnNurbsPlaneShape + '.worldSpace[0]',
                                 arcLenShape + '.nurbsGeometry')
                cmds.setAttr(arcLenShape + '.vParamValue', 1)
                # avoid undesired squash if rotateZ the nurbsPlane:
                cmds.setAttr(arcLenShape + '.uParamValue', 0.5)
                arcLenValue = cmds.getAttr(arcLenShape + '.arcLengthInV')
                # create a multiplyDivide to output the squashStretch values:
                rbnMD = cmds.createNode('multiplyDivide',
                                        name=side + self.userGuideName +
                                        "_Rbn_MD")
                cmds.connectAttr(arcLenShape + '.arcLengthInV',
                                 rbnMD + '.input2X')
                cmds.setAttr(rbnMD + '.input1X', arcLenValue)
                cmds.setAttr(rbnMD + '.operation', 2)
                # create a blendColor, a condition and a multiplyDivide in order to get the correct result value of volumeVariation:
                rbnBlendColors = cmds.createNode(
                    'blendColors',
                    name=side + self.userGuideName + "_Rbn_BlendColor")
                cmds.connectAttr(
                    self.hipsA + '.' + side + self.userGuideName + '_' +
                    self.langDic[self.langName]['c_volumeVariation'],
                    rbnBlendColors + '.blender')
                rbnCond = cmds.createNode('condition',
                                          name=side + self.userGuideName +
                                          '_Rbn_Cond')
                cmds.connectAttr(
                    self.hipsA + '.' + side + self.userGuideName + '_active_' +
                    self.langDic[self.langName]['c_volumeVariation'],
                    rbnCond + '.firstTerm')
                cmds.connectAttr(rbnBlendColors + '.outputR',
                                 rbnCond + '.colorIfTrueR')
                cmds.connectAttr(rbnMD + '.outputX',
                                 rbnBlendColors + '.color1R')
                rbnVVMD = cmds.createNode('multiplyDivide',
                                          name=side + self.userGuideName +
                                          "_Rbn_VV_MD")
                cmds.connectAttr(
                    self.hipsA + '.' + side + self.userGuideName +
                    '_masterScale_' +
                    self.langDic[self.langName]['c_volumeVariation'],
                    rbnVVMD + '.input2X')
                cmds.connectAttr(rbnVVMD + '.outputX',
                                 rbnCond + '.colorIfFalseR')
                cmds.setAttr(rbnVVMD + '.operation', 2)
                cmds.setAttr(rbnBlendColors + '.color2R', 1)
                cmds.setAttr(rbnCond + ".secondTerm", 1)
                # middle ribbon setup:
                for n in range(1, self.nJoints - 1):
                    if self.currentStyle == 0:  #default
                        self.middle = cmds.circle(
                            name=side + self.userGuideName + "_" +
                            self.langDic[self.langName]['c_middle'] + str(n) +
                            "_Ctrl",
                            ch=False,
                            o=True,
                            nr=(0, 0, 1),
                            d=3,
                            s=8,
                            radius=self.ctrlRadius)[0]
                        cmds.setAttr(self.middle + ".rotateOrder", 4)
                    else:  #biped
                        self.middle = cmds.circle(
                            name=side + self.userGuideName + "_" +
                            self.langDic[self.langName]['c_middle'] + str(n) +
                            "_Ctrl",
                            ch=False,
                            o=True,
                            nr=(0, 1, 0),
                            d=3,
                            s=8,
                            radius=self.ctrlRadius)[0]
                        cmds.setAttr(self.middle + ".rotateOrder", 3)
                    self.aFkCtrl[s].append(self.middle)
                    ctrls.setLockHide([self.middle], ['sx', 'sy', 'sz'])
                    cmds.setAttr(self.middle + '.visibility', keyable=False)
                    cmds.parent(self.middle, self.hipsA)
                    middleLocGuide = side + self.userGuideName + "_Guide_JointLoc" + str(
                        n + 1)
                    cmds.delete(
                        cmds.parentConstraint(middleLocGuide,
                                              self.middle,
                                              maintainOffset=False))
                    if self.currentStyle == 1:  #biped
                        cmds.rotate(0, 0, 0, self.middle)
                    utils.zeroOut([self.middle])
                    middleCluster = cmds.cluster(
                        rbnNurbsPlane + ".cv[0:3][" + str(n + 1) + "]",
                        name=side + self.userGuideName + '_Middle_Cls')[1]
                    middleLocPos = cmds.xform(side + self.userGuideName +
                                              "_Guide_JointLoc" + str(n),
                                              query=True,
                                              worldSpace=True,
                                              translation=True)
                    tempDel = cmds.parentConstraint(middleLocGuide,
                                                    middleCluster,
                                                    maintainOffset=False)
                    cmds.delete(tempDel)
                    middleClusterRot = cmds.xform(middleCluster,
                                                  query=True,
                                                  worldSpace=True,
                                                  rotation=True)
                    cmds.xform(middleCluster,
                               worldSpace=True,
                               rotation=(middleClusterRot[0] + 90,
                                         middleClusterRot[1],
                                         middleClusterRot[2]))
                    cmds.parentConstraint(self.middle,
                                          middleCluster,
                                          maintainOffset=True,
                                          name=middleCluster +
                                          "_ParentConstraint")
                    # parenting constraints like guide locators:
                    self.parentConst = cmds.parentConstraint(
                        self.hipsB,
                        self.chestB,
                        self.middle + "_Zero",
                        name=self.middle + "_ParentConstraint",
                        maintainOffset=True)[0]
                    nParentValue = (n) / float(self.nJoints - 1)
                    cmds.setAttr(self.parentConst + "." + self.hipsB + "W0",
                                 1 - nParentValue)
                    cmds.setAttr(self.parentConst + "." + self.chestB + "W1",
                                 nParentValue)
                    cmds.parent(middleCluster, clustersGrp, relative=True)
                    # add originedFrom attribute to this middle ctrl:
                    utils.originedFrom(objName=self.middle,
                                       attrString=middleLocGuide)
                    # apply volumeVariation to joints in the middle ribbon setup:
                    cmds.connectAttr(rbnCond + '.outColorR',
                                     self.aRbnJointList[n] + '.scaleX')
                    cmds.connectAttr(rbnCond + '.outColorR',
                                     self.aRbnJointList[n] + '.scaleZ')
                # update spine volume variation setup
                currentVV = cmds.getAttr(rbnMD + '.outputX')
                cmds.setAttr(rbnVVMD + '.input1X', currentVV)
                # organize groups:
                self.rbnRigGrp = cmds.group(name=side + self.userGuideName +
                                            "_Grp",
                                            empty=True)
                self.rbnControlGrp = cmds.group(
                    name=side + self.userGuideName + "_Control_Grp",
                    empty=True)
                cmds.parent(self.hipsA + "_Zero",
                            self.rbnControlGrp,
                            relative=True)
                cmds.parent(clustersGrp,
                            side + self.userGuideName + "_Rbn_RibbonJoint_Grp",
                            self.rbnControlGrp,
                            arcLen,
                            self.rbnRigGrp,
                            relative=True)
                if hideJoints:
                    cmds.setAttr(
                        side + self.userGuideName +
                        "_Rbn_RibbonJoint_Grp.visibility", 0)
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.rbnControlGrp, hookType='ctrlHook')
                utils.addHook(objName=clustersGrp, hookType='scalableHook')
                utils.addHook(objName=self.rbnRigGrp, hookType='staticHook')
                cmds.addAttr(self.rbnRigGrp,
                             longName="dpAR_name",
                             dataType="string")
                cmds.addAttr(self.rbnRigGrp,
                             longName="dpAR_type",
                             dataType="string")
                cmds.setAttr(self.rbnRigGrp + ".dpAR_name",
                             self.userGuideName,
                             type="string")
                cmds.setAttr(self.rbnRigGrp + ".dpAR_type",
                             CLASS_NAME,
                             type="string")
                # add module type counter value
                cmds.addAttr(self.rbnRigGrp,
                             longName='dpAR_count',
                             attributeType='long',
                             keyable=False)
                cmds.setAttr(self.rbnRigGrp + '.dpAR_count', dpAR_count)
                # lockHide scale of up and down controls:
                ctrls.setLockHide(
                    [self.hipsA, self.hipsB, self.chestA, self.chestB],
                    ['sx', 'sy', 'sz'])
                # 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()
Exemplo n.º 48
0
def patch():

    #vars#########################################################################################
    sides = ['L', 'R']
    intFixes = ['front', 'back']
    fullLegDuplicate = ['leg_01', 'leg_02', 'foot_01', 'foot_02']
    ##############################################################################################

    for side in sides:
        if side == 'L':
            ctrlcolor = 6
        elif side == 'R':
            ctrlcolor = 13
        #duplicates legs joints to create new fullLeg chain######################################################
        newChain = []
        for i, joint in enumerate(fullLegDuplicate):
            target = '%s_%s_%s' % (side, intFixes[1], joint)
            if mc.objExists(target):
                newjoint = mc.duplicate(target, po=True)[0]
                patchLib.locksSwitch(newjoint,
                                     T=True,
                                     R=True,
                                     S=True,
                                     V=True,
                                     lockdo='unlock',
                                     keydo=True)
                mc.parent(newjoint, w=True)
                newName = '%s_%s_fullLeg_%02d' % (side, intFixes[1], (i + 1))
                mc.rename(newjoint, newName)
                newChain.append(newName)
        if newChain:
            mc.parent(newChain[3], newChain[2])
            mc.parent(newChain[2], newChain[1])
            mc.parent(newChain[1], newChain[0])
        ##parents new fullLeg at the same place as base legs########################################################
        newParent = mc.listRelatives('%s_%s_leg_01_orig' % (side, intFixes[1]),
                                     p=True)[0]
        mc.parent(newChain[0], newParent)
        ############################################################################################################
        #creates new upvector and ik for fullLeg####################################################################
        duplicatedUpVector = mc.duplicate('%s_%s_leg_PV_ctrl' %
                                          (side, intFixes[1]))[0]
        fullLegUpV = mc.rename(duplicatedUpVector,
                               '%s_%s_fullLeg_PV_ctrl' % (side, intFixes[1]))
        shapes.create(fullLegUpV,
                      shape='pyramid',
                      size=1,
                      scale=[1, 1, 1],
                      axis='y',
                      twist=0,
                      offset=[0, 0, 0],
                      color=ctrlcolor,
                      colorDegradeTo=None,
                      replace=True,
                      middle=False)
        fullLegUpVOrig = orig.orig(objlist=[fullLegUpV],
                                   suffix=['_orig'],
                                   origtype='transform',
                                   fromsel=False,
                                   viz=False,
                                   get_ssc=False,
                                   rtyp='auto')[0]
        mc.parent(fullLegUpVOrig, 'traj')
        ###scales newUpvector shape up ##########################################################
        scalePoints = mc.ls('%s.cv[*]' % fullLegUpV, fl=True)
        mc.scale(1.25, 1.25, 1.25, scalePoints, r=True, ocp=True)
        ##creates ik for fullLeg###################################################################################
        fullLegIkName = '%s_%s_fullLeg_ikh' % (side, intFixes[1])
        fullLegIk = mc.ikHandle(sj=newChain[0],
                                ee=newChain[3],
                                n=fullLegIkName,
                                sol='ikRPsolver')
        mc.poleVectorConstraint(fullLegUpV, fullLegIk[0])
        ##reparent log upV in FullLeg upV and replace constraint
        upVCnsName = '%s_%s_leg_PV_ctrl_orig_parentConstraint1' % (side,
                                                                   intFixes[1])
        upVCnsTarget = mc.parentConstraint(upVCnsName, q=True, tl=True)[0]
        mc.delete(upVCnsName)
        legUpVOrig = '%s_%s_leg_PV_ctrl_orig' % (side, intFixes[1])
        mc.parent(legUpVOrig, fullLegUpV)
        mc.parentConstraint(upVCnsTarget, fullLegUpVOrig, mo=True)

        ############################################################################################################

        #updating original ball 01 and 02 rigs######################################################################
        ball01 = '%s_%s_leg_rvfoot_ball_01_ctrl' % (side, intFixes[1])
        ball02Orig = '%s_%s_leg_rvfoot_ball_02_ctrl_orig' % (side, intFixes[1])
        ball02 = '%s_%s_leg_rvfoot_ball_02_ctrl' % (side, intFixes[1])
        #updating original ball_01 rig##############################################################################
        ##ads ik offset on ball01###################################################################################
        patchLib.locksSwitch(ball01,
                             T=True,
                             R=True,
                             S=True,
                             V=True,
                             lockdo='unlock',
                             keydo=True)
        ball01ik = mc.duplicate(ball01, po=True)
        ball01ikend = mc.duplicate(ball02Orig, po=True)
        ball01ikName = '%s_%s_leg_ik_rvfoot_ball_01_joint' % (side,
                                                              intFixes[1])
        ball01ikEndName = '%s_%s_leg_ik_rvfoot_ball_01_end' % (side,
                                                               intFixes[1])
        ball01ik = mc.rename(ball01ik, ball01ikName)
        ball01ikend = mc.rename(ball01ikend, ball01ikEndName)
        mc.parent(ball01ikend, ball01ik)
        mc.parent(ball01, ball01ik)
        ###creates ctrl for ball01  ik offset###########################################################################
        ballIKCtrlname = '%s_%s_leg_rvfoot_ik_ball_01_ctrl' % (side,
                                                               intFixes[1])
        mc.select(cl=True)
        ballIKCtrl = mc.joint(n=ballIKCtrlname)
        mc.setAttr('%s.drawStyle' % ballIKCtrl, 2)
        ballIKCtrlOrig = orig.orig(objlist=[ballIKCtrl],
                                   suffix=['_orig'],
                                   origtype='joint',
                                   fromsel=False,
                                   viz=False,
                                   get_ssc=False,
                                   rtyp='auto')[0]
        shapes.create(ballIKCtrl,
                      shape='cube',
                      size=.25,
                      scale=[1, .5, 1],
                      axis='y',
                      twist=0,
                      offset=[0, 0, 0],
                      color=ctrlcolor,
                      colorDegradeTo=None,
                      replace=True,
                      middle=False)
        mc.parent(ballIKCtrlOrig, ball01ikend)
        mc.setAttr('%s.translate' % ballIKCtrlOrig, 0, 0, 0)
        mc.parent(ballIKCtrlOrig, (mc.listRelatives(ball01ik, p=True)))
        ###creates ikSCsolver for ball 01 ik #####################################################################
        ball01ikhName = '%s_%s_leg_rvfoot_ik_ball_01_ikh' % (side, intFixes[1])
        ball01ikh = mc.ikHandle(sj=ball01ik,
                                ee=ball01ikend,
                                n=ball01ikhName,
                                sol='ikSCsolver')
        mc.parent(ball01ikh[0], ballIKCtrl)

        patchLib.locksSwitch(ball01,
                             T=True,
                             R=False,
                             S=True,
                             V=True,
                             lockdo='lock',
                             keydo=False)
        #updating original ball_02 rig##############################################################################
        ##remove original aim constraint############################################################################
        ball02AimCns = mc.listConnections('%s.rotateX' % ball02Orig)[0]
        mc.delete(ball02AimCns)
        ##ads ik offset on ball02###################################################################################
        ballDublicate = [
            ball02Orig,
            '%s_%s_leg_rvfoot_ball_02_ctrl' % (side, intFixes[1]),
            '%s_%s_leg_rvfoot_ankle_ctrl' % (side, intFixes[1])
        ]
        newBall = []
        for j, ballJnt in enumerate(ballDublicate):
            newJnt = mc.duplicate(ballJnt, po=True)
            newJntName = ballDublicate[j].replace('rvfoot', 'rvfoot_ik')
            newJntName = newJntName.replace('ctrl', 'jnt')
            mc.rename(newJnt, newJntName)
            newBall.append(newJntName)
        mc.parent(newBall[2], newBall[1])
        mc.parent(newBall[1], newBall[0])
        mc.parent(newBall[0], ball02Orig)
        mc.parent(ball02, newBall[1])
        ###creates ikSCsolver for ball ik offset#####################################################################
        ball02ikhName = '%s_%s_leg_rvfoot_ik_ball_02_ikh' % (side, intFixes[1])
        ball02ikh = mc.ikHandle(sj=newBall[1],
                                ee=newBall[2],
                                n=ball02ikhName,
                                sol='ikSCsolver')
        ###creates ctrl for ball ik offset###########################################################################
        ballIKCtrlname = '%s_%s_leg_rvfoot_ik_ball_02_ctrl' % (side,
                                                               intFixes[1])
        mc.select(cl=True)
        ballIKCtrl = mc.joint(n=ballIKCtrlname)
        mc.setAttr('%s.drawStyle' % ballIKCtrl, 2)
        ballIKCtrlOrig = orig.orig(objlist=[ballIKCtrl],
                                   suffix=['_orig'],
                                   origtype='joint',
                                   fromsel=False,
                                   viz=False,
                                   get_ssc=False,
                                   rtyp='auto')[0]
        if side == 'L':
            ctrlcolor = 6
        elif side == 'R':
            ctrlcolor = 13
        shapes.create(ballIKCtrl,
                      shape='locator',
                      size=1,
                      scale=[1, 1, 1],
                      axis='y',
                      twist=0,
                      offset=[0, 0, 0],
                      color=ctrlcolor,
                      colorDegradeTo=None,
                      replace=True,
                      middle=False)
        mc.parent(ballIKCtrlOrig, newBall[2], r=True)
        mc.parent(ballIKCtrlOrig, newBall[0])
        ####adjusts ctrl position####################################################################################
        mc.setAttr('%s.translateY' % ballIKCtrlOrig,
                   (mc.getAttr('%s.translateY' % ballIKCtrlOrig)) * 2)
        mc.xform(ballIKCtrlOrig, ws=True, r=True, a=True, ro=(0, 0, 0))
        if side == 'L':
            mc.setAttr('%s.jointOrientX' % ballIKCtrl,
                       180 - (mc.getAttr('%s.rotateX' % ballIKCtrlOrig)))
        if side == 'R':
            mc.setAttr('%s.jointOrientX' % ballIKCtrl,
                       -(mc.getAttr('%s.rotateX' % ballIKCtrlOrig)))
        ##parents ball 02 ikh into ctrl##############################################################################
        mc.parent(ball02ikh[0], ballIKCtrl)
        mc.setAttr('%s.translate' % ball02ikh[0], 0, 0, 0)
        ##constraints updated ball02 to fullLeg######################################################################
        mc.parentConstraint(newChain[3],
                            newBall[0],
                            st=["x", "y", "z"],
                            mo=True)
        ##connects translate of fullLegs first joint to base legs first joint#######################################
        mc.connectAttr('%s.translate' % newChain[0],
                       '%s_%s_leg_01_orig.translate' % (side, intFixes[1]),
                       f=True)
        ##parent new ikh############################################################################################
        fullLegParent = '%s_%s_leg_rvfoot_ball_01_ctrl' % (side, intFixes[1])
        mc.parent(fullLegIk[0], fullLegParent)

        ##############################################################################################################
        #temp remove front aim cns on ball_02
        mc.delete('%s_%s_leg_rvfoot_ball_02_ctrl_orig_aimConstraint1' %
                  (side, intFixes[0]))
        ##############################################################################################################
        # rough cleanup
        hideList = [
            'leg_rvfoot_ik_ball_02_ikh', 'fullLeg_ikh',
            'leg_rvfoot_ik_ball_01_ikh', 'fullLeg_01'
        ]
        for toHide in hideList:
            mc.hide('%s_%s_%s' % (side, intFixes[1], toHide))
Exemplo n.º 49
0
    def generateLODS(self):
        x = self.ui.selectedGeo_groupBox.title()
        x = (x.replace('Selected Mesh:  ', ''))
        fullPath = str(cmds.ls(x, long=True)[0])
        if fullPath:
            print fullPath
            obSl = fullPath
            if len(obSl) == 0:
                cmds.confirmDialog(
                    title='Error:',
                    message='No objects selected for polygon reduction')
            else:
                print('\n')
                cmds.select(obSl)
                lods = []
                LOD01_Val = []
                LOD02_Val = []
                LOD03_Val = []
                currentIndex = self.whatTab()
                print currentIndex
                if currentIndex == 0:
                    LOD1_Number = int(self.ui.LOD1_num.text())
                    LOD2_Number = int(self.ui.LOD2_num.text())
                    LOD3_Number = int(self.ui.LOD3_num.text())
                    LOD3_Number = int(self.ui.LOD3_num.text())
                    LOD01_Val.append(LOD1_Number)
                    LOD02_Val.append(LOD2_Number)
                    LOD03_Val.append(LOD3_Number)
                else:
                    LOD01_Percent = self.ui.LOD1_horizontalSlider.value()
                    LOD02_Percent = self.ui.LOD2_horizontalSlider.value()
                    LOD03_Percent = self.ui.LOD3_horizontalSlider.value()
                    currentMeshPolyGonCount = cmds.polyEvaluate(f=True)
                    print currentMeshPolyGonCount
                    LOD01_PolyPercent = (LOD01_Percent *
                                         currentMeshPolyGonCount) / 100
                    LOD02_PolyPercent = (LOD02_Percent *
                                         currentMeshPolyGonCount) / 100
                    LOD03_PolyPercent = (LOD03_Percent *
                                         currentMeshPolyGonCount) / 100
                    LOD01_Val.append(LOD01_PolyPercent)
                    LOD02_Val.append(LOD02_PolyPercent)
                    LOD03_Val.append(LOD03_PolyPercent)

                LOD0_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD0'))
                lods.append(LOD0_LOD)
                #print LOD01_Val,LOD02_Val,LOD03_Val
                if self.ui.LOD1_chkBox.isChecked():
                    LOD1_Num = LOD01_Val[0]
                    LOD1_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD1'))
                    self.genFunction(LOD1_LOD, LOD1_Num)
                    lods.append(LOD1_LOD)
                    print('"__LOD1"__LOD__generated__Successfully :~- ' +
                          str(LOD1_LOD))
                if self.ui.LOD2_chkBox.isChecked():
                    LOD2_Num = LOD02_Val[0]
                    LOD2_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD2'))
                    self.genFunction(LOD2_LOD, LOD2_Num)
                    lods.append(LOD2_LOD)
                    print('"__LOD2"__LOD__generated__Successfully :~- ' +
                          str(LOD2_LOD))
                if self.ui.LOD3_chkBox.isChecked():
                    LOD3_Num = LOD03_Val[0]
                    LOD3_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD3'))
                    self.genFunction(LOD3_LOD, LOD3_Num)
                    lods.append(LOD3_LOD)
                    print('"__LOD3"__LOD__generated__Successfully :~- ' +
                          str(LOD3_LOD))

                if self.ui.WRAP_chkBox.isChecked():
                    WRAP_Num = str(self.ui.wrap_comboBox.currentText())
                    print WRAP_Num
                    LOD5_LOD = cmds.CreatePolygonSoccerBall(n=obSl + '__LOD4')
                    newMesh = cmds.rename(LOD5_LOD, (obSl + '__LOD4'))
                    if WRAP_Num == '180':
                        cmds.polySmooth(newMesh, divisions=1)
                    if WRAP_Num == '720':
                        cmds.polySmooth(newMesh, divisions=2)
                    if WRAP_Num == '2880':
                        cmds.polySmooth(newMesh, divisions=3)
                    cmds.delete(newMesh, ch=True)
                    bbox = cmds.exactWorldBoundingBox(obSl)
                    x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(obSl)
                    xc = (x2 + x1) / 2.0
                    yc = (y2 + y1) / 2.0
                    zc = (z2 + z1) / 2.0
                    xw = x2 - x1
                    yw = y2 - y1
                    zw = z2 - z1
                    cmds.move(xc, yc, zc, newMesh)
                    cmds.scale(xw, yw, zw, newMesh)
                    shrinkWrapNode = pm.deformer(newMesh, type='shrinkWrap')[0]
                    pm.PyNode(obSl).worldMesh[0] >> shrinkWrapNode.targetGeom
                    shrinkWrapNode.closestIfNoIntersection.set(True)
                    cmds.delete(newMesh, ch=True)
                    cmds.select(clear=True)
                    cmds.select(newMesh)
                    cmds.select(obSl, add=True)
                    self.copyPivot()
                    lods.append(newMesh)
                if self.ui.BBOX_chkBox.isChecked():
                    print('make a bounding box')
                    cmds.select(obSl)
                    box = self.MakeCube()
                    newmeshBox = cmds.rename(box, (obSl + '__LOD5'))
                    lods.append(newmeshBox)
                    cmds.select(obSl)
                    cmds.select(newmeshBox, add=True)
                    self.copyPivot()
                cmds.select(clear=True)
                if lods == []:
                    pass
                else:
                    grp = (obSl + '__LOD_grp')
                    if cmds.objExists(grp):
                        pass
                    else:
                        lod_grp = cmds.group(n=grp, em=True)
                    print grp
                    for lod in lods:
                        print lod
                        cmds.parent(lod, grp)
                print('\n')
                cmds.inViewMessage(amg="LOD generated successfully",
                                   pos="botCenter",
                                   fade=True)
                print('Done')
        else:
            cmds.confirmDialog(
                title='Error:',
                message='No objects selected for polygon reduction')
def createHouse(scaleX, scaleY, scaleZ, r, g, b, numOfHouses, randX, randY,
                randZ, rotateX, rotateY, rotateZ):

    for i in range(numOfHouses):

        # Create new scene every time program runs
        mc.file(new=True, force=True)
        """
	        Below, we create the roof for the house
	        """
        # Roof
        roof = mc.polyPyramid(n='roof')
        mc.scale(28.147, 12.410, 28.373)
        mc.move(1.167, 32.273, 0)
        mc.setAttr('roof.ry', 45)
        colorLambert = mc.shadingNode('lambert', asShader=True)
        mc.select(roof)

        # ColorLambert and HyperShade are for setting color of the object

        mc.setAttr((colorLambert + '.color'), r, g, b, type='double3')

        mc.hyperShade(assign=colorLambert)
        mc.polyMoveVertex('roof.vtx[0:1]', tx=-25.3)
        mc.polyMoveVertex('roof.vtx[4]', tx=-10.3)

        # Roof 2
        roof2 = mc.polyPyramid(n='roof2')
        mc.scale(28.147, 12.410, 28.373)
        mc.move(1.167, 28.601, -28.944)
        mc.setAttr('roof2.rx', -20.000)
        mc.setAttr('roof2.ry', 43.000)
        mc.setAttr('roof2.rz', -13.500)
        colorLambert = mc.shadingNode('lambert', asShader=True)
        mc.select(roof2)
        #mc.setAttr((colorLambert + '.color'), 0.5725, 0.1686, 0.129, type = 'double3')
        mc.setAttr((colorLambert + '.color'), r, g, b, type='double3')

        mc.hyperShade(assign=colorLambert)
        mc.polyMoveVertex('roof2.vtx[0:1]', tx=-25.3)
        mc.polyMoveVertex('roof2.vtx[4]', tx=-10.3)
        """
	                Below, we create the windows for the house
	                """
        # Windows

        # Front top above garage
        for i in range(1):
            windows = mc.polyCube(n='windowsFrontTop')
            mc.scale(0.420, 5.886, 9.002)
            mc.move(11.975, 23.622, -10.279 * -i)
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(windows)
            mc.setAttr((colorLambert + '.color'), 0, 0, 0, type='double3')
            mc.hyperShade(assign=colorLambert)

# Left Side on 2nd story
        for i in range(0, 2):
            windows = mc.polyCube(n='windowsRightSideBottom')
            mc.scale(0.420, 3.325, 5.290)
            mc.rotate(0, 90, 0)
            mc.move(-15.612 * i, 23.622, 13.253)
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(windows)
            mc.setAttr((colorLambert + '.color'), 0, 0, 0, type='double3')
            mc.hyperShade(assign=colorLambert)

# Rear windows on 2nd story
        for i in range(-1, 1):
            windows = mc.polyCube(n='windowsFrontBottom')
            mc.scale(0.420, 3, 2.940)
            mc.move(-33.978, 23.622, 8.921 * -i)
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(windows)
            mc.setAttr((colorLambert + '.color'), 0, 0, 0, type='double3')
            mc.hyperShade(assign=colorLambert)

# 2 end windows near Front Door
        for i in range(2):
            frontDoorEndWindow = mc.polyCube(n='frontDoorEndWindow')
            mc.scale(0.627, 4.665, 2.428)
            mc.move(-4.546, 13.984, -27.740 - (10 * i))
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(frontDoorEndWindow)
            mc.setAttr((colorLambert + '.color'), 0, 0, 0, type='double3')
            mc.hyperShade(assign=colorLambert)

# Window near Front Door
        for i in range(1):
            frontDoorWindow = mc.polyCube(n='frontDoorWindow')
            mc.scale(0.627, 4.665, 7.094)
            mc.move(-4.546, 13.984, -32.742)
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(frontDoorWindow)
            #mc.setAttr((colorLambert + '.color'), 0.412, 0.412, 0.412, type = 'double3' )
            mc.setAttr((colorLambert + '.color'),
                       random.uniform(0.0, 1.0),
                       random.uniform(0.0, 1.0),
                       random.uniform(0.0, 1.0),
                       type='double3')
            mc.hyperShade(assign=colorLambert)

# Rear window near ground floor bedroom
        for i in range(1):
            windowsRearBottomNearBedroom = mc.polyCube(
                n='windowsRearBottomNearBedroom')
            mc.scale(0.420, 3, 6.388)
            mc.move(-33.978, 14.686, -19.139)
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(windowsRearBottomNearBedroom)
            mc.setAttr((colorLambert + '.color'), 0, 0, 0, type='double3')
            mc.hyperShade(assign=colorLambert)

# Rear window near kitchen
        for i in range(1):
            windowsRearBottomNearKitchen = mc.polyCube(
                n='windowsRearBottomNearKitchen')
            mc.scale(0.420, 7.818, 4.556)
            mc.move(-33.978, 10.546, -36.449)
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(windowsRearBottomNearKitchen)
            mc.setAttr((colorLambert + '.color'), 0, 0, 0, type='double3')
            mc.hyperShade(assign=colorLambert)
        """
	                Below, we create the main and right side of the building for the house
	                """
        # main building
        building = mc.polyCube(n='building')
        mc.scale(25.963, 26.190, 45.551)
        mc.move(-10.958, 14.810, 0)
        mc.setAttr('building.ry', 90)
        colorLambert = mc.shadingNode('lambert', asShader=True)
        mc.select(building)
        #mc.setAttr((colorLambert + '.color'), r, g, b, type = 'double3' )
        mc.setAttr((colorLambert + '.color'),
                   random.uniform(0.0, 1.0),
                   random.uniform(0.0, 1.0),
                   random.uniform(0.0, 1.0),
                   type='double3')
        mc.hyperShade(assign=colorLambert)
        mc.polySplitVertex('building.vtx[2:5]')

        # Right side of building
        rightSide = mc.polyCube(n='rightSide')
        mc.scale(28.082, 7.793, 29.276)
        mc.rotate(0, 90, 0)
        mc.move(-19.041, 5.623, -26.999)
        colorLambert = mc.shadingNode('lambert', asShader=True)
        mc.select(rightSide)
        #mc.setAttr((colorLambert + '.color'), r, g, b, type = 'double3' )
        mc.setAttr((colorLambert + '.color'),
                   random.uniform(0.0, 1.0),
                   random.uniform(0.0, 1.0),
                   random.uniform(0.0, 1.0),
                   type='double3')
        mc.hyperShade(assign=colorLambert)
        mc.polyMoveVertex('rightSide.vtx[2]', 'rightSide.vtx[4]', ty=18.4)
        mc.polyMoveVertex('rightSide.vtx[3]', 'rightSide.vtx[5]', ty=10)
        mc.polyMoveVertex('rightSide.vtx[3]', ty=1)
        mc.polyMoveVertex('rightSide.vtx[5]', ty=1)
        """
	                Below, we create the front doors and the garage door
	                """
        # 2 Front Doors
        for i in range(2):
            frontDoor = mc.polyCube(n='frontDoor')
            mc.scale(0.627, 8.678, 4.392)
            mc.move(-4.546, 6.086, -15.466 - (4.5 * i))
            colorLambert = mc.shadingNode('lambert', asShader=True)
            mc.select(frontDoor)
            mc.setAttr((colorLambert + '.color'), 0.5, 0, 0, type='double3')
            mc.hyperShade(assign=colorLambert)

# Garage Door
        for i in range(1):
            garageDoor = mc.polyCube(n='garageDoor')
            mc.move(11.982, 6.060 + (2.35 * i), 0)
            mc.scale(0.277, 8.664, 18.652)
            mc.select(garageDoor)

# polyUnite() will gather the objects and will merge all of them together. This allows to scale the entire house without having to worry about modifying the coordinates of the windows, roof, and other components of the house
        house = mc.polyUnite('rightSide',
                             'building',
                             'garageDoor',
                             'windowsRightSideBottom',
                             'windowsRightSideBottom1',
                             'windowsFrontBottom1',
                             'windowsFrontTop',
                             'frontDoorEndWindow1',
                             'roof',
                             'frontDoor1',
                             'frontDoor',
                             'roof2',
                             'windowsFrontBottom',
                             'windowsRearBottomNearKitchen',
                             'windowsRearBottomNearBedroom',
                             'frontDoorWindow',
                             'frontDoorEndWindow',
                             n='house')
        mc.setAttr('house.translateX', 54)

        # Here we are spawning the number of houses into the scene
        for i in range(1, numOfHouses):
            mc.scale(scaleX / 10, scaleY / 10, scaleZ / 10, house)
            mc.duplicate('house', smartTransform=False)
            mc.setAttr('house.translateX', 54)
            mc.setAttr('house%d.rx' % i, rotateX)
            mc.setAttr('house%d.ry' % i, rotateY)
            mc.setAttr('house%d.rz' % i, rotateZ)

            mc.setAttr('house%d.tx' % i, 54 - randX)
            mc.setAttr('house%d.ty' % i, 2 * i * randY)
            mc.setAttr('house%d.tz' % i, i * 5 * randZ)

            #mc.xform('house%d' % i, translation=[54 - randX, 2 * i * randY, 5 * i * randZ])

        return house  # Now we return the object
Exemplo n.º 51
0
def upperArmTwist(color, rollGrpParent, fkArmJoint, ikArmJoint, suffix, name,
                  prefix, upperArm, lowerArm):
    print "START Building the " + suffix + " UPPER arm twists---------------------------------------"

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

        # define the joints for this rig.
        upperarm = prefix + upperArm + suffix
        lowerarm = prefix + lowerArm + suffix
        driver_clavicle = "driver_" + prefix + "clavicle" + suffix
        driver_upperarm = "driver_deltoid_" + prefix + upperArm + suffix
        driver_lowerarm = "driver_" + prefix + lowerArm + suffix

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

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

        for i in range(int(numRolls)):
            print "...Building upper arm twist_0" + str(i + 1)
            driver_upperarm_twist = "driver_" + prefix + upperArm + "_twist_0" + str(
                i + 1) + suffix

            rollGrp = cmds.group(empty=True,
                                 name=upperarm + "_roll_grp_0" + str(i + 1))
            cmds.parent(rollGrp, "arm_sys_grp")

            # Move the driver_upperarm_twist joint to its correct position between the driver_upperarm and its driver_lowerarm using a point constraint.
            const = cmds.parentConstraint(driver_upperarm,
                                          driver_upperarm_twist,
                                          n=driver_upperarm +
                                          "_temp_parentConst",
                                          weight=1)
            cmds.delete(const)
            const = cmds.pointConstraint(driver_upperarm,
                                         driver_lowerarm,
                                         driver_upperarm_twist,
                                         n=driver_upperarm +
                                         "_temp_PointConst",
                                         weight=1)
            cmds.delete(const)

            # Duplicate the driver_upperarm, driver_lowerarm, and driver_upperarm_twist joints
            blendJnts = []
            blend_driver_upperarmParent = cmds.duplicate(
                driver_upperarm,
                n="Blend_" + driver_upperarm + "_parent_ignore_0" + str(i + 1),
                ic=True,
                po=True)[0]
            blendJnts.append(blend_driver_upperarmParent)

            blend_driver_lowerarm = cmds.duplicate(
                driver_lowerarm,
                n="Blend_" + driver_lowerarm + "_ignore_0" + str(i + 1),
                ic=True,
                po=True)[0]
            blendJnts.append(blend_driver_lowerarm)

            blend_driver_upperarm = cmds.duplicate(
                driver_upperarm,
                n="Blend_" + driver_upperarm + "_ignore_0" + str(i + 1),
                po=True)[0]
            blendJnts.append(blend_driver_upperarm)

            blend_driver_upperarm_twist = cmds.duplicate(
                driver_upperarm_twist,
                n="Blend_" + driver_upperarm_twist + "_ignore_0" + str(i + 1),
                ic=True,
                po=True)[0]
            blendJnts.append(blend_driver_upperarm_twist)

            cmds.parent(blend_driver_lowerarm, blend_driver_upperarm_twist,
                        blend_driver_upperarmParent)
            cmds.parent(blend_driver_upperarm, blend_driver_upperarm_twist)

            # Set the parent bone to have zyx rotation order
            cmds.setAttr(blend_driver_upperarmParent + ".rotateOrder", 2)

            originalJnts = [driver_upperarm, driver_lowerarm]
            #print originalJnts

            # Now we are going to disconnect the constraints that were driving the original driver_upperarm
            # and driver_lowerarm joints and re-connect them to the parent_ignore and ignore joints that were duped from them.
            # This is so that we can create new constraints on the driver_upperarm and driver_lowerarm joints for the rig.
            j = 0
            a = 0

            #while a < len(originalJnts):
            for a in range(0, len(originalJnts)):
                # Go through the inputs of the original joints and disconnect them
                origConn = cmds.listConnections(originalJnts[a],
                                                d=False,
                                                c=+ True,
                                                p=True)

                for j in range(0, len(origConn), 2):
                    cmds.disconnectAttr(origConn[j + 1], origConn[j])
                    nameList = origConn[j + 1].split(".")[0]
                    destConn = cmds.listConnections(nameList, s=False)
                    # Find out if the node that was an input to the original joint is also an output
                    if originalJnts[a] in destConn:
                        sourceConn = cmds.listConnections(nameList,
                                                          d=False,
                                                          c=True,
                                                          p=True)
                        for k in range(0, len(sourceConn), 2):
                            # Get the input connections to the node that are connected to the original joint
                            nameConnList = sourceConn[k + 1].split(".")
                            if (nameConnList[0] == originalJnts[a]):
                                # Disconnect from the original joint and connect to the blend joint
                                cmds.disconnectAttr(sourceConn[k + 1],
                                                    sourceConn[k])
                                nameConnList[0] = blendJnts[a]
                                cmds.connectAttr(
                                    nameConnList[0] + "." + nameConnList[-1],
                                    sourceConn[k])

            # create the manual twist control
            if i == 0:
                twistCtrl = utils.createControl("circle", 15,
                                                upperarm + "_twist_anim")
            else:
                twistCtrl = utils.createControl(
                    "circle", 15, upperarm + "_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(blend_driver_upperarm_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(blend_driver_upperarm_twist,
                                               twistCtrlGrp)[0]
            cmds.delete(constraint)
            cmds.parent(twistCtrl, twistCtrlGrp)
            cmds.parent(twistCtrlGrp, rollGrp)
            cmds.makeIdentity(twistCtrl, t=1, r=1, s=1, apply=True)
            cmds.parentConstraint(blend_driver_upperarm_twist, twistCtrlGrp)

            # 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=(name + "twistCtrlVisUpper"),
                             at='bool',
                             dv=0,
                             keyable=True)
            cmds.connectAttr("Rig_Settings." + name + "twistCtrlVisUpper",
                             twistCtrl + ".v")

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

            cmds.parent(blend_driver_upperarmParent, rollGrp)

            # Constrain the original joints to the blend joints
            cmds.orientConstraint(blend_driver_upperarm,
                                  driver_upperarm,
                                  n=driver_upperarm + "_0" + str(i + 1) +
                                  "_OrntCnst",
                                  mo=True,
                                  w=1)
            cmds.pointConstraint(blend_driver_upperarm,
                                 driver_upperarm,
                                 n=driver_upperarm + "_0" + str(i + 1) +
                                 "_PtCnst",
                                 mo=True,
                                 w=1)

            cmds.orientConstraint(blend_driver_lowerarm,
                                  driver_lowerarm,
                                  n=driver_lowerarm + "_0" + str(i + 1) +
                                  "_OrntCnst",
                                  mo=True,
                                  w=1)
            cmds.pointConstraint(blend_driver_lowerarm,
                                 driver_lowerarm,
                                 n=driver_lowerarm + "_0" + str(i + 1) +
                                 "_PtCnst",
                                 mo=True,
                                 w=1)

            cmds.orientConstraint(twistCtrl,
                                  driver_upperarm_twist,
                                  n=driver_upperarm_twist + "_0" + str(i + 1) +
                                  "_OrntCnst",
                                  mo=True,
                                  w=1)
            cmds.pointConstraint(twistCtrl,
                                 driver_upperarm_twist,
                                 n=driver_upperarm_twist + "_0" + str(i + 1) +
                                 "_PtCnst",
                                 mo=True,
                                 w=1)

            # Create a driver_upperarm_twist multiplier to multiply the driver_upperarm_twist values by -.5 to counter rotate the driver_upperarm_twist and driver_upperarm back from the overall limb's driver_upperarm_twist amount.
            twistMult = cmds.shadingNode("multiplyDivide",
                                         asUtility=True,
                                         name=blend_driver_upperarm_twist +
                                         "_0" + str(i + 1) + "_MDnode")
            twistMultDrive = cmds.shadingNode(
                "multiplyDivide",
                asUtility=True,
                name=blend_driver_upperarm_twist + "_0" + str(i + 1) +
                "_Drive_MDnode")
            twistMultDriveInv = cmds.shadingNode(
                "multiplyDivide",
                asUtility=True,
                name=blend_driver_upperarm_twist + "_0" + str(i + 1) +
                "_DriveInv_MDnode")
            twistMultMultiplier = cmds.shadingNode(
                "multiplyDivide",
                asUtility=True,
                name=blend_driver_upperarm_twist + "_0" + str(i + 1) +
                "_Multiplier_MDnode")
            twistMultMultiplierInv = cmds.shadingNode(
                "multiplyDivide",
                asUtility=True,
                name=blend_driver_upperarm_twist + "_0" + str(i + 1) +
                "_MultiplierInv_MDnode")
            twistReverse = cmds.shadingNode("reverse",
                                            asUtility=True,
                                            name=blend_driver_upperarm_twist +
                                            "_0" + str(i + 1) + "_REVnode")

            cmds.connectAttr(blend_driver_upperarmParent + ".rotateX",
                             twistMult + ".input1X",
                             force=True)
            cmds.connectAttr(
                "Rig_Settings." + name + "UpperarmTwist" + str(i + 1) +
                "Amount", twistReverse + ".inputX")
            cmds.connectAttr(
                "Rig_Settings." + name + "UpperarmTwist" + str(i + 1) +
                "Amount", twistMultMultiplierInv + ".input1X")
            cmds.connectAttr(twistReverse + ".outputX",
                             twistMultMultiplier + ".input1X",
                             force=True)
            cmds.connectAttr(twistMult + ".outputX",
                             twistMultDrive + ".input1X",
                             force=True)
            cmds.connectAttr(twistMultMultiplier + ".outputX",
                             twistMultDrive + ".input2X",
                             force=True)
            cmds.connectAttr(twistMult + ".outputX",
                             twistMultDriveInv + ".input1X",
                             force=True)
            cmds.connectAttr(twistMultMultiplierInv + ".outputX",
                             twistMultDriveInv + ".input2X",
                             force=True)
            cmds.connectAttr(twistMultDrive + ".outputX",
                             blend_driver_upperarm_twist + ".rotateX",
                             force=True)
            cmds.connectAttr(twistMultDriveInv + ".outputX",
                             blend_driver_upperarm + ".rotateX",
                             force=True)
            cmds.setAttr(twistMult + ".input2X", -0.5)
            cmds.setAttr(twistMult + ".input2X", l=True)

            cmds.setAttr(twistMultMultiplier + ".input2X", 2)
            cmds.setAttr(twistMultMultiplierInv + ".input2X", 2)

            cmds.select(blend_driver_upperarmParent)

            cmds.parentConstraint(driver_clavicle, rollGrp, mo=True)
    print ".END Building the " + suffix + " UPPER arm twists---------------------------------------"
Exemplo n.º 52
0
def locators():
    #root locator
    root = cmds.spaceLocator(n='loc_root')
    cmds.move(0, 3, 0)
    cmds.scale(.5, .5, .5)

    #hip connection for the legs
    hipCon = cmds.spaceLocator(n='loc_spine_hip_connect')
    cmds.move(0, 1.5, -.5)
    cmds.scale(.5, .5, .5)
    cmds.parent(hipCon, root)

    #spine locator
    body = cmds.spaceLocator(n='loc_spine_body')
    cmds.move(0, 2, 0)
    cmds.scale(.5, .5, .5)
    cmds.parent(body, root)

    #create and group the left wing locators
    locGrp = cmds.group(n='Locators_Left_Wing', em=True)
    cmds.parent(locGrp, root)
    shoulder = cmds.spaceLocator(n='loc_wing_shoulder')
    cmds.move(.7, 3.1, 0.05)
    cmds.scale(.2, .2, .2)
    cmds.parent(shoulder, locGrp)

    elbow = cmds.spaceLocator(n='loc_wing_elbow')
    cmds.move(1.4, 1.7, -.7)
    cmds.scale(.2, .2, .2)
    cmds.parent(elbow, locGrp)

    mid = cmds.spaceLocator(n='loc_wing_mid')
    cmds.move(2.2, 3.5, .46)
    cmds.scale(.2, .2, .2)
    cmds.parent(mid, locGrp)

    tip = cmds.spaceLocator(n='loc_wing_tip')
    cmds.move(4.6, 2.6, 0)
    cmds.parent(tip, locGrp)

    #duplicate and rename left wing locators for the right side
    cmds.select(locGrp)
    cmds.duplicate(n='Locators_Right_Wing', rr=True, rc=False)
    cmds.scale(-2, 2, 2)

    #create and group left leg locators
    locGrp2 = cmds.group(n='Locators_Left_Leg', em=True)
    cmds.parent(locGrp2, root)
    leg = cmds.spaceLocator(n='loc_leg')
    cmds.move(.42, 1.15, -.35)
    cmds.scale(.5, .5, .5)
    cmds.parent(leg, locGrp2)

    knee = cmds.spaceLocator(n='loc_leg_knee')
    cmds.move(.5, .57, -.15)
    cmds.scale(.5, .5, .5)
    cmds.parent(knee, locGrp2)

    ankle = cmds.spaceLocator(n='loc_leg_ankle')
    cmds.move(.5, .16, .12)
    cmds.scale(.5, .5, .5)
    cmds.parent(ankle, locGrp2)

    #duplicate and rename left leg locators for the right side
    cmds.select(locGrp2)
    cmds.duplicate(n='Locators_Right_Leg', rr=True, rc=True)
    cmds.scale(-2, 2, 2)
    print 'locators created'
    def testDuplicate(self):
        '''Duplicate Maya and USD objects.'''

        # Select two objects, one Maya, one USD.
        spherePath = ufe.Path(mayaUtils.createUfePathSegment("|pSphere1"))
        sphereItem = ufe.Hierarchy.createItem(spherePath)
        sphereHierarchy = ufe.Hierarchy.hierarchy(sphereItem)
        worldItem = sphereHierarchy.parent()

        ball35Path = ufe.Path([
            mayaUtils.createUfePathSegment("|transform1|proxyShape1"),
            usdUtils.createUfePathSegment("/Room_set/Props/Ball_35")
        ])
        ball35Item = ufe.Hierarchy.createItem(ball35Path)
        ball35Hierarchy = ufe.Hierarchy.hierarchy(ball35Item)
        propsItem = ball35Hierarchy.parent()

        worldHierarchy = ufe.Hierarchy.hierarchy(worldItem)
        worldChildrenPre = worldHierarchy.children()
        propsHierarchy = ufe.Hierarchy.hierarchy(propsItem)
        propsChildrenPre = propsHierarchy.children()

        ufe.GlobalSelection.get().append(sphereItem)
        ufe.GlobalSelection.get().append(ball35Item)

        # Set the edit target to the layer in which Ball_35 is defined (has a
        # primSpec, in USD terminology).  Otherwise, duplication will not find
        # a source primSpec to copy.  Layers are the (anonymous) session layer,
        # the root layer, then the Assembly_room_set sublayer.  Trying to find
        # the layer by name is not practical, as it requires the full path
        # name, which potentially differs per run-time environment.
        ball35Prim = usdUtils.getPrimFromSceneItem(ball35Item)
        stage = ball35Prim.GetStage()

        layer = stage.GetLayerStack()[2]
        stage.SetEditTarget(layer)

        cmds.duplicate()

        # The duplicate command doesn't return duplicated non-Maya UFE objects.
        # They are in the selection, in the same order as the sources.
        snIter = iter(ufe.GlobalSelection.get())
        sphereDupItem = next(snIter)
        sphereDupName = str(sphereDupItem.path().back())
        ball35DupItem = next(snIter)
        ball35DupName = str(ball35DupItem.path().back())

        worldChildren = worldHierarchy.children()
        propsChildren = propsHierarchy.children()

        self.assertEqual(len(worldChildren) - len(worldChildrenPre), 1)
        self.assertEqual(len(propsChildren) - len(propsChildrenPre), 1)

        self.assertIn(sphereDupItem, worldChildren)
        self.assertIn(ball35DupItem, propsChildren)

        cmds.undo()

        # The duplicated items should no longer appear in the child list of
        # their parents.

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

        worldHierarchy = ufe.Hierarchy.hierarchy(worldItem)
        worldChildren = worldHierarchy.children()
        propsHierarchy = ufe.Hierarchy.hierarchy(propsItem)
        propsChildren = propsHierarchy.children()

        worldChildrenNames = childrenNames(worldChildren)
        propsChildrenNames = childrenNames(propsChildren)

        self.assertNotIn(sphereDupName, worldChildrenNames)
        self.assertNotIn(ball35DupName, propsChildrenNames)

        # The duplicated items shoudl reappear after a redo
        cmds.redo()

        snIter = iter(ufe.GlobalSelection.get())
        sphereDupItem = next(snIter)
        ball35DupItem = next(snIter)

        worldChildren = worldHierarchy.children()
        propsChildren = propsHierarchy.children()

        self.assertEqual(len(worldChildren) - len(worldChildrenPre), 1)
        self.assertEqual(len(propsChildren) - len(propsChildrenPre), 1)

        self.assertIn(sphereDupItem, worldChildren)
        self.assertIn(ball35DupItem, propsChildren)

        cmds.undo()

        # The duplicated items should not be assigned to the name of a
        # deactivated USD item.

        cmds.select(clear=True)

        # Delete the even numbered props:
        evenPropsChildrenPre = propsChildrenPre[0:35:2]
        for propChild in evenPropsChildrenPre:
            ufe.GlobalSelection.get().append(propChild)
        cmds.delete()

        worldHierarchy = ufe.Hierarchy.hierarchy(worldItem)
        worldChildren = worldHierarchy.children()
        propsHierarchy = ufe.Hierarchy.hierarchy(propsItem)
        propsChildren = propsHierarchy.children()
        propsChildrenPostDel = propsHierarchy.children()

        # Duplicate Ball_1
        ufe.GlobalSelection.get().append(propsChildrenPostDel[0])

        cmds.duplicate()

        snIter = iter(ufe.GlobalSelection.get())
        ballDupItem = next(snIter)
        ballDupName = str(ballDupItem.path().back())

        self.assertNotIn(ballDupItem, propsChildrenPostDel)
        self.assertNotIn(ballDupName, propsChildrenNames)
        self.assertEqual(ballDupName, "Ball_36")

        cmds.undo()  # undo duplication
        cmds.undo()  # undo deletion
Exemplo n.º 54
0
def makeHeadStreatch(jointCount=5):
    # -> testing guide
    if not getHeadStreatchGuide(): return

    # -> make curve
    attachCurve = makeAttachCurve()
    upVectorCurve = mc.duplicate(attachCurve)[0]
    baseDistanceCurve = mc.duplicate(attachCurve)[0]

    # -> move up vector curve
    mc.move(mc.arclen(upVectorCurve, ch=False) / 18,
            0,
            0,
            upVectorCurve,
            r=True)

    # -> make joints
    Joints, upLocators = makeAttachJoints(attachCurve, upVectorCurve,
                                          jointCount)

    moreWeghtJnt = mc.createNode('joint')
    mc.delete(mc.parentConstraint(Joints[0], moreWeghtJnt))
    mc.setAttr('%s.radius' % moreWeghtJnt, 1.5)

    # -> make bend Joints
    BendJoints = []
    for i, jnt in enumerate(Joints):
        BendJoints.append(mc.createNode('joint'))
        mc.delete(mc.parentConstraint(jnt, BendJoints[i]))
        mc.makeIdentity(BendJoints[i], t=True, r=True, s=True, apply=True)
        if i > 0:
            mc.parent(BendJoints[i], BendJoints[i - 1])

    # -> make streatch
    #-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    distanceValueNode = mc.arclen(attachCurve, ch=True)
    baseValueNode = mc.arclen(baseDistanceCurve, ch=True)

    divdeNode = mc.createNode('multiplyDivide')

    for attr in ('input2X', 'input1Y', 'input2Z'):
        mc.connectAttr('%s.arcLength' % distanceValueNode,
                       '%s.%s' % (divdeNode, attr))

    for attr in ('input1X', 'input2Y', 'input1Z'):
        mc.connectAttr('%s.arcLength' % baseValueNode,
                       '%s.%s' % (divdeNode, attr))

    mc.setAttr('%s.operation' % divdeNode, 2)

    for jnt in Joints:
        for attr in 'XYZ':
            mc.connectAttr('%s.output%s' % (divdeNode, attr),
                           '%s.scale%s' % (jnt, attr))
    #  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    DisStartLocator = mc.spaceLocator(p=(0, 0, 0))[0]
    DisEndLocator = mc.spaceLocator(p=(0, 0, 0))[0]
    DistanceNode = mc.createNode('distanceBetween')
    DisDivideNode = mc.createNode('multiplyDivide')

    mc.delete(mc.parentConstraint(BendJoints[0], DisStartLocator))
    mc.delete(mc.parentConstraint(BendJoints[-1], DisEndLocator))

    mc.connectAttr(
        '%s.worldPosition[0]' %
        mc.listRelatives(DisStartLocator, s=True, path=True)[0],
        '%s.point1' % DistanceNode)
    mc.connectAttr(
        '%s.worldPosition[0]' %
        mc.listRelatives(DisEndLocator, s=True, path=True)[0],
        '%s.point2' % DistanceNode)

    mc.connectAttr('%s.distance' % DistanceNode, '%s.input1Y' % DisDivideNode)
    mc.setAttr('%s.input2Y' % DisDivideNode,
               mc.getAttr('%s.input1Y' % DisDivideNode))
    mc.setAttr('%s.operation' % DisDivideNode, 2)

    for jnt in BendJoints:
        mc.connectAttr('%s.outputY' % DisDivideNode, '%s.sy' % jnt)
    #-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

    # -> Rig
    # - bend joints -
    #BendIKHandle = mc.ikHandle(sj=BendJoints[0], ee=BendJoints[1])
    VectorLoc = mc.spaceLocator(p=(0, 0, 0))[0]

    mc.delete(mc.parentConstraint(Joints[0], VectorLoc))
    mc.move(mc.arclen(upVectorCurve, ch=False) / 18, 0, 0, VectorLoc, r=True)

    for i, jnt in enumerate(BendJoints):
        if i > 0:
            mc.connectAttr('%s.rotate' % BendJoints[0], '%s.rotate' % jnt)

    # - skin bind Curve -
    mc.skinCluster(BendJoints, attachCurve)
    mc.skinCluster(BendJoints, upVectorCurve)

    # - make Cotrol -
    localStartControl = mc.circle(nr=(0, 1, 0), ch=False)[0]
    localEndControl = mc.circle(nr=(0, 1, 0), ch=False)[0]

    localStartControlGrp = mc.group(localStartControl)
    localEndControlGrp = mc.group(localEndControl)

    startControl = mc.circle(nr=(0, 1, 0), ch=False)[0]
    endControl = mc.circle(nr=(0, 1, 0), ch=False)[0]

    startControlGrp = mc.group(startControl)
    endControlGrp = mc.group(endControl)

    #  - match position -
    mc.delete(mc.parentConstraint(Joints[0], localStartControlGrp))
    mc.delete(mc.parentConstraint(Joints[-1], localEndControlGrp))

    mc.delete(mc.parentConstraint(Joints[0], startControlGrp))
    mc.delete(mc.parentConstraint(Joints[-1], endControlGrp))

    # - add Attribute -
    mc.addAttr(endControl, ln='range', min=0, max=3, dv=1)
    mc.setAttr('%s.range' % endControl, k=False, cb=True)

    # - connect -
    for i, attr in enumerate(
        ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v')):

        mc.connectAttr('%s.%s' % (startControl, attr),
                       '%s.%s' % (localStartControl, attr))

        if i < 3:
            multiNode = mc.createNode('multDoubleLinear')
            mc.connectAttr('%s.%s' % (endControl, attr),
                           '%s.input1' % multiNode)
            mc.connectAttr('%s.range' % endControl, '%s.input2' % multiNode)
            mc.connectAttr('%s.output' % multiNode,
                           '%s.%s' % (localEndControl, attr))
        else:
            mc.connectAttr('%s.%s' % (endControl, attr),
                           '%s.%s' % (localEndControl, attr))

        if i > 2:
            mc.setAttr('%s.%s' % (startControl, attr), l=True, k=False)
            mc.setAttr('%s.%s' % (endControl, attr), l=True, k=False)

    # - constraint -
    mc.pointConstraint(localStartControl, BendJoints[0])
    mc.aimConstraint(localEndControl,
                     BendJoints[0],
                     aim=(0, 1, 0),
                     wu=(1, 0, 0),
                     wuo=VectorLoc,
                     wut='object')
    # -> Compile
    JointGrp = mc.group(Joints, moreWeghtJnt)
    LocatorGrp = mc.group(upLocators)
    CurveGrp = mc.group(attachCurve, upVectorCurve, baseDistanceCurve)

    BendJointGrp = mc.group(BendJoints[0])

    controlGrp = mc.group(startControlGrp, endControlGrp)
    localControlGrp = mc.group(localStartControlGrp, localEndControlGrp)
    setGrp = mc.group(JointGrp, BendJointGrp, LocatorGrp, CurveGrp)

    rootGrp = mc.group(controlGrp, localControlGrp, setGrp)

    mc.parent(DisStartLocator, localStartControl)
    mc.parent(DisEndLocator, localEndControl)

    mc.parent(VectorLoc, localStartControl)

    # -> rename
    # - bend set -
    DisStartLocator = mc.rename(DisStartLocator, 'C_HSbendDisStart_loc_0')
    DisEndLocator = mc.rename(DisEndLocator, 'C_HSbendDisEnd_loc_0')

    for i, jnt in enumerate(BendJoints):
        BendJoints[i] = mc.rename(jnt,
                                  'C_HSbend%s_jnt_0' % string.uppercase[i])
    BendJointGrp = mc.rename(BendJointGrp, 'C_HSbendJoint_jnh_0')

    VectorLoc = mc.rename(VectorLoc, 'C_HSBendVector_loc_0')
    # - joint -
    for i, jnt in enumerate(Joints):
        Joints[i] = mc.rename(jnt,
                              'C_headStreatch%s_bnd_0' % string.uppercase[i])

    moreWeghtJnt = mc.rename(moreWeghtJnt, 'C_headStreatch_bnd_0')
    JointGrp = mc.rename(JointGrp, 'C_headStreatch_bndG_0')

    # - locator -
    for i, loc in enumerate(upLocators):
        upLocators[i] = mc.rename(
            loc, 'C_headStreatchUp%s_loc_0' % string.uppercase[i])

    mc.rename(LocatorGrp, 'C_headStreatch_locG_0')

    # - control -
    startControl = mc.rename(startControl, 'C_HSstart_ctl_0')
    endControl = mc.rename(endControl, 'C_HSend_ctl_0')

    startControlGrp = mc.rename(startControlGrp, 'C_HSstart_cth_0')
    endControlGrp = mc.rename(endControlGrp, 'C_HSend_cth_0')

    localStartControl = mc.rename(localStartControl, 'C_HSstartLocal_ctl_0')
    localEndControl = mc.rename(localEndControl, 'C_HSendLocal_ctl_0')

    localStartControlGrp = mc.rename(localStartControlGrp,
                                     'C_HSstartLocal_cth_0')
    localEndControlGrp = mc.rename(localEndControlGrp, 'C_HSendLocal_cth_0')

    controlGrp = mc.rename(controlGrp, 'C_headStreatch_cth_0')
    localControlGrp = mc.rename(localControlGrp, 'C_headStreatchLocal_cth_0')

    # - curve -
    attachCurve = mc.rename(attachCurve, 'C_HSJointAttach_cus_0')
    upVectorCurve = mc.rename(upVectorCurve, 'C_HSLocatorAttach_cus_0')
    baseDistanceCurve = mc.rename(baseDistanceCurve, 'C_HSDistance_cus_0')

    mc.rename(CurveGrp, 'C_HeadStreatch_cusgrp_0')

    # - comp group -
    mc.rename(setGrp, 'C_headStreatch_setg_0')
    mc.rename(rootGrp, 'C_headStreatch_grp_0')

    # -> clean up
    mc.hide(upLocators)
    mc.hide(upVectorCurve, baseDistanceCurve)
    mc.hide(localControlGrp)
    mc.hide(BendJointGrp)

    mc.setAttr('%s.template' % attachCurve, 1)

    # -> create selection sets
    mc.sets(Joints, moreWeghtJnt, name='C_HSJoint_set_0')
    mc.sets(startControl, endControl, name='C_HSControl_set_0')
Exemplo n.º 55
0
def recreateJoints():
    if not cmds.objExists("loc_Grp_1"):
        print "You must generate a skeleton first!"
    else:

        locList = []
        cmds.duplicate("loc_Grp_1", rc=True)
        locsDup = []
        cmds.group(n="loc_Grp_dup", em=True)

        for pc in cmds.listRelatives("loc_Grp_2", ad=True):
            if "parentConstraint2" in pc:
                cmds.delete(pc)
            else:
                print "didnt find pc"
                if "Shape" in pc:
                    print "this is shape"
                else:
                    locsDup.append(pc)
                    cmds.parent(pc, "loc_Grp_dup")
        for loc in cmds.listRelatives("loc_Grp_dup"):
            cmds.select(loc)
            for item in pm.selected():
                if "tail" in loc:
                    print "skippy"
                elif "4" in item:
                    item.rename(item.name().replace('4', '11'))
                elif "5" in loc:
                    item.rename(item.name().replace('5', '21'))
                elif "6" in loc:
                    item.rename(item.name().replace('6', '31'))
                else:
                    print "nope"
                '''
                if item == "loc_spine11":
                    item.rename(item.name().replace('11','21'))
                    
                if item == "loc_spine3":
                    item.rename(item.name().replace('spine3','spine11'))
                '''

        cmds.delete("loc_Grp_2")
        cmds.group(n="new_dup_Grp", em=True)
        for i in cmds.listRelatives("loc_Grp_dup"):
            #aimLocs = cmds.listRelatives(i,p=1)
            #aimLocsPar = cmds.listRelatives(i,p=1)
            if "L_" in i:
                print i
                new_dup = cmds.duplicate(i, n=i + "moved")
                cmds.parent(new_dup, 'new_dup_Grp')
                cmds.xform(os=True, r=True, t=(0, 1, 0))

        for obj in cmds.listRelatives("loc_Grp_1", ad=True, type="locator"):
            #print obj
            locs = cmds.listRelatives(obj, p=1)
            locsPar = cmds.listRelatives(locs, p=True)
            #print locs[0] + " is the child"
            #print locsPar[0] + " is the parent"
            if locs[0] == "loc_root_joint":
                locList.append(locs[0])
            elif locs[0] == "loc_Grp_1":
                print locs[0]
            elif locsPar[0] == "loc_Grp_1":
                print locsPar[0]
            else:
                if "11" in locs[0] or "11" in locsPar[0]:
                    print "no par"
                elif not cmds.objExists(locs[0] +
                                        "1") or not cmds.objExists(locsPar[0] +
                                                                   "1"):
                    print "no exists"
                else:
                    if "L_" not in locs[0] or "L_" not in locsPar[0]:
                        print "THIS IS THE FLAG YOURE LOOKING FOR       :         " + locs[
                            0] + " ----->" + locsPar[0]
                        #aimToDel = cmds.aimConstraint(locs[0] + "1",locsPar[0] + "1",wuo=locs[0] + "1" + "moved")
                        #cmds.delete(aimToDel)
                        cmds.parent(locs[0] + "1", locsPar[0] + "1")
                        locList.append(locs[0])
                    elif "hand" in locsPar[0]:
                        print "THIS IS THE HAND : " + locsPar[0]
                        cmds.parent(locs[0] + "1", locsPar[0] + "1")
                        locList.append(locs[0])
                    else:
                        print "THIS IS THE FLAG SAYING NOT L        :      " + locs[
                            0] + "=====>" + locsPar[0]
                        aimToDel = cmds.aimConstraint(locs[0] + "1",
                                                      locsPar[0] + "1",
                                                      wuo=locsPar[0] + "1" +
                                                      "moved",
                                                      u=(0, 1, 0),
                                                      aim=(1, 0, 0),
                                                      wut="object")
                        cmds.delete(aimToDel)
                        cmds.parent(locs[0] + "1", locsPar[0] + "1")
                        locList.append(locs[0])
        cmds.delete('new_dup_Grp')
        jointGroup = []
        newLocList = []
        newJointList = []
        counterJoint = 1
        newJointGroup = cmds.group(n="joint_group", em=True)
        '''
        for locator in locList:
            print locator
            if "_R_" in locator:
                print "bad loc"
            else:
                if locator not in newLocList:
                    print locator
                    newLocList.append(locator)
                else:
                    print " its in list"
        '''
        posture = ''
        for fix in cmds.listRelatives("loc_Grp_dup", ad=True, type="locator"):
            fixNew = cmds.listRelatives(fix, p=True)
            newLocList.append(fixNew)

        if "hock" in str(newLocList):
            posture = "quadruped"
        elif "hock" not in str(newLocList):
            print "asd"
            posture = "biped"

        print locList
        print newLocList
        for l in newLocList:
            print "JUST STARTESDFSJDGSDFJG"
            print l

            cmds.select(cl=True)
            locPos = []
            locRot = []
            locPos.append(cmds.xform(l, q=True, ws=True, t=True))
            locRot.append(cmds.xform(l, q=True, ws=True, ro=True))
            newJoint = cmds.joint(n="joint_" + l[0], p=locPos[0], o=locRot[0])
            jointGroup.append(newJoint)
            print "just made " + newJoint
            newJointList.append(newJoint)
            cmds.parent(newJoint, newJointGroup)
            print "just parented " + newJoint + " to : " + newJointGroup
        for jtl in newLocList:
            getJointParent = cmds.listRelatives(jtl, p=True)
            print getJointParent[0] + " THIS IS THE PARENT"
            print jtl[0] + " THIS IS THE CHILD"
            if not getJointParent:
                print "no parent"
            else:
                properJointParent = "joint_" + getJointParent[-1]
                properJointChild = newJointList[counterJoint]

                if "joint_loc_Grp_dup" in properJointParent or "joint_loc_Grp_dup" in properJointChild:
                    print "top of chain"
                else:
                    print "it dont work"
                    print properJointChild + "      ch"
                    print properJointParent + "     par"
                    cmds.parent(properJointChild, properJointParent, a=True)
                    counterJoint += 1
        print posture
        if posture == "biped":
            shoulderNames = ["clav"]
        else:
            shoulderNames = ["clav", "shoulder"]

        thighNames = ["thigh", "hip"]
        for jx in newLocList:
            print jx[0]
            jxPar = cmds.listRelatives(jx[0], p=True)
            if ("_L_" in jx[0] or "L_" in jx[0]) and ("_L_" not in jxPar
                                                      or "L_" not in jxPar):
                for name in shoulderNames:
                    if name in jx[0]:
                        clav_mirror = cmds.select("joint_" + jx[0])
                        sel = cmds.ls(sl=True)
                        cmds.mirrorJoint(clav_mirror,
                                         mb=True,
                                         myz=True,
                                         sr=("L_", "R_"))
                for oName in thighNames:
                    if oName in jx[0]:
                        thigh_mirror = cmds.select("joint_" + jx[0])
                        sel = cmds.ls(sl=True)
                        cmds.mirrorJoint(thigh_mirror,
                                         mb=True,
                                         myz=True,
                                         sr=("L_", "R_"))
                else:
                    print "not right"

        #cmds.mirrorJoint(clav_mirror,mb=True, myz=True, sr = ("L_","R_"))
        #thigh_mirror = cmds.select("joint_loc_L_thigh_joint1")
        #cmds.mirrorJoint(thigh_mirror,mb=True, myz=True, sr = ("L_","R_"))

        cmds.delete("loc_Grp_1")
        cmds.delete("obj_group_1")
        cmds.delete("loc_Grp_dup")
    cmds.select('joint_loc_root_joint1')
    print "THIS IS THE NEW SCRIPT!!!!!!!"
# Importing the Maya command set.
import maya.cmds as cmds

# Creating snowman base
cmds.polySphere(r=True, sx=20, sy=20, ax=[0, 1, 0], cuv=2, ch=1)
# Result: pSphere1 polySphere1 #
cmds.duplicate(rr=True)
# Result: pSphere2 #
cmds.move(0, 1.831615, 0, r=True, os=True, wd=True)
cmds.scale(0.687349, 0.687349, 0.687349, r=True)
cmds.move(0, -0.244511, 0, r=True, os=True, wd=True)
cmds.duplicate(rr=True)
# Result: pSphere3 #
cmds.move(0, 1.1459, 0, r=True, os=True, wd=True)
cmds.scale(0.758657, 0.758657, 0.758657, r=True)
cmds.move(0, -0.127419, 0, r=True, os=True, wd=True)
cmds.select('pSphere2', tgl=True)
cmds.move(0, -0.245208, 0, r=True, os=True, wd=True)
cmds.select(clear=True)
cmds.select('pSphere1', r=True)
cmds.scale(0.91359, 0.91359, 0.91359, r=True)
cmds.move(0, 0.123063, 0, r=True, os=True, wd=True)
cmds.scale(0.946528, 0.946528, 0.946528, r=True)
cmds.select('pSphere2', r=True)
cmds.scale(1.03269, 1.03269, 1.03269, r=True)
cmds.select(clear=True)

# Creating the eyes
cmds.select('pSphere3', r=True)
cmds.duplicate(rr=True)
# Result: pSphere4 #
Exemplo n.º 57
0
import sys
sys.path.append(r"C:\Program Files\Autodesk\Maya2016\Python\Lib\site-packages")

from os.path import join

from maya.standalone import initialize
import maya.cmds as cmds
import maya.mel as mel

initialize("python")
origPath = "H:/Windows/Desktop/headlessTest.ma"

cmds.file(origPath, open=True)

mySphere = "pSphere1"
cmds.duplicate(mySphere)
cmds.xform(mySphere, ws=True, t=(3, 3, 3))

newName = "NEWTEST.ma"
path = join("H:/Windows/Desktop", newName)
fileName = cmds.file(rename=path)

cmds.file(s=True)
Exemplo n.º 58
0
    def sqGenerateCurves(self, *args):
        self.edgeList = cmds.ls(selection=True, flatten=True)
        if not self.edgeList == None and not self.edgeList == [] and not self.edgeList == "":
            self.baseCurve = cmds.polyToCurve(name="baseCurve",
                                              form=2,
                                              degree=1)[0]
            cmds.select(self.baseCurve + ".ep[*]")
            cmds.insertKnotCurve(cmds.ls(selection=True, flatten=True),
                                 constructionHistory=True,
                                 curveOnSurface=True,
                                 numberOfKnots=1,
                                 addKnots=False,
                                 insertBetween=True,
                                 replaceOriginal=True)

            pointListA, pointListB, sideA, sideB = self.sqGetPointLists()

            toDeleteList = []
            p = 2
            for k in range((sideA + 2), (sideB - 1)):
                if p % 2 == 0:
                    toDeleteList.append(self.baseCurve + ".cv[" + str(k) + "]")
                    toDeleteList.append(self.baseCurve + ".cv[" +
                                        str(k + len(pointListA) - 1) + "]")
                p = p + 1
            q = 2
            m = sideA - 2
            if m >= 0:
                while m >= 0:
                    if not m == sideA and not m == sideB:
                        if q % 2 == 0:
                            toDeleteList.append(self.baseCurve + ".cv[" +
                                                str(m) + "]")
                    m = m - 1
                    q = q + 1

            cmds.delete(toDeleteList)
            cmds.insertKnotCurve([
                self.baseCurve + ".u[" + str(len(pointListA) - 1) + "]",
                self.baseCurve + ".ep[" + str(len(pointListA) - 1) + "]"
            ],
                                 constructionHistory=True,
                                 curveOnSurface=True,
                                 numberOfKnots=1,
                                 addKnots=False,
                                 insertBetween=True,
                                 replaceOriginal=True)

            pointListA, pointListB, sideA, sideB = self.sqGetPointLists()

            posListA, posListB = [], []
            for i in range(0, len(pointListA) - 1):
                posListA.append(
                    cmds.xform(pointListA[i],
                               query=True,
                               worldSpace=True,
                               translation=True))
                posListB.append(
                    cmds.xform(pointListB[i],
                               query=True,
                               worldSpace=True,
                               translation=True))

            self.mainCurveA = cmds.curve(name="StickyLips_Main_A_Crv",
                                         degree=1,
                                         point=posListA)
            self.mainCurveB = cmds.curve(name="StickyLips_Main_B_Crv",
                                         degree=1,
                                         point=posListB)

            cmds.rename(
                cmds.listRelatives(self.mainCurveA, children=True,
                                   shapes=True)[0], self.mainCurveA + "Shape")
            cmds.rename(
                cmds.listRelatives(self.mainCurveB, children=True,
                                   shapes=True)[0], self.mainCurveB + "Shape")

            cmds.select(self.mainCurveA + ".cv[*]")
            self.curveLenght = len(cmds.ls(selection=True, flatten=True))
            cmds.select(clear=True)

            self.sqCheckCurveDirection(self.mainCurveA)
            self.sqCheckCurveDirection(self.mainCurveB)

            self.baseCurveA = cmds.duplicate(self.mainCurveA,
                                             name=self.mainCurveA.replace(
                                                 "_Main_", "_Base_"))[0]
            self.baseCurveB = cmds.duplicate(self.mainCurveB,
                                             name=self.mainCurveB.replace(
                                                 "_Main_", "_Base_"))[0]

            cmds.delete(self.baseCurve)
            self.maxIter = len(posListA)

            cmds.group(self.mainCurveA,
                       self.mainCurveB,
                       self.baseCurveA,
                       self.baseCurveB,
                       name="StickyLips_StaticData_Grp")
        else:
            mel.eval("warning \"Please, select an closed edgeLoop.\";")
Exemplo n.º 59
0
def invert(base=None, corrective=None, name=None):
    """Inverts a shape through the deformation chain.

    @param[in] base Deformed base mesh.
    @param[in] corrective Sculpted corrective mesh.
    @param[in] name Name of the generated inverted shape.
    @return The name of the inverted shape.
    """
    cmds.loadPlugin('cvshapeinverter_plugin.py', qt=True)
    if not base or not corrective:
        sel = cmds.ls(sl=True)
        if not sel or len(sel) != 2:
            cmds.undoInfo(closeChunk=True)
            raise RuntimeError, 'Select base then corrective'
        base, corrective = sel

    # Get points on base mesh
    base_points = get_points(base)
    point_count = base_points.length()

    # Get points on corrective mesh
    corrective_points = get_points(corrective)

    # Get the intermediate mesh
    orig_mesh = get_shape(base, intermediate=True)

    # Get the component offset axes
    orig_points = get_points(orig_mesh)
    x_points = OpenMaya.MPointArray(orig_points)
    y_points = OpenMaya.MPointArray(orig_points)
    z_points = OpenMaya.MPointArray(orig_points)

    cmds.undoInfo(openChunk=True)
    for i in range(point_count):
        x_points[i].x += 1.0
        y_points[i].y += 1.0
        z_points[i].z += 1.0
    set_points(orig_mesh, x_points)
    x_points = get_points(base)
    set_points(orig_mesh, y_points)
    y_points = get_points(base)
    set_points(orig_mesh, z_points)
    z_points = get_points(base)
    set_points(orig_mesh, orig_points)

    # Create the mesh to get the inversion deformer
    if not name:
        name = '%s_inverted' % corrective

    inverted_shapes = cmds.duplicate(base, name=name)[0]
    # Delete the unnessary shapes
    shapes = cmds.listRelatives(inverted_shapes, children=True, shapes=True, path=True)
    for s in shapes:
        if cmds.getAttr('%s.intermediateObject' % s):
            cmds.delete(s)
    set_points(inverted_shapes, orig_points)
    # Unlock the transformation attrs
    for attr in 'trs':
        for x in 'xyz':
            cmds.setAttr('%s.%s%s' % (inverted_shapes, attr, x), lock=False)
    cmds.setAttr('%s.visibility' % inverted_shapes, 1)
    deformer = cmds.deformer(inverted_shapes, type='cvShapeInverter')[0]

    # Calculate the inversion matrices
    deformer_mobj = get_mobject(deformer)
    fn_deformer = OpenMaya.MFnDependencyNode(deformer_mobj)
    plug_matrix = fn_deformer.findPlug('inversionMatrix', False)
    fn_matrix_data = OpenMaya.MFnMatrixData()
    for i in range(point_count):
        matrix = OpenMaya.MMatrix()
        set_matrix_row(matrix, x_points[i] - base_points[i], 0)
        set_matrix_row(matrix, y_points[i] - base_points[i], 1)
        set_matrix_row(matrix, z_points[i] - base_points[i], 2)
        set_matrix_row(matrix, corrective_points[i], 3)
        matrix = matrix.inverse()
        matrix_mobj = fn_matrix_data.create(matrix)

        plug_matrixElement = plug_matrix.elementByLogicalIndex(i)
        plug_matrixElement.setMObject(matrix_mobj)

    # Store the base points.
    fn_point_data = OpenMaya.MFnPointArrayData()
    point_data_mobj = fn_point_data.create(base_points)
    plug_deformed_points = fn_deformer.findPlug('deformedPoints', False)
    plug_deformed_points.setMObject(point_data_mobj)

    cmds.connectAttr('%s.outMesh' % get_shape(corrective), '%s.correctiveMesh' % deformer)

    cmds.undoInfo(closeChunk=True)
    return inverted_shapes
Exemplo n.º 60
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
            # create lists to be integrated:
            # 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:
                        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)
                # 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):
                # redeclaring variables:
                self.base = side + self.userGuideName + "_Guide_Base"
                self.cvFootLoc = side + self.userGuideName + "_Guide_Foot"
                self.cvRFALoc = side + self.userGuideName + "_Guide_RfA"
                self.cvRFBLoc = side + self.userGuideName + "_Guide_RfB"
                self.cvRFCLoc = side + self.userGuideName + "_Guide_RfC"
                self.cvRFDLoc = side + self.userGuideName + "_Guide_RfD"
                self.cvRFELoc = side + self.userGuideName + "_Guide_RfE"
                self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd"

                # declaring attributes reading from dictionary:
                ankleRFAttr = self.langDic[self.langName]['c009_leg_extrem']
                middleRFAttr = self.langDic[
                    self.langName]['c017_RevFoot_middle']
                outsideRFAttr = self.langDic[self.langName]['c010_RevFoot_A']
                insideRFAttr = self.langDic[self.langName]['c011_RevFoot_B']
                heelRFAttr = self.langDic[self.langName]['c012_RevFoot_C']
                toeRFAttr = self.langDic[self.langName]['c013_RevFoot_D']
                ballRFAttr = self.langDic[self.langName]['c014_RevFoot_E']
                footRFAttr = self.langDic[self.langName]['c015_RevFoot_F']
                sideRFAttr = self.langDic[self.langName]['c016_RevFoot_G']
                rfRoll = self.langDic[
                    self.langName]['c018_RevFoot_roll'].capitalize()
                rfSpin = self.langDic[
                    self.langName]['c019_RevFoot_spin'].capitalize()
                rfTurn = self.langDic[
                    self.langName]['c020_RevFoot_turn'].capitalize()
                rfAngle = self.langDic[
                    self.langName]['c102_angle'].capitalize()
                rfPlant = self.langDic[
                    self.langName]['c103_plant'].capitalize()
                showCtrlsAttr = self.langDic[
                    self.langName]['c021_showControls']

                # creating joints:
                cmds.select(clear=True)
                self.footJnt = cmds.joint(name=side + self.userGuideName +
                                          "_" + ankleRFAttr.capitalize() +
                                          "_Jnt")
                utils.setJointLabel(
                    self.footJnt, s + jointLabelAdd, 18,
                    self.userGuideName + "_" + ankleRFAttr.capitalize())
                self.middleFootJxt = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    middleRFAttr.capitalize() + "_Jxt")
                self.endJnt = cmds.joint(name=side + self.userGuideName +
                                         "_JEnd")
                cmds.select(clear=True)
                self.middleFootJnt = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    middleRFAttr.capitalize() + "_Jnt")
                utils.setJointLabel(
                    self.middleFootJnt, s + jointLabelAdd, 18,
                    self.userGuideName + "_" + middleRFAttr.capitalize())
                self.endBJnt = cmds.joint(name=side + self.userGuideName +
                                          "B_JEnd")
                cmds.parent(self.middleFootJnt, self.middleFootJxt)
                cmds.addAttr(self.footJnt,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                cmds.addAttr(self.middleFootJnt,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                cmds.select(clear=True)
                '''
                Deactivate the segment scale compensate on the bone to prevent scaling problem in maya 2016
                It will prevent a double scale problem that will come from the upper parent in the rig
                '''
                if (int(cmds.about(version=True)[:4]) >= 2016):
                    cmds.setAttr(self.footJnt + ".segmentScaleCompensate", 0)
                    cmds.setAttr(
                        self.middleFootJxt + ".segmentScaleCompensate", 0)
                    cmds.setAttr(
                        self.middleFootJnt + ".segmentScaleCompensate", 0)

                # reverse foot controls:
                self.RFACtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" +
                    outsideRFAttr.capitalize() + "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree)
                self.RFBCtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" +
                    insideRFAttr.capitalize() + "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree)
                self.RFCCtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" + heelRFAttr.capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree,
                    dir="+Y",
                    rot=(0, 90, 0))
                self.RFDCtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" + toeRFAttr.capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree,
                    dir="+Y",
                    rot=(0, 90, 0))
                self.RFECtrl = self.ctrls.cvControl(
                    "id_019_FootReverseE",
                    side + self.userGuideName + "_" + ballRFAttr.capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree,
                    rot=(0, 90, 0))

                # reverse foot groups:
                self.RFAGrp = cmds.group(self.RFACtrl,
                                         name=self.RFACtrl + "_Grp")
                self.RFBGrp = cmds.group(self.RFBCtrl,
                                         name=self.RFBCtrl + "_Grp")
                self.RFCGrp = cmds.group(self.RFCCtrl,
                                         name=self.RFCCtrl + "_Grp")
                self.RFDGrp = cmds.group(self.RFDCtrl,
                                         name=self.RFDCtrl + "_Grp")
                self.RFEGrp = cmds.group(self.RFECtrl,
                                         name=self.RFECtrl + "_Grp")
                rfGrpList = [
                    self.RFAGrp, self.RFBGrp, self.RFCGrp, self.RFDGrp,
                    self.RFEGrp
                ]
                self.ballRFList.append(self.RFEGrp)

                # putting groups in the correct place:
                tempToDelA = cmds.parentConstraint(self.cvFootLoc,
                                                   self.footJnt,
                                                   maintainOffset=False)
                tempToDelB = cmds.parentConstraint(self.cvRFELoc,
                                                   self.middleFootJxt,
                                                   maintainOffset=False)
                tempToDelC = cmds.parentConstraint(self.cvEndJoint,
                                                   self.endJnt,
                                                   maintainOffset=False)
                tempToDelD = cmds.parentConstraint(self.cvEndJoint,
                                                   self.endBJnt,
                                                   maintainOffset=False)
                tempToDelE = cmds.parentConstraint(self.cvRFALoc,
                                                   self.RFAGrp,
                                                   maintainOffset=False)
                tempToDelF = cmds.parentConstraint(self.cvRFBLoc,
                                                   self.RFBGrp,
                                                   maintainOffset=False)
                tempToDelG = cmds.parentConstraint(self.cvRFCLoc,
                                                   self.RFCGrp,
                                                   maintainOffset=False)
                tempToDelH = cmds.parentConstraint(self.cvRFDLoc,
                                                   self.RFDGrp,
                                                   maintainOffset=False)
                tempToDelI = cmds.parentConstraint(self.cvRFELoc,
                                                   self.RFEGrp,
                                                   maintainOffset=False)
                cmds.delete(tempToDelA, tempToDelB, tempToDelC, tempToDelD,
                            tempToDelE, tempToDelF, tempToDelG, tempToDelH,
                            tempToDelI)

                # mounting hierarchy:
                cmds.parent(self.RFBGrp, self.RFACtrl)
                cmds.parent(self.RFCGrp, self.RFBCtrl)
                cmds.parent(self.RFDGrp, self.RFCCtrl)
                cmds.parent(self.RFEGrp, self.RFDCtrl)

                # reverse foot zero out groups:
                self.RFEZero = utils.zeroOut([self.RFEGrp])[0]
                self.RFEZeroExtra = utils.zeroOut([self.RFEZero])[0]
                self.RFDZero = utils.zeroOut([self.RFDGrp])[0]
                self.RFCZero = utils.zeroOut([self.RFCGrp])[0]
                self.RFBZero = utils.zeroOut([self.RFBGrp])[0]
                self.RFAZero = utils.zeroOut([self.RFAGrp])[0]
                self.RFAZeroExtra = utils.zeroOut([self.RFAZero])[0]
                rfJointZeroList = [
                    self.RFAZero, self.RFBZero, self.RFCZero, self.RFDZero,
                    self.RFEZero
                ]

                # fixing side rool rotation order:
                cmds.setAttr(self.RFBZero + ".rotateOrder", 5)

                # creating ikHandles:
                ikHandleAnkleList = cmds.ikHandle(
                    name=side + self.userGuideName + "_" +
                    ankleRFAttr.capitalize() + "_IkHandle",
                    startJoint=self.footJnt,
                    endEffector=self.middleFootJxt,
                    solver='ikSCsolver')
                ikHandleMiddleList = cmds.ikHandle(
                    name=side + self.userGuideName + "_" +
                    middleRFAttr.capitalize() + "_IkHandle",
                    startJoint=self.middleFootJxt,
                    endEffector=self.endJnt,
                    solver='ikSCsolver')
                cmds.rename(ikHandleAnkleList[1],
                            ikHandleAnkleList[0] + "_Effector")
                cmds.rename(ikHandleMiddleList[1],
                            ikHandleMiddleList[0] + "_Effector")
                cmds.setAttr(ikHandleAnkleList[0] + '.visibility', 0)
                cmds.setAttr(ikHandleMiddleList[0] + '.visibility', 0)

                # creating Fk controls:
                self.footCtrl = self.ctrls.cvControl(
                    "id_020_FootFk",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c009_leg_extrem'] + "_Ctrl",
                    r=(self.ctrlRadius * 0.5),
                    d=self.curveDegree,
                    dir="+Z")
                self.footCtrlList.append(self.footCtrl)
                cmds.setAttr(self.footCtrl + ".rotateOrder", 1)

                self.revFootCtrlShapeList.append(
                    cmds.listRelatives(self.footCtrl,
                                       children=True,
                                       type='nurbsCurve')[0])

                self.middleFootCtrl = self.ctrls.cvControl(
                    "id_021_FootMiddle",
                    side + self.userGuideName + "_" + self.langDic[
                        self.langName]['c017_RevFoot_middle'].capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.5),
                    d=self.curveDegree)
                cmds.setAttr(self.middleFootCtrl + '.overrideEnabled', 1)
                cmds.setAttr(self.middleFootCtrl + ".rotateOrder", 4)
                tempToDelA = cmds.parentConstraint(self.cvFootLoc,
                                                   self.footCtrl,
                                                   maintainOffset=False)
                tempToDelB = cmds.parentConstraint(self.cvRFELoc,
                                                   self.middleFootCtrl,
                                                   maintainOffset=False)
                cmds.delete(tempToDelA, tempToDelB)
                if s == 1:
                    cmds.setAttr(self.middleFootCtrl + ".scaleX", -1)
                    cmds.setAttr(self.middleFootCtrl + ".scaleY", -1)
                    cmds.setAttr(self.middleFootCtrl + ".scaleZ", -1)
                self.footCtrlZeroList = utils.zeroOut(
                    [self.footCtrl, self.middleFootCtrl])
                self.middleFootCtrlList.append(self.middleFootCtrl)

                # mount hierarchy:
                cmds.parent(self.footCtrlZeroList[1],
                            self.RFDCtrl,
                            absolute=True)
                cmds.parent(ikHandleMiddleList[0],
                            self.middleFootCtrl,
                            absolute=True)
                self.toLimbIkHandleGrp = cmds.group(
                    empty=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c009_leg_extrem'] + "_Grp")
                self.toLimbIkHandleGrpList.append(self.toLimbIkHandleGrp)
                cmds.parent(ikHandleAnkleList[0],
                            self.toLimbIkHandleGrp,
                            self.RFECtrl,
                            absolute=True)
                cmds.makeIdentity(self.toLimbIkHandleGrp,
                                  apply=True,
                                  translate=True,
                                  rotate=True,
                                  scale=True)
                parentConst = cmds.parentConstraint(self.RFECtrl,
                                                    self.footJnt,
                                                    maintainOffset=True,
                                                    name=self.footJnt +
                                                    "_ParentConstraint")[0]
                self.parentConstList.append(parentConst)
                self.footJntList.append(self.footJnt)
                cmds.parent(self.RFAZeroExtra, self.footCtrl, absolute=True)

                scaleConst = cmds.scaleConstraint(self.footCtrl,
                                                  self.footJnt,
                                                  maintainOffset=True,
                                                  name=self.footJnt +
                                                  "_ScaleConstraint")
                self.scaleConstList.append(scaleConst)
                cmds.parentConstraint(self.middleFootCtrl,
                                      self.middleFootJnt,
                                      maintainOffset=True,
                                      name=self.middleFootJnt +
                                      "_ParentConstraint")
                cmds.scaleConstraint(self.middleFootCtrl,
                                     self.middleFootJnt,
                                     maintainOffset=True,
                                     name=self.middleFootJnt +
                                     "_ScaleConstraint")

                # add attributes to footCtrl and connect them to reverseFoot groups rotation:
                rfAttrList = [
                    outsideRFAttr, insideRFAttr, heelRFAttr, toeRFAttr,
                    ballRFAttr
                ]
                rfTypeAttrList = [rfRoll, rfSpin]
                for j, rfAttr in enumerate(rfAttrList):
                    for t, rfType in enumerate(rfTypeAttrList):
                        if t == 1 and j == (len(rfAttrList) -
                                            1):  # create turn attr to ball
                            cmds.addAttr(self.footCtrl,
                                         longName=rfAttr + rfTurn,
                                         attributeType='float',
                                         keyable=True)
                            cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                             rfTurn,
                                             rfGrpList[j] + ".rotateZ",
                                             force=True)
                            self.reverseFootAttrList.append(rfAttr + rfTurn)
                        cmds.addAttr(self.footCtrl,
                                     longName=rfAttr + rfType,
                                     attributeType='float',
                                     keyable=True)
                        self.reverseFootAttrList.append(rfAttr + rfType)
                        if t == 0:
                            if j > 1:
                                cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                                 rfType,
                                                 rfGrpList[j] + ".rotateX",
                                                 force=True)
                            else:
                                cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                                 rfType,
                                                 rfGrpList[j] + ".rotateZ",
                                                 force=True)
                        else:
                            cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                             rfType,
                                             rfGrpList[j] + ".rotateY",
                                             force=True)

                # creating the originedFrom attributes (in order to permit integrated parents in the future):
                utils.originedFrom(objName=self.footCtrl,
                                   attrString=self.base + ";" +
                                   self.cvFootLoc + ";" + self.cvRFALoc + ";" +
                                   self.cvRFBLoc + ";" + self.cvRFCLoc + ";" +
                                   self.cvRFDLoc)
                utils.originedFrom(objName=self.middleFootCtrl,
                                   attrString=self.cvRFELoc + ";" +
                                   self.cvEndJoint)

                # creating pre-defined attributes for footRoll and sideRoll attributes, also rollAngle:
                cmds.addAttr(self.footCtrl,
                             longName=footRFAttr + rfRoll,
                             attributeType='float',
                             keyable=True)
                cmds.addAttr(self.footCtrl,
                             longName=footRFAttr + rfRoll + rfAngle,
                             attributeType='float',
                             defaultValue=30,
                             keyable=True)
                cmds.addAttr(self.footCtrl,
                             longName=footRFAttr + rfRoll + rfPlant,
                             attributeType='float',
                             defaultValue=0,
                             keyable=True)
                cmds.addAttr(self.footCtrl,
                             longName=sideRFAttr + rfRoll,
                             attributeType='float',
                             keyable=True)

                # create clampNodes in order to limit the side rotations:
                sideClamp = cmds.createNode("clamp",
                                            name=side + self.userGuideName +
                                            "_Side_Clp")
                # outside values in R
                cmds.setAttr(sideClamp + ".minR", -360)
                # inside values in G
                cmds.setAttr(sideClamp + ".maxG", 360)
                # inverting sideRoll values:
                sideMD = cmds.createNode("multiplyDivide",
                                         name=side + self.userGuideName +
                                         "_Side_MD")
                cmds.setAttr(sideMD + ".input2X", -1)
                # connections:
                cmds.connectAttr(self.footCtrl + "." + sideRFAttr + rfRoll,
                                 sideMD + ".input1X",
                                 force=True)
                cmds.connectAttr(sideMD + ".outputX",
                                 sideClamp + ".inputR",
                                 force=True)
                cmds.connectAttr(sideMD + ".outputX",
                                 sideClamp + ".inputG",
                                 force=True)
                cmds.connectAttr(sideClamp + ".outputR",
                                 self.RFAZero + ".rotateZ",
                                 force=True)
                cmds.connectAttr(sideClamp + ".outputG",
                                 self.RFBZero + ".rotateZ",
                                 force=True)

                # for footRoll:
                footHeelClp = cmds.createNode("clamp",
                                              name=side + self.userGuideName +
                                              "_Roll_Heel_Clp")
                # heel values in R
                cmds.setAttr(footHeelClp + ".minR", -360)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footHeelClp + ".inputR",
                                 force=True)
                cmds.connectAttr(footHeelClp + ".outputR",
                                 self.RFCZero + ".rotateX",
                                 force=True)

                # footRoll with angle limit:
                footPMA = cmds.createNode("plusMinusAverage",
                                          name=side + self.userGuideName +
                                          "_Roll_PMA")
                footSR = cmds.createNode("setRange",
                                         name=side + self.userGuideName +
                                         "_Roll_SR")
                cmds.setAttr(footSR + ".oldMaxY", 180)
                cmds.setAttr(footPMA + ".input1D[0]", 180)
                cmds.setAttr(footPMA + ".operation", 2)  #substract
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footSR + ".valueX",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footSR + ".valueY",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footSR + ".maxX",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footSR + ".oldMinY",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footSR + ".oldMaxX",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footPMA + ".input1D[1]",
                                 force=True)
                cmds.connectAttr(footPMA + ".output1D",
                                 footSR + ".maxY",
                                 force=True)

                # plant angle for foot roll:
                footPlantClp = cmds.createNode("clamp",
                                               name=side + self.userGuideName +
                                               "_Roll_Plant_Clp")
                footPlantCnd = cmds.createNode("condition",
                                               name=side + self.userGuideName +
                                               "_Roll_Plant_Cnd")
                cmds.setAttr(footPlantCnd + ".operation", 4)  #less than
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footPlantClp + ".inputR",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 footPlantClp + ".maxR",
                                 force=True)
                cmds.connectAttr(footPlantClp + ".outputR",
                                 footPlantCnd + ".firstTerm",
                                 force=True)
                cmds.connectAttr(footPlantClp + ".outputR",
                                 footPlantCnd + ".colorIfTrueR",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 footPlantCnd + ".secondTerm",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 footPlantCnd + ".colorIfFalseR",
                                 force=True)

                # back to zero footRoll when greather then angle plus plant values:
                anglePlantPMA = cmds.createNode(
                    "plusMinusAverage",
                    name=side + self.userGuideName + "_AnglePlant_PMA")
                anglePlantMD = cmds.createNode("multiplyDivide",
                                               name=side + self.userGuideName +
                                               "_AnglePlant_MD")
                anglePlantRmV = cmds.createNode(
                    "remapValue",
                    name=side + self.userGuideName + "_AnglePlant_RmV")
                anglePlantCnd = cmds.createNode(
                    "condition",
                    name=side + self.userGuideName + "_AnglePlant_Cnd")
                cmds.setAttr(anglePlantMD + ".input2X", -1)
                cmds.setAttr(anglePlantRmV + ".inputMax", 90)
                cmds.setAttr(anglePlantRmV + ".value[0].value_Interp",
                             3)  #spline
                cmds.setAttr(anglePlantRmV + ".value[1].value_Interp",
                             3)  #spline
                cmds.setAttr(anglePlantCnd + ".operation", 2)  #greather than
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 anglePlantPMA + ".input1D[0]",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 anglePlantPMA + ".input1D[1]",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 anglePlantCnd + ".firstTerm",
                                 force=True)
                cmds.connectAttr(anglePlantPMA + ".output1D",
                                 anglePlantCnd + ".secondTerm",
                                 force=True)
                cmds.connectAttr(anglePlantPMA + ".output1D",
                                 anglePlantMD + ".input1X",
                                 force=True)
                cmds.connectAttr(anglePlantPMA + ".output1D",
                                 anglePlantRmV + ".inputMin",
                                 force=True)
                cmds.connectAttr(anglePlantMD + ".outputX",
                                 anglePlantRmV + ".outputMax",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 anglePlantRmV + ".inputValue",
                                 force=True)
                cmds.connectAttr(anglePlantRmV + ".outColorR",
                                 anglePlantCnd + ".colorIfTrueR",
                                 force=True)
                cmds.connectAttr(anglePlantCnd + ".outColorR",
                                 self.RFEZeroExtra + ".rotateX",
                                 force=True)

                # connect to groups in order to rotate them:
                cmds.connectAttr(footSR + ".outValueY",
                                 self.RFDZero + ".rotateX",
                                 force=True)
                cmds.connectAttr(footSR + ".outValueX",
                                 self.RFEZero + ".rotateX",
                                 force=True)
                if s == 0:  #left
                    cmds.connectAttr(footPlantCnd + ".outColorR",
                                     self.footCtrlZeroList[1] + ".rotateX",
                                     force=True)
                else:  #fix right side mirror
                    footPlantInvMD = cmds.createNode(
                        "multiplyDivide",
                        name=side + self.userGuideName + "_Plant_Inv_MD")
                    cmds.setAttr(footPlantInvMD + ".input2X", -1)
                    cmds.connectAttr(footPlantCnd + ".outColorR",
                                     footPlantInvMD + ".input1X",
                                     force=True)
                    cmds.connectAttr(footPlantInvMD + ".outputX",
                                     self.footCtrlZeroList[1] + ".rotateX",
                                     force=True)

                # organizing keyable attributes:
                self.ctrls.setLockHide([self.middleFootCtrl, self.footCtrl],
                                       ['v'],
                                       l=False)

                # show or hide reverseFoot controls:
                cmds.addAttr(self.footCtrl,
                             longName=showCtrlsAttr,
                             attributeType='long',
                             min=0,
                             max=1,
                             defaultValue=1)
                cmds.setAttr(self.footCtrl + "." + showCtrlsAttr,
                             keyable=False,
                             channelBox=True)
                showHideCtrlList = [
                    self.RFACtrl, self.RFBCtrl, self.RFCCtrl, self.RFDCtrl
                ]
                for rfCtrl in showHideCtrlList:
                    rfCtrlShape = cmds.listRelatives(rfCtrl,
                                                     children=True,
                                                     type='nurbsCurve')[0]
                    cmds.connectAttr(self.footCtrl + "." + showCtrlsAttr,
                                     rfCtrlShape + ".visibility",
                                     force=True)

                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp = cmds.group(
                    self.footCtrlZeroList[0],
                    name=side + self.userGuideName + "_Control_Grp")
                self.revFootCtrlGrpFinalList.append(self.toCtrlHookGrp)

                self.toScalableHookGrp = cmds.createNode(
                    "transform", name=side + self.userGuideName + "_Joint_Grp")
                mWorldFoot = cmds.getAttr(self.footJnt + ".worldMatrix")
                cmds.xform(self.toScalableHookGrp,
                           matrix=mWorldFoot,
                           worldSpace=True)
                cmds.parent(self.footJnt,
                            self.toScalableHookGrp,
                            absolute=True)
                #Remove the Joint orient to make sure the bone is at the same orientation than it's parent
                cmds.setAttr(self.footJnt + ".jointOrientX", 0)
                cmds.setAttr(self.footJnt + ".jointOrientY", 0)
                cmds.setAttr(self.footJnt + ".jointOrientZ", 0)
                self.aScalableGrp.append(self.toScalableHookGrp)

                self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp,
                                                  self.toScalableHookGrp,
                                                  name=side +
                                                  self.userGuideName + "_Grp")
                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)
                # create a locator in order to avoid delete static group
                loc = cmds.spaceLocator(name=side + self.userGuideName +
                                        "_DO_NOT_DELETE")[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')
                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()