Example #1
0
def skeletonizeCharacter(masterNull):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Skeletonizes a character
    
    ARGUMENTS:
    masterNull(string)
    
    RETURNS:
    nothin
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    modules = modules.returnModules(masterNull)
    orderedModules = modules.returnOrderedModules(modules)
    #>>> Do the spine first
    stateCheck = modules.moduleStateCheck(orderedModules[0], ['template'])
    if stateCheck == 1:
        spineJoints = skeletonize(orderedModules[0])
    else:
        print('%s%s' %
              (module, ' has already been skeletonized. Moving on...'))

    #>>> Do the rest
    for module in orderedModules[1:]:
        stateCheck = modules.moduleStateCheck(module, ['template'])
        if stateCheck == 1:
            templateNull = modules.returnTemplateNull(module)
            root = modules.returnInfoNullObjects(module,
                                                 'templatePosObjects',
                                                 types='templateRoot')

            #>>> See if our item has a non default anchor
            anchored = storeTemplateRootParent(module)
            if anchored == True:
                anchor = attributes.returnMessageObject(
                    root[0], 'skeletonParent')
                closestJoint = distance.returnClosestObject(
                    anchor, spineJoints)
            else:
                closestJoint = distance.returnClosestObject(
                    root[0], spineJoints)

            limbJoints = skeletonize(module)
            rootName = rigging.doParentReturnName(limbJoints[0], closestJoint)
            print rootName
        else:
            print('%s%s' %
                  (module, ' has already been skeletonized. Moving on...'))
Example #2
0
def copyWeightsByClosestVerticeFromVert(sourceMesh, targetVert):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    New
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    assert mc.objExists(sourceMesh) is True,"'%s' doesn't exist" %sourceMesh
    assert mc.objExists(targetVert) is True,"'%s' doesn't exist" %targetVert
    
    targetMeshBuffer = targetVert.split('.')
    print targetMeshBuffer
    targetSkinCluster = querySkinCluster(targetMeshBuffer[0])
    print  targetSkinCluster
    influenceData = returnVerticeJointWeightDataToDict(sourceMesh)
    print influenceData
    sourceVertexList = (mc.ls ([sourceMesh+'.vtx[*]'],flatten=True))
    print sourceVertexList
    rebuiltVertWeightData = []


    """ find the closest vert """
    verticeBuffer = [targetVert]
    closestVert = distance.returnClosestObject(targetVert,sourceVertexList)
    print ("Copying " + closestVert + " >>>> " + targetVert)
    """ rebuild our vert weighting data to set"""
    verticeBuffer.append(influenceData.get(closestVert))
    rebuiltVertWeightData.append(verticeBuffer)

    setSkinWeights(targetSkinCluster,rebuiltVertWeightData)
    return rebuiltVertWeightData
Example #3
0
def copyWeightsByClosestVerticeFromVert(sourceMesh, targetVert):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    New
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    assert mc.objExists(sourceMesh) is True,"'%s' doesn't exist" %sourceMesh
    assert mc.objExists(targetVert) is True,"'%s' doesn't exist" %targetVert
    
    targetMeshBuffer = targetVert.split('.')
    print targetMeshBuffer
    targetSkinCluster = querySkinCluster(targetMeshBuffer[0])
    print  targetSkinCluster
    influenceData = returnVerticeJointWeightDataToDict(sourceMesh)
    print influenceData
    sourceVertexList = (mc.ls ([sourceMesh+'.vtx[*]'],flatten=True))
    print sourceVertexList
    rebuiltVertWeightData = []


    """ find the closest vert """
    verticeBuffer = [targetVert]
    closestVert = distance.returnClosestObject(targetVert,sourceVertexList)
    print ("Copying " + closestVert + " >>>> " + targetVert)
    """ rebuild our vert weighting data to set"""
    verticeBuffer.append(influenceData.get(closestVert))
    rebuiltVertWeightData.append(verticeBuffer)

    setSkinWeights(targetSkinCluster,rebuiltVertWeightData)
    return rebuiltVertWeightData
Example #4
0
def attachQSSSkinJointsToRigJoints (qssSkinJoints,qssRigJoints):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Created for N project. It will constrain one skeleton to the other
    by looking for the closest joint in a qss set of bind joints

    ARGUMENTS:
    qssSet(set) - must exist in scene. Set of the rig joints
    rigStartJoint - the first joint of a unifed  deformation skeleton

    RETURNS:
    Nothing
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    mc.select(cl=True)
    mc.select(qssSkinJoints)
    skinnedHeirarchy = mc.ls(sl=True)
    mc.select(cl=True)
    mc.select(qssRigJoints)
    rigHeirarchy = mc.ls(sl=True)
    constraintsList = []
    for obj in rigHeirarchy:
        print ('On '+obj)
        attachJoint = distance.returnClosestObject(obj,skinnedHeirarchy)
        pntConstBuffer = mc.pointConstraint(obj,attachJoint,maintainOffset=True,weight=1)
        orConstBuffer = mc.orientConstraint(obj,attachJoint,maintainOffset=True,weight=1)
        pntConst = mc.rename(pntConstBuffer,(obj+('_pntConst')))
        orConst = mc.rename(orConstBuffer,(obj+('_orConst')))
        constraintsList.append(pntConst)
        constraintsList.append(orConst)
    #make our attribute Holder object
    """ need to make our master scale connector"""
    dataHolderGrp= ('rigJointsConstraintHolder_grp')
    if mc.objExists (dataHolderGrp):
        pass
    else:
        mc.group (n= dataHolderGrp, w=True, empty=True)
    #stores the constraints
    attributes.storeObjListNameToMessage (constraintsList, dataHolderGrp)
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Example #5
0
def attachQSSSkinJointsToRigJoints (qssSkinJoints,qssRigJoints):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Created for N project. It will constrain one skeleton to the other
    by looking for the closest joint in a qss set of bind joints

    ARGUMENTS:
    qssSet(set) - must exist in scene. Set of the rig joints
    rigStartJoint - the first joint of a unifed  deformation skeleton

    RETURNS:
    Nothing
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    mc.select(cl=True)
    mc.select(qssSkinJoints)
    skinnedHeirarchy = mc.ls(sl=True)
    mc.select(cl=True)
    mc.select(qssRigJoints)
    rigHeirarchy = mc.ls(sl=True)
    constraintsList = []
    for obj in rigHeirarchy:
        print ('On '+obj)
        attachJoint = distance.returnClosestObject(obj,skinnedHeirarchy)
        pntConstBuffer = mc.pointConstraint(obj,attachJoint,maintainOffset=True,weight=1)
        orConstBuffer = mc.orientConstraint(obj,attachJoint,maintainOffset=True,weight=1)
        pntConst = mc.rename(pntConstBuffer,(obj+('_pntConst')))
        orConst = mc.rename(orConstBuffer,(obj+('_orConst')))
        constraintsList.append(pntConst)
        constraintsList.append(orConst)
    #make our attribute Holder object
    """ need to make our master scale connector"""
    dataHolderGrp= ('rigJointsConstraintHolder_grp')
    if mc.objExists (dataHolderGrp):
        pass
    else:
        mc.group (n= dataHolderGrp, w=True, empty=True)
    #stores the constraints
    attributes.storeObjListNameToMessage (constraintsList, dataHolderGrp)
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Example #6
0
def returnLocalAimDirection(rootObj, aimObj):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a local aim direction

    ARGUMENTS:
    rootObj(string)
    aimObj(string)

    RETURNS:
    direction(list) - [0,0,0]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    directionalLocArray = []
    locGroups = []
    directions = ['+x', '-x', '+y', '-y', '+z', '-z']
    returnDirections = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0],
                        [0, 0, 1], [0, 0, -1]]
    distanceBuffer = distance.returnDistanceBetweenObjects(rootObj, aimObj)

    #distanceValues = distanceBuffer /2
    cnt = 0
    for direction in directions:
        locBuffer = locators.locMeObject(rootObj)
        locBuffer = mc.rename(locBuffer, (locBuffer + '_' + str(cnt)))
        locGroups.append(rigging.groupMeObject(locBuffer))
        directionBuffer = list(direction)
        if directionBuffer[0] == '-':
            mc.setAttr((locBuffer + '.t' + directionBuffer[1]), -1)
        else:
            mc.setAttr((locBuffer + '.t' + directionBuffer[1]), 1)
        directionalLocArray.append(locBuffer)
        cnt += 1
    closestLoc = distance.returnClosestObject(aimObj, directionalLocArray)
    matchIndex = directionalLocArray.index(closestLoc)

    for grp in locGroups:
        mc.delete(grp)

    return returnDirections[matchIndex]
Example #7
0
def HOLDER(moduleNull):

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Connect skin joints to surface joints
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    for joint in skinJoints:
        attachJoint = distance.returnClosestObject(joint, surfaceJoints)
        pntConstBuffer = mc.pointConstraint(attachJoint,
                                            joint,
                                            maintainOffset=True,
                                            weight=1)
        orConstBuffer = mc.orientConstraint(attachJoint,
                                            joint,
                                            maintainOffset=True,
                                            weight=1)
        #scaleConstBuffer = mc.scaleConstraint(attachJoint,joint,maintainOffset=True,weight=1)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Template Save and Removal
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ get rid of the template """
Example #8
0
def copyWeightsByClosestVertice(sourceMesh, targetMesh):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Tool to copy weights from one mesh to another by checking for the closest vertice to each vertice

    ARGUMENTS:
    sourceMesh(string)
    targetMesh(string)

    RETURNS:
    None
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    assert mc.objExists(sourceMesh) is True,"'%s' doesn't exist" %sourceMesh
    assert mc.objExists(targetMesh) is True,"'%s' doesn't exist" %targetMesh

    targetSkinCluster = querySkinCluster(targetMesh)

    influenceData = returnVerticeJointWeightDataToDict(sourceMesh)

    targetVertexList = (mc.ls ([targetMesh+'.vtx[*]'],flatten=True))
    sourceVertexList = (mc.ls ([sourceMesh+'.vtx[*]'],flatten=True))

    rebuiltVertWeightData = []

    for v in targetVertexList:
        verticeBuffer = [v]

        """ find the closest vert """
        closestVert = distance.returnClosestObject(v,sourceVertexList)
        print ("Copying " + closestVert + " >>>> " + v)
        """ rebuild our vert weighting data to set"""
        verticeBuffer.append(influenceData.get(closestVert))
        rebuiltVertWeightData.append(verticeBuffer)


    setSkinWeights(targetSkinCluster,rebuiltVertWeightData)
    return rebuiltVertWeightData
Example #9
0
def copyWeightsByClosestVertice(sourceMesh, targetMesh):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Tool to copy weights from one mesh to another by checking for the closest vertice to each vertice

    ARGUMENTS:
    sourceMesh(string)
    targetMesh(string)

    RETURNS:
    None
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    assert mc.objExists(sourceMesh) is True,"'%s' doesn't exist" %sourceMesh
    assert mc.objExists(targetMesh) is True,"'%s' doesn't exist" %targetMesh

    targetSkinCluster = querySkinCluster(targetMesh)

    influenceData = returnVerticeJointWeightDataToDict(sourceMesh)

    targetVertexList = (mc.ls ([targetMesh+'.vtx[*]'],flatten=True))
    sourceVertexList = (mc.ls ([sourceMesh+'.vtx[*]'],flatten=True))

    rebuiltVertWeightData = []

    for v in targetVertexList:
        verticeBuffer = [v]

        """ find the closest vert """
        closestVert = distance.returnClosestObject(v,sourceVertexList)
        print ("Copying " + closestVert + " >>>> " + v)
        """ rebuild our vert weighting data to set"""
        verticeBuffer.append(influenceData.get(closestVert))
        rebuiltVertWeightData.append(verticeBuffer)


    setSkinWeights(targetSkinCluster,rebuiltVertWeightData)
    return rebuiltVertWeightData
Example #10
0
def constrainToParentModule(self):
    """
    Pass a module class. Constrains template root to parent's closest template object
    """
    log.debug(">>> constrainToParentModule")
    if not self.isTemplated():
        log.error("Must be template state to contrainToParentModule: '%s' "%self.getShortName())
        return False
    
    if not self.getMessage('moduleParent'):
        return False
    else:
        log.debug("looking for moduleParent info")
        i_templateNull = self.templateNull #Link
        i_parent = self.moduleParent #Link
        parentState = i_parent.getState()
        if i_parent.isTemplated():#If the parent has been templated, it makes things easy
            log.debug("Parent has been templated...")
            parentTemplateObjects = i_parent.templateNull.getMessage('controlObjects')
            log.debug("parentTemplateObjects: %s"%parentTemplateObjects)
            closestObj = distance.returnClosestObject(i_templateNull.getMessage('root')[0],parentTemplateObjects)
            log.debug("closestObj: %s"%closestObj)
            if parentTemplateObjects.index(closestObj) == 0:#if it's the first object, connect to the root
                log.info('Use root for parent object')
                closestObj = i_parent.templateNull.root.mNode
                
            #Find the closest object from the parent's template object
            log.debug("closestObj: %s"%closestObj)
            l_constraints = cgmMeta.cgmObject(i_templateNull.root.parent).getConstraintsTo()
            if cgmMeta.cgmObject(i_templateNull.root.parent).isConstrainedBy(closestObj):
                log.debug("Already constrained!")
                return True
            elif l_constraints:mc.delete(l_constraints)
                
            return constraints.doConstraintObjectGroup(closestObj,group = i_templateNull.root.parent,constraintTypes=['point'])
        else:
            log.debug("Parent has not been templated...")           
            return False
Example #11
0
def simpleControlSurfaceSmoothWeights(surface,maxBlend = 3):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Early version of a weight smoother for a

    ARGUMENTS:
    surface(string)

    RETURNS:
    Nada
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    cvList = (mc.ls ([surface+'.cv[*][*]'],flatten=True))
    skinCluster = querySkinCluster (surface)
    influenceObjects = queryInfluences (skinCluster)

    #find the closest influence object to the start
    startObject =  (distance.returnClosestObjToCV (cvList[0], influenceObjects))
    #find the closest influence object to the end
    endObject = (distance.returnClosestObjToCV (cvList[-1], influenceObjects))
    #getting the last cv list number
    cvChainLength =  ((len(cvList)-1)/2)

    #Smooth interior weights
    """ get our interior CVs """
    interiorCvList = []
    cnt = 1
    for i in range(cvChainLength):
        interiorCvList.append('%s%s%i%s' % (surface,'.cv[0][',cnt,']'))
        interiorCvList.append('%s%s%i%s' % (surface,'.cv[1][',cnt,']'))
        cnt += 1

    """ overall blend """
    for cv in interiorCvList:
        closestObject = (distance.returnClosestObjToCV (cv, influenceObjects))
        closestObjectsDict = distance.returnClosestObjectsFromAim(closestObject,influenceObjects)
        upObjects = closestObjectsDict.get('up')
        downObjects = closestObjectsDict.get('dn')
        objectsToCheck = []
        if upObjects != None:
            objectsToCheck += upObjects
        if downObjects != None:
            objectsToCheck += downObjects
        blendInfluences =[]
        blendInfluences.append(closestObject)
        distances = []
        cnt = 1
        print objectsToCheck
        while cnt < maxBlend and cnt < len(objectsToCheck):
            closestSubObj = distance.returnClosestObject(closestObject, objectsToCheck)
            blendInfluences.append(closestSubObj)
            objectsToCheck.remove(closestSubObj)
            cnt+=1

        """ get our distances to normalize """
        locBuffer = locators.locMeSurfaceCV(cv)
        for obj in blendInfluences:
            distances.append(distance.returnDistanceBetweenObjects(locBuffer,obj))
        normalizedDistances = cgmMath.normList(distances, normalizeTo=1)
        cnt = 0
        for obj in blendInfluences:
            mc.skinPercent (skinCluster,cv, tv = [obj,normalizedDistances[cnt]])
            cnt +=1
        mc.delete(locBuffer)

    """ Set closest cv's to respective infuences to max """
    cvList1 = []
    cvList2 = []
    for i in range(cvChainLength):
        cvList1.append('%s%s%i%s' % (surface,'.cv[0][',cnt,']'))
        cvList2.append('%s%s%i%s' % (surface,'.cv[1][',cnt,']'))
        cnt += 1
    for obj in influenceObjects:
        closestCV1 = distance.returnClosestCVFromList(obj, cvList1)
        mc.skinPercent (skinCluster,closestCV1, tv = [obj,1])
        closestCV2 = distance.returnClosestCVFromList(obj, cvList2)
        mc.skinPercent (skinCluster,closestCV2, tv = [obj,1])

    #set the skin weights for the top and bottom
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][0:1]'), tv = [startObject,1])
    mc.skinPercent (skinCluster,('%s%s%i%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-1),':',cvChainLength,']')), tv = [endObject,1])
    #Blend in the nearest row to the start and end
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][2]'), tv = [startObject,1])
    mc.skinPercent (skinCluster,('%s%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-2),']')), tv = [endObject,1])

    mc.skinPercent (skinCluster,(surface+'.cv[0:1][3]'), tv = [startObject,.7])
    mc.skinPercent (skinCluster,('%s%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-3),']')), tv = [endObject,.7])
Example #12
0
def rigSpine(moduleNull):
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>>Get our info
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    partName = NameFactory.returnUniqueGeneratedName(moduleNull,
                                                     ignore='cgmType')
    """ template null """
    templateNull = modules.returnTemplateNull(moduleNull)
    templateNullData = attributes.returnUserAttrsToDict(templateNull)
    jointOrientation = modules.returnSettingsData('jointOrientation')
    templateRoot = modules.returnInfoNullObjects(moduleNull,
                                                 'templatePosObjects',
                                                 types='templateRoot')
    """ AutonameStuff """
    divider = NameFactory.returnCGMDivider()
    """ control helper objects """
    controlTemplateObjects = modules.returnInfoNullObjects(
        moduleNull, 'templateControlObjects', types='all')
    controlTemplateObjects = distance.returnDistanceSortedList(
        templateRoot, controlTemplateObjects)

    print 'controlTemplateObjects...'
    print controlTemplateObjects
    """size list of template control objects """
    controlTemplateObjectsSizes = []
    for obj in controlTemplateObjects:
        controlTemplateObjectsSizes.append(
            distance.returnAbsoluteSizeCurve(obj))
    print 'sizes...'
    print controlTemplateObjectsSizes
    """ Skin Joints """
    skinJoints = modules.returnInfoNullObjects(moduleNull,
                                               'skinJoints',
                                               types='all')
    skinJoints = distance.returnDistanceSortedList(templateRoot, skinJoints)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Make Controls
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ control options """
    fk = templateNullData.get('fk')
    ik = templateNullData.get('ik')
    stretch = templateNullData.get('stretch')
    bend = templateNullData.get('bend')
    """controls to make """
    controlsToMake = []
    controlsToMake.append('cog')

    if fk == True:
        controlsToMake.append('segmentControls')
        controlsToMake.append('hips')

    if ik == True:
        controlsToMake.append('vectorHandles')
        controlsToMake.append('spineIKHandle')

    controlsDict = modules.limbControlMaker(moduleNull, controlsToMake)

    print controlsDict
    #>>> Organize em
    segmentControls = controlsDict.get('segmentControls')
    spineIKHandle = controlsDict.get('spineIKHandle')
    cog = controlsDict.get('cog')
    hips = controlsDict.get('hips')
    vectorHandles = controlsDict.get('vectorHandles')

    for handle in vectorHandles[-1:]:
        mc.delete(handle)
        vectorHandles.remove(handle)

    #>>> Parent em
    rigging.parentListToHeirarchy(segmentControls)
    mc.parent(spineIKHandle, segmentControls[-1])
    mc.parent(segmentControls[0], cog)
    mc.parent(hips, cog)

    for obj in segmentControls:
        rigging.zeroTransformMeObject(obj)
        mc.makeIdentity(obj, apply=True, translate=True)

    for obj in vectorHandles:
        mc.makeIdentity(obj, apply=True, translate=True)
    """ hips anchor locator """
    locBuffer = locators.locMeObject(hips)
    attributes.storeInfo(locBuffer, 'cgmName', hips)
    attributes.storeInfo(locBuffer, 'cgmTypeModifier', 'anchor')
    hipsAnchor = NameFactory.doNameObject(locBuffer)

    mc.setAttr((hipsAnchor + '.rotateOrder'), 5)

    pointConstraintBuffer = mc.pointConstraint(hips,
                                               hipsAnchor,
                                               maintainOffset=False,
                                               weight=1)
    orientConstraintBuffer = mc.orientConstraint(hips,
                                                 hipsAnchor,
                                                 maintainOffset=False,
                                                 skip=['x', 'y'],
                                                 weight=1)
    """ hips anchor group constraint """
    groupBuffer = rigging.groupMeObject(hipsAnchor)
    attributes.storeInfo(groupBuffer, 'cgmName', hipsAnchor)
    attributes.storeInfo(groupBuffer, 'cgmTypeModifier', 'orient')
    hipsAnchorOrGroup = NameFactory.doNameObject(groupBuffer)
    orientConstraintBuffer = mc.orientConstraint(segmentControls[0],
                                                 hipsAnchorOrGroup,
                                                 maintainOffset=False,
                                                 weight=1)
    """ end anchor locator """
    locBuffer = locators.locMeObject(segmentControls[-1])
    attributes.storeInfo(locBuffer, 'cgmName', segmentControls[-1])
    attributes.storeInfo(locBuffer, 'cgmTypeModifier', 'anchor')
    endAnchor = NameFactory.doNameObject(locBuffer)

    mc.setAttr((endAnchor + '.rotateOrder'), 5)

    mc.parent(endAnchor, spineIKHandle)

    #>>> set up follow chains
    constraintChain = []
    constraintChain.append(hipsAnchor)
    constraintChain = constraintChain + vectorHandles
    constraintChain.append(endAnchor)

    constraintChainReturn = constraints.doSegmentAimPointConstraint(
        constraintChain)
    print constraintChainReturn
    vectorHandlesZeroGroups = []
    for obj in vectorHandles:
        vectorHandlesZeroGroups.append(rigging.zeroTransformMeObject(obj))
    """ parent the last group to our IK handle """
    #mc.parent(vectorHandlesZeroGroups[-1],spineIKHandle)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Joint Chains
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ surface chain """
    dupJointsBuffer = mc.duplicate(skinJoints[:-1], po=True, rc=True)
    surfaceJoints = []
    for joint in dupJointsBuffer:
        attributes.storeInfo(joint, 'cgmType', 'surfaceJoint')
        surfaceJoints.append(NameFactory.doNameObject(joint))
    """ firm start """
    startJointsBuffer = mc.duplicate(skinJoints[0], po=True, rc=True)
    startJoints = []
    for joint in startJointsBuffer:
        attributes.storeInfo(joint, 'cgmType', 'deformationJoint')
        startJoints.append(NameFactory.doNameObject(joint))
    """ firm end """
    endJointsBuffer = mc.duplicate(skinJoints[-2:], po=True, rc=True)
    endJoints = []
    for joint in endJointsBuffer:
        attributes.storeInfo(joint, 'cgmType', 'deformationJoint')
        endJoints.append(NameFactory.doNameObject(joint))
    mc.parent(endJoints[0], world=True)

    #>>> Influence chain
    """
    get the root joints from our main chain searching by "cgmName" tags...maybe not the best way
    Maybe should change to search to closest joints
    """
    influenceJointsBuffer = []
    for obj in surfaceJoints:
        if (search.returnTagInfo(obj, 'cgmName')) != False:
            influenceJointsBuffer.append(obj)
    """ make our influence joints """
    influenceJoints = []
    for joint in influenceJointsBuffer:
        buffer = mc.duplicate(joint, po=True)
        closestObject = distance.returnClosestObject(buffer[0], surfaceJoints)
        attributes.storeInfo(buffer[0], 'cgmName', closestObject)
        attributes.storeInfo(buffer[0], 'cgmType', 'influenceJoint')
        rigging.doParentToWorld(buffer[0])
        influenceJoints.append(NameFactory.doNameObject(buffer[0]))

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Put our deformation joints in the rig
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    ############### need better way of doing this for iterative
    mc.parent(endJoints[0], spineIKHandle)
    mc.parent(startJoints[0], hips)
    mc.parent(influenceJoints[0], hipsAnchor)
    mc.parent(influenceJoints[1], vectorHandles[0])
    mc.parent(influenceJoints[2], spineIKHandle)
    #mc.parent(influenceJoints[3],spineIKHandle)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Control Surface
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ create """
    orientationBuffer = list(jointOrientation)
    outChannel = orientationBuffer[2]
    upChannel = (orientationBuffer[1] + 'up')
    print upChannel

    surfaceBuffer = joints.loftSurfaceFromJointList(surfaceJoints, outChannel)
    controlSurface = surfaceBuffer[0]
    attributes.copyUserAttrs(moduleNull,
                             controlSurface,
                             attrsToCopy=['cgmName'])
    attributes.storeInfo(controlSurface, 'cgmType', 'controlSurface', True)
    controlSurface = NameFactory.doNameObject(controlSurface)
    """ connect joints to surface"""
    surfaceConnectReturn = joints.attachJointChainToSurface(
        surfaceJoints, controlSurface, jointOrientation, upChannel, 'animCrv')
    print surfaceConnectReturn
    """ surface influence joints skinning"""
    surfaceSkinCluster = mc.skinCluster(influenceJoints,
                                        controlSurface,
                                        tsb=True,
                                        n=(controlSurface + '_skinCluster'),
                                        maximumInfluences=3,
                                        normalizeWeights=1,
                                        dropoffRate=1)
    #surfaceSkinCluster = mc.skinCluster (influenceJoints,controlSurface,tsb=True, n=(controlSurface+'_skinCluster'),maximumInfluences = 3, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
    controlSurfaceSkinCluster = surfaceSkinCluster[0]
    """ smooth skin weights """
    skinning.simpleControlSurfaceSmoothWeights(controlSurface)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Connect skin joints to surface joints
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    deformationJoints = []
    deformationJoints.append(startJoints[0])
    deformationJoints = deformationJoints + surfaceJoints[1:-2]
    deformationJoints = deformationJoints + endJoints
    for joint in skinJoints:
        attachJoint = distance.returnClosestObject(joint, deformationJoints)
        pntConstBuffer = mc.pointConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
        orConstBuffer = mc.orientConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
        #mc.connectAttr((attachJoint+'.t'),(joint+'.t'))
        #mc.connectAttr((attachJoint+'.r'),(joint+'.r'))
        mc.connectAttr((attachJoint + '.s'), (joint + '.s'))
        pntConstBuffer = mc.pointConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
        orConstBuffer = mc.orientConstraint(attachJoint,
                                            joint,
                                            maintainOffset=False,
                                            weight=1)
Example #13
0
def surfRigger(objectNull,anchor,worldScale,mirror,mode,jointsPerChain,deformChains,ctrlChains):
    """ Get variables"""
    nullBase = names.stripSuffixObj (objectNull)
    templateNull = (nullBase + '_templateNull')
    moverNull = (nullBase + '_mover')
    templateNullMessageData = []
    templateNullMessageData = attributes.returnMessageAttrs (templateNull)
    templateObjects = []
    coreNamesList = []
    spineJointNumber = int(mc.getAttr (objectNull+'.rollJoints'))
    #spineChainList = search.returnChildrenJoints (spineChain)
    spineChainList = []
    spineChainList.append (anchor)
    jointChains = []
    for set in templateNullMessageData:
        templateObjects.append (set[1])
        coreNamesList.append (set[0])
    #>>>>>>>>>>>>>>>>>>>>>Store skin joint data
    """ check for master skin info group """
    if mc.objExists ('master_skinJntList_grp'):
        masterSkinJointList = ('master_skinJntList_grp')
    else:
        masterSkinJointList = mc.group (n= ('master_skinJntList_grp'), w=True, empty=True)
        mc.parent(masterSkinJointList,'rigStuff_grp')
    """ check for segment skin info group """
    if mc.objExists (nullBase+'_skinJntList_grp'):
        skinJointListGrp = (nullBase+'_skinJntList_grp')
    else:
        skinJointListGrp = mc.group (n= (nullBase+'_skinJntList_grp'), w=True, empty=True)
    attributes.storeObjNameToMessage (skinJointListGrp,masterSkinJointList)
    mc.parent (skinJointListGrp,masterSkinJointList)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ Rebuild curve - with actual curve in it!"""
    mc.rebuildCurve ((templateObjects[3]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=jointsPerChain, d=1, tol=5)
    mc.rebuildCurve ((templateObjects[7]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=jointsPerChain, d=1, tol=5)
    mc.rebuildCurve ((templateObjects[11]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=jointsPerChain, d=1, tol=5)
    """ Reverse the curve """
    mc.reverseCurve ((templateObjects[3]),ch=False,rpo=True)
    mc.reverseCurve ((templateObjects[7]),ch=False,rpo=True)
    mc.reverseCurve ((templateObjects[11]),ch=False,rpo=True)
    """ loft our surface to figure out joint positions, then delete it"""
    controlSurface = mc.loft ([templateObjects[3],templateObjects[7],templateObjects[11]],name=(nullBase+'_surf'),ss=(ctrlChains-mode),ch=1,u=1,c=0,ar=1,d=3,rn=0,po=0,rsn=True)
    mc.select (cl=True)
    jointChains = joints.createJointChainsFromLoftSurface (nullBase,controlSurface[0],2,False)
    frontChain = jointChains[0]
    backChain = jointChains[-1]
    """ Chain - orienting, sizing """
    for chain in jointChains:
        joints.orientJointChain (chain, 'xyz', 'zup')
        joints.setGoodJointRadius(chain,.5)
    #IF we have mode 0, gotta make a main ctrl
    if mode == 0:
        midChain = []
        if (len(jointChains)) > 3:
            midChain = jointChains[int(len(jointChains)/2)]
        else:
            midChain = jointChains[1]
            jointChains.remove(midChain)
        if ctrlChains > 2:
            masterCtrlBuffer = mc.duplicate (midChain[0],parentOnly=True)
        else:
            masterCtrlBuffer = midChain[0]
            mc.delete (midChain[1])
        masterCtrl = mc.rename (masterCtrlBuffer,(nullBase+'_master_anim'))
        position.movePointSnap(masterCtrl,moverNull)
        """ temp parenting the master control for mirroring purposes """
        spineHookJoint = distance.returnClosestObject (masterCtrl, spineChainList)
        mc.parent (masterCtrl,spineHookJoint)
    mc.delete (controlSurface[0])
    #>>>>>>>>>>>>Parent time
    """ Get closest joint """
    if mode == 0:
        for chain in jointChains:
            mc.parent (chain[0],masterCtrl)
    else:
        for chain in jointChains:
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            mc.parent (chain[0],tailHookJoint)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>> Ctrl Joints to Ctrls
    cnt = 0
    for chain in jointChains:
        ctrlSize = (distance.returnAverageDistanceBetweenObjects (chain)/2)
        for jnt in chain[0:-1]:
            rigging.makeObjCtrl (jnt,ctrlSize)
        """ adds our Anim tag """
        chainBuffer = []
        chainBuffer = names.addSuffixList ('anim', chain)
        jointChains[cnt]= chainBuffer
        cnt +=1
    #>>>>>>>>>>>>>>>>>>>Mirroring while getting chain info
    """ If mirroring ...."""
    if mirror == True:
        # if we have a main control
        leftSkinChains = []
        rightSkinChains = []
        masterCtrls = []
        if mode == 0:
            leftChain = []
            rightChain = []
            finHeirarchy = []
            finHeirarchy.append (masterCtrl)
            children = search.returnChildrenJoints (masterCtrl)
            finHeirarchy += children
            leftChain = names.addPrefixList ('left',finHeirarchy)
            masterCtrl = leftChain [0]
            rightChainBuffer = mc.mirrorJoint (masterCtrl,mirrorYZ=True,mirrorBehavior=True, searchReplace =['left','right'])
            rightChainJointBuffer = mc.ls (rightChainBuffer,type='joint')
            rightChain = rightChainJointBuffer
            leftSkinChains.append(leftChain)
            rightSkinChains.append(rightChain)
            masterCtrls.append(leftChain[0])
            masterCtrls.append(rightChain[0])
        else:
            for chain in jointChains:
                leftChain =[]
                leftChain = names.addPrefixList ('left',chain)
                rightChainBuffer = (mc.mirrorJoint (leftChain[0],mirrorYZ=True,mirrorBehavior=True, searchReplace =['left','right']))
                rightChainJointBuffer = mc.ls (rightChainBuffer,type='joint')
                rightChain = rightChainJointBuffer
                rightSkinChains.append (rightChainJointBuffer)
                leftSkinChains.append (leftChain)
        """ complile our chains to lists of skin joints """
        leftSkinJointList=[]
        rightSkinJointList=[]
        for chain in leftSkinChains:
            for jnt in chain:
                leftSkinJointList.append (jnt)
        for chain in rightSkinChains:
            for jnt in chain:
                rightSkinJointList.append (jnt)
        """if we're not mirroring, let's return our skin joints for the deformation surface"""
    else:
        skinJointList = []
        skinChains = []
        for chain in jointChains:
            skinChains.append (chain)
            for jnt in chain:
                skinJointList.append (jnt)
                
    #>>>>>>>>>>>>>>>>>>>>>>>>>>Time to make the deformation surface stuff
    """ Rebuild curve - with actual curve in it!"""
    #mc.rebuildCurve ((templateObjects[3]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=(3), d=1, tol=5)
    #mc.rebuildCurve ((templateObjects[7]), ch=0, rpo=1, rt=0, end=0, kr=0, kcp=0, kep=1, kt=0, s=(3), d=1, tol=5)
    """ loft our surface to figure out joint positions, then delete it"""
    deformSurface = mc.loft ([templateObjects[3],templateObjects[7],templateObjects[11]],name=(nullBase+'_surf'),ss=(deformChains-1),ch=0,u=1,c=0,ar=1,d=3,rn=0,po=0,rsn=True)
    if mirror == True:
        deformSurfaceNameBuffer = deformSurface[0]
        """we have a surface to mirror..."""
        surfaceMirrorBuffer = mc.duplicate (deformSurface[0])
        mc.setAttr ((surfaceMirrorBuffer[0]+'.sx'),-1)
        leftBuffer = mc.rename (deformSurface[0],('left_'+deformSurfaceNameBuffer))
        rightBuffer = mc.rename (surfaceMirrorBuffer[0],('right_'+deformSurfaceNameBuffer))
        deformSurface[0]=leftBuffer
        deformSurface.append(rightBuffer)
        leftDeformJointChains = joints.createJointChainsFromLoftSurface (('left_'+nullBase),deformSurface[0],2,False)
        rightDeformJointChains = joints.createJointChainsFromLoftSurface (('right_'+nullBase),deformSurface[1],2,False)
        """ Connecting to surface """
        for chain in leftDeformJointChains:
            attachSurfaceReturn = joints.attachJointChainToSurface (chain,deformSurface[0],'xyz','zup')
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            """ break the connection so we can parent it"""
            """first return the original thing to follow"""
            parentBuffer = attributes.returnDriverObject ((chain[0]+'.translate'))
            attributes.doBreakConnection (chain[0]+'.translate')
            #mc.parent (chain[0],tailHookJoint)
            """ reconstrain it to the driver"""
            constraintBuffer = mc.pointConstraint (parentBuffer,chain[0], maintainOffset = True)
            mc.rename (constraintBuffer[0],(chain[0]+'_pointConst'))
            """ store the skin joint data """
            for jnt in chain:
                attributes.storeObjNameToMessage (jnt,skinJointListGrp)

        for chain in rightDeformJointChains:
            attachSurfaceMirrorReturn = joints.attachJointChainToSurface (chain,deformSurface[1],'xyz','zup')
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            """ break the connection s we can parent it"""
            """first return the original thing to follow"""
            parentBuffer = attributes.returnDriverObject ((chain[0]+'.translate'))
            attributes.doBreakConnection (chain[0]+'.translate')
            #mc.parent (chain[0],tailHookJoint)
            """ reconstrain it to the driver"""
            constraintBuffer = mc.pointConstraint (parentBuffer,chain[0], maintainOffset = True)
            mc.rename (constraintBuffer[0],(chain[0]+'_pointConst'))
            """ store the skin joint data """
            for jnt in chain:
                attributes.storeObjNameToMessage (jnt,skinJointListGrp)

        """ parent the scale stuff to rig stuff grp"""
        mc.select (cl=True)
        for item in attachSurfaceReturn[0]:
            mc.parent(item,'rigStuff_grp')
        for item in attachSurfaceMirrorReturn[0]:
            mc.parent(item,'rigStuff_grp')
        """ hook up world scale """
        mc.connectAttr (worldScale,attachSurfaceReturn[1])
        mc.connectAttr (worldScale,attachSurfaceMirrorReturn[1])
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Skin in the control joints
        """ Time to set skin our surface to our control joints """
        mc.skinCluster (leftSkinJointList,deformSurface[0],tsb=True, n=(deformSurface[0]+'_skinCluster'),maximumInfluences = 8, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
        mc.skinCluster (rightSkinJointList,deformSurface[1],tsb=True, n=(deformSurface[1]+'_skinCluster'),maximumInfluences = 8, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
    #>>>>>If we,re not mirrored, let's make our deform setup
    else:
        deformJointChains = []
        deformJointChains = joints.createJointChainsFromLoftSurface (nullBase,deformSurface[0],2,False)
        """ Connecting to surface """
        for chain in deformJointChains:
            attachSurfaceReturn = joints.attachJointChainToSurface (chain,deformSurface[0],'xyz','zup')
            tailHookJoint = distance.returnClosestObject (chain[0], spineChainList)
            """ break the connection so we can parent it"""
            """first return the original thing to follow"""
            parentBuffer = attributes.returnDriverObject ((chain[0]+'.translate'))
            attributes.doBreakConnection (chain[0]+'.translate')
            #mc.parent (chain[0],tailHookJoint)
            """ reconstrain it to the driver"""
            constraintBuffer = mc.pointConstraint (parentBuffer,chain[0], maintainOffset = True)
            mc.rename (constraintBuffer[0],(chain[0]+'_pointConst'))
            """ store the skin joint data """
            for jnt in chain:
                attributes.storeObjNameToMessage (jnt,skinJointListGrp)
        """ hook up world scale  """
        partScaleBuffer = attachSurfaceReturn[1]
        mc.connectAttr (worldScale, partScaleBuffer)
        """ parent the scale stuff to rig stuff grp"""
        mc.select (cl=True)
        for item in attachSurfaceReturn[0]:
            mc.parent(item,'rigStuff_grp')
        """ Time to set skin our surface to our control joints """
        mc.skinCluster (skinJointList,deformSurface[0],tsb=True, n=(deformSurface[0]+'_skinCluster'),maximumInfluences = 8, normalizeWeights = 1, dropoffRate=1,smoothWeights=.5,obeyMaxInfluences=True, weight = 1)
        
        
    """ Setting up the joint starts"""
    if mode == 0:
        if mirror == True:
            for ctrl in masterCtrls:
                rigging.makeObjCtrl (ctrl,(ctrlSize*4))
                masterCtrlGrp = rigging.groupMeObject (ctrl,True)
                """ Get closest joint and connect the Cntrl """
                spineHookJoint = distance.returnClosestObject (masterCtrlGrp, spineChainList)
                mc.parent(masterCtrlGrp,spineHookJoint)
        else:
            rigging.makeObjCtrl (masterCtrl,(ctrlSize*4))
            masterCtrlGrp = rigging.groupMeObject (masterCtrl,True)
            """ Get closest joint and connect the Cntrl """
            spineHookJoint = distance.returnClosestObject (masterCtrlGrp, spineChainList)
            mc.parent(masterCtrlGrp,spineHookJoint)
    #else we need to connect the individual chains to the spine
    else:
        if mirror == True:
            for chain in leftSkinChains:
                chainCtrlGrp = rigging.groupMeObject (chain[0],True)
                spineHookJoint = distance.returnClosestObject (chainCtrlGrp, spineChainList)
                mc.parent(chainCtrlGrp,spineHookJoint)
            for chain in rightSkinChains:
                chainCtrlGrp = rigging.groupMeObject (chain[0],True)
                spineHookJoint = distance.returnClosestObject (chainCtrlGrp, spineChainList)
                mc.parent(chainCtrlGrp,spineHookJoint)
        else:
            for chain in skinChains:
                chainCtrlGrp = rigging.groupMeObject (chain[0],True)
                spineHookJoint = distance.returnClosestObject (chainCtrlGrp, spineChainList)
                mc.parent(chainCtrlGrp,spineHookJoint)
Example #14
0
        def makeLimbTemplate (self):
            #>>>Curve degree finder
            if self.optionCurveDegree.get() == 0:
                doCurveDegree = 1
            else:
                if len(corePositionList) <= 3:
                    doCurveDegree = 1
                else:
                    doCurveDegree = len(corePositionList) - 1
                    
            #Make some storage vehicles
            self.templatePosObjectsBuffer = BufferFactory(self.infoNulls['templatePosObjects'].get())
            self.templatePosObjectsBuffer.purge()
            
            LocatorCatcher = ObjectFactory('')
            LocatorBuffer = BufferFactory(LocatorCatcher.nameLong)
            LocatorBuffer.purge()
            
            returnList = []
            self.templHandleList = []
            
            moduleColors = modules.returnModuleColors(self.ModuleNull.nameShort)
            
            #>>>Scale stuff
            moduleParent = self.msgModuleParent.get()
            
            if not moduleParent:
                length = (distance.returnDistanceBetweenPoints (corePositionList[0],corePositionList[-1]))
                size = length / self.optionHandles.get()
            else:
                #>>>>>>>>>>>>>>>>>>>>> NOT TOUCHED YET
                parentTemplatePosObjectsInfoNull = modules.returnInfoTypeNull(moduleParent,'templatePosObjects')
                parentTemplatePosObjectsInfoData = attributes.returnUserAttrsToDict (parentTemplatePosObjectsInfoNull)
                parentTemplateObjects = []
                for key in parentTemplatePosObjectsInfoData.keys():
                    if (mc.attributeQuery (key,node=parentTemplatePosObjectsInfoNull,msg=True)) == True:
                        if search.returnTagInfo((parentTemplatePosObjectsInfoData[key]),'cgmType') != 'templateCurve':
                            parentTemplateObjects.append (parentTemplatePosObjectsInfoData[key])
                createBuffer = curves.createControlCurve('sphere',1)
                pos = corePositionList[0]
                mc.move (pos[0], pos[1], pos[2], createBuffer, a=True)
                closestParentObject = distance.returnClosestObject(createBuffer,parentTemplateObjects)
                boundingBoxSize = distance.returnBoundingBoxSize (closestParentObject)
                maxSize = max(boundingBoxSize)
                size = maxSize *.25
                mc.delete(createBuffer)
                if partType == 'clavicle':
                    size = size * .5
                elif partType == 'head':
                    size = size * .75
                if (search.returnTagInfo(moduleParent,'cgmModuleType')) == 'clavicle':
                    size = size * 2
        
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            # Making the template objects
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            self.TemplateObject = {}
            
            #>>> Template objects
            for cnt,pos in enumerate(corePositionList):
                #Size multiplier based on PuppetMode, make it take into account module mode eventually
                if PuppetInstance.optionPuppetMode.get() == 0:
                    if cnt == 0:
                        sizeMultiplier = 1
                    elif cnt == len(corePositionList) -1:
                        sizeMultiplier = .8
                    else:
                        sizeMultiplier = .5
                else:
                    sizeMultiplier = 1
                    
                #make a sphere and move it
                createBuffer = curves.createControlCurve('sphere',(size * sizeMultiplier))
                self.TemplateObject[cnt] = ObjectFactory(createBuffer) # Instance the control to our module
                obj = self.TemplateObject[cnt]
                curves.setCurveColorByName(obj.nameLong,moduleColors[0])
                obj.store('cgmName',coreNames[cnt])
                
                obj.getNameTagsFromObject(self.ModuleNull.nameLong,['cgmName','cgmType'])

                obj.store('cgmType','templateObject')
                obj.doName()
                mc.move (pos[0], pos[1], pos[2], [obj.nameLong], a=True)
                            
                #adds it to the list
                self.templHandleList.append (obj.nameLong) 
                self.templatePosObjectsBuffer.store(obj.nameLong)
            
             
            #Aim the objects           
            position.aimObjects(self.templHandleList,
                                dictionary.axisDirectionsByString[ self.optionAimAxis.get() ],
                                dictionary.axisDirectionsByString[ self.optionUpAxis.get() ],
                                dictionary.axisDirectionsByString[ PuppetInstance.optionUpAxis.get() ])            
            
            #>>> Template curve
            crvName = mc.curve (d=doCurveDegree, p = corePositionList , os=True, n=('%s_%s' %(partName,(typesDictionary.get('templateCurve')))))            
            self.afTemplateCurve = AttrFactory(self.infoNulls['templatePosObjects'].get(),
                                               'curve','message', value=crvName)# connect it back to our template objects info null
            
            curve = ObjectFactory(crvName) # instance it
            curve.getNameTagsFromObject(self.ModuleNull.nameLong,['cgmType']) #get name tags from the module

            attributes.storeInfo(crvName,'cgmType','templateCurve') # store type
            curves.setCurveColorByName(crvName,moduleColors[1]) # set curve color
            
            # Make locators to connect the cv's to
            for cnt,obj in enumerate(self.templHandleList):
                pointLoc = locators.locMeObject(obj) # make the loc
                loc = ObjectFactory(pointLoc) #instance it
                mc.setAttr ((loc.nameShort+'.visibility'),0) # turn off visibility
                mc.parentConstraint ([obj],[loc.nameShort],mo=False) # parent constrain
                mc.connectAttr ( (loc.nameShort+'.translate'),
                                 ('%s.controlPoints[%i]' % (crvName, cnt)), f=True ) # connect the cv to the loc
                self.TemplateObject[cnt].store('loc',loc.nameLong)
                LocatorBuffer.store(loc.nameLong)
                
            #>>> Direction and size Stuff
            """
            # Directional data derived from joints 
            generalDirection = logic.returnHorizontalOrVertical(self.templHandleList)
            if generalDirection == 'vertical' and 'leg' not in self.afModuleType.get():
                worldUpVector = [0,0,-1]
            elif generalDirection == 'vertical' and 'leg' in self.afModuleType.get():
                worldUpVector = [0,0,1]
            else:
                worldUpVector = [0,1,0]
            """            
            
            # Create root control
            templateNull = self.msgTemplateNull.get()
            handleList = copy.copy(self.templatePosObjectsBuffer.bufferList)
            
            rootSize = (distance.returnBoundingBoxSizeToAverage(self.templHandleList[0])*1.5)
            rootCtrl = ObjectFactory(curves.createControlCurve('cube',rootSize))
            rootCtrl.getNameTagsFromObject(self.ModuleNull.nameLong)
            self.msgTemplateRoot = AttrFactory(self.infoNulls['templatePosObjects'].get(), 'root', 'message', value = rootCtrl.nameLong)
            curves.setCurveColorByName(rootCtrl.nameLong,moduleColors[0])
            
            # move the root
            if self.afModuleType.get() == 'clavicle':
                position.movePointSnap(rootCtrl.nameLong,self.templHandleList[0])
            else:
                position.movePointSnap(rootCtrl.nameLong,self.templHandleList[0])
            # aim the root
            position.aimSnap(rootCtrl.nameShort,self.templHandleList[-1],  
                            dictionary.axisDirectionsByString[ self.optionAimAxis.get() ],
                            dictionary.axisDirectionsByString[ self.optionUpAxis.get() ],
                            dictionary.axisDirectionsByString[ PuppetInstance.optionUpAxis.get() ]) 
            
            rootCtrl.store('cgmType','templateRoot')
            rootCtrl.doName()
            
            #>>> Parent the main objcts
            rootGroup = rootCtrl.doGroup()
            rootGroup = rigging.doParentReturnName(rootGroup,templateNull)
            curve.doParent(templateNull)
            
            for obj in LocatorBuffer.bufferList:
                rigging.doParentReturnName(obj,templateNull)
            mc.delete(LocatorCatcher.nameShort) # delete the locator buffer obj
            
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Orientation helpers
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            # Make our Orientation Helpers 
            """
            orientHelpersReturn = template.addOrientationHelpers(self)
            masterOrient = orientHelpersReturn[0]
            orientObjects = orientHelpersReturn[1]
            return
            
        
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Control helpers
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            print orientObjects
            print self.ModuleNull.nameShort
            print (templateNull+'.visControlHelpers')
            controlHelpersReturn = addControlHelpers(orientObjects,self.ModuleNull.nameShort,(templateNull+'.visControlHelpers'))"""
    
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Input the saved values if there are any
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            # Orientation Helpers 
            """rotBuffer = coreRotationList[-1]
            #actualName = mc.spaceLocator (n= wantedName)
            rotCheck = sum(rotBuffer)
            if rotCheck != 0:
                mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],masterOrient,os=True)
            
            cnt = 0
            for obj in orientObjects:
                rotBuffer = coreRotationList[cnt]
                rotCheck = sum(rotBuffer)
                if rotCheck != 0:
                    mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],obj,os=True)
                cnt +=1 
                    
            # Control Helpers 
            controlHelpers = controlHelpersReturn[0]
            cnt = 0
            for obj in controlHelpers:
                posBuffer = controlPositionList[cnt]
                posCheck = sum(posBuffer)
                if posCheck != 0:
                    mc.xform(obj,t=[posBuffer[0],posBuffer[1],posBuffer[2]],ws=True)
                
                rotBuffer = controlRotationList[cnt]
                rotCheck = sum(rotBuffer)
                if rotCheck != 0:
                    mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],obj,ws=True)
                
                scaleBuffer = controlScaleList[cnt]
                scaleCheck = sum(scaleBuffer)
                if scaleCheck != 0:
                    mc.scale(scaleBuffer[0],scaleBuffer[1],scaleBuffer[2],obj,absolute=True)
                cnt +=1 """
            
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Final stuff
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            """
            returnList.append(templObjNameList)
            returnList.append(self.templHandleList)
            returnList.append(rootCtrl)"""
            return True	
Example #15
0
def skeletonize(moduleNull, stiffIndex=0):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Basic limb skeletonizer
    
    ARGUMENTS:
    moduleNull(string)
    stiffIndex(int) - the index of the template objects you want to not have roll joints
                      For example, a value of -1 will let the chest portion of a spine 
                      segment be solid instead of having a roll segment. Default is '0'
                      which will put roll joints in every segment
    
    RETURNS:
    limbJoints(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>>Get our info
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    partName = NameFactory.returnUniqueGeneratedName(moduleNull,
                                                     ignore='cgmType')
    """ template null """
    templateNull = modules.returnTemplateNull(moduleNull)
    templateNullData = attributes.returnUserAttrsToDict(templateNull)
    """ template object nulls """
    templatePosObjectsInfoNull = modules.returnInfoTypeNull(
        moduleNull, 'templatePosObjects')
    templateControlObjectsNull = modules.returnInfoTypeNull(
        moduleNull, 'templateControlObjects')
    templatePosObjectsInfoData = attributes.returnUserAttrsToDict(
        templatePosObjectsInfoNull)
    templateControlObjectsData = attributes.returnUserAttrsToDict(
        templateControlObjectsNull)

    jointOrientation = modules.returnSettingsData('jointOrientation')
    moduleRootBuffer = modules.returnInfoNullObjects(moduleNull,
                                                     'templatePosObjects',
                                                     types='templateRoot')
    moduleRoot = moduleRootBuffer[0]
    stiffIndex = templateNullData.get('stiffIndex')
    rollJoints = templateNullData.get('rollJoints')
    """ AutonameStuff """
    divider = NameFactory.returnCGMDivider()
    skinJointsNull = modules.returnInfoTypeNull(moduleNull, 'skinJoints')

    templateObjects = []
    coreNamesArray = []

    #>>>TemplateInfo
    for key in templatePosObjectsInfoData.keys():
        if (mc.attributeQuery(key, node=templatePosObjectsInfoNull,
                              msg=True)) == True:
            templateObjects.append(templatePosObjectsInfoData[key])
        coreNamesArray.append(key)

    posTemplateObjects = []
    """ Get the positional template objects"""
    for obj in templateObjects:
        bufferList = obj.split(divider)
        if (typesDictionary.get('templateObject')) in bufferList:
            posTemplateObjects.append(obj + divider +
                                      typesDictionary.get('locator'))
    """put objects in order of closeness to root"""
    posTemplateObjects = distance.returnDistanceSortedList(
        moduleRoot, posTemplateObjects)
    curve = (templatePosObjectsInfoData['curve'])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Actually making the skeleton with consideration for roll joints and the stiffIndex!
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    if stiffIndex == 0:
        """ If no roll joints """
        limbJoints = joints.createJointsFromCurve(curve, partName, rollJoints)
    else:
        rolledJoints = joints.createJointsFromCurve(curve, partName,
                                                    rollJoints)
        if rollJoints == 0:
            limbJoints = rolledJoints
        else:
            if stiffIndex < 0:
                """ Get our to delete number in a rolledJoints[-4:] format"""
                #searchIndex = (int('%s%s' %('-',(rollJoints+1)))*abs(stiffIndex)-1)
                searchIndex = (int('%s%s' % ('-', (rollJoints + 1))) *
                               abs(stiffIndex))
                toDelete = rolledJoints[searchIndex:]
                """ delete out the roll joints we don't want"""
                mc.delete(toDelete[0])
                for name in toDelete:
                    rolledJoints.remove(name)
                """ make our stiff joints """
                jointPositions = []
                if abs(stiffIndex) == 1:
                    jointPositions.append(
                        distance.returnClosestUPosition(
                            posTemplateObjects[stiffIndex], curve))
                else:
                    for obj in posTemplateObjects[stiffIndex:]:
                        jointPositions.append(
                            distance.returnClosestUPosition(obj, curve))

                stiffJoints = joints.createJointsFromPosListName(
                    jointPositions, 'partName')
                """ connect em up """
                mc.parent(stiffJoints[0], rolledJoints[-1])
                limbJoints = []
                for joint in rolledJoints:
                    limbJoints.append(joint)
                for joint in stiffJoints:
                    limbJoints.append(joint)

            else:
                """ if it's not negative, it's positive...."""
                searchIndex = ((rollJoints + 1) * abs(stiffIndex))
                toDelete = rolledJoints[:searchIndex]
                toKeep = rolledJoints[searchIndex:]
                """ delete out the roll joints we don't want"""
                mc.parent(toKeep[0], world=True)
                mc.delete(toDelete[0])
                for name in toDelete:
                    rolledJoints.remove(name)
                """ make our stiff joints """
                jointPositions = []
                if abs(stiffIndex) == 1:
                    jointPositions.append(
                        distance.returnClosestUPosition(
                            posTemplateObjects[stiffIndex - 1], curve))
                else:
                    for obj in posTemplateObjects[:stiffIndex]:
                        jointPositions.append(
                            distance.returnClosestUPosition(obj, curve))

                stiffJoints = joints.createJointsFromPosListName(
                    jointPositions, 'partName')
                """ connect em up """
                mc.parent(rolledJoints[0], stiffJoints[-1])
                limbJoints = []
                for joint in stiffJoints:
                    limbJoints.append(joint)
                for joint in rolledJoints:
                    limbJoints.append(joint)

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Naming
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ 
    Copy naming information from template objects to the joints closest to them
    copy over a cgmNameModifier tag from the module first
    """
    attributes.copyUserAttrs(moduleNull,
                             limbJoints[0],
                             attrsToCopy=['cgmNameModifier'])
    """
    First we need to find our matches
    """
    for obj in posTemplateObjects:
        closestJoint = distance.returnClosestObject(obj, limbJoints)
        transferObj = attributes.returnMessageObject(obj, 'cgmName')
        """Then we copy it"""
        attributes.copyUserAttrs(
            transferObj,
            closestJoint,
            attrsToCopy=['cgmNameModifier', 'cgmDirection', 'cgmName'])

    limbJointsBuffer = NameFactory.doRenameHeir(limbJoints[0])
    limbJoints = []
    limbJoints.append(limbJointsBuffer[0])
    for joint in limbJointsBuffer[1]:
        limbJoints.append(joint)
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Orientation
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    limbJoints = orientSegment(limbJoints, posTemplateObjects,
                               jointOrientation)

    #>>> Set its radius and toggle axis visbility on
    #averageDistance = distance.returnAverageDistanceBetweenObjects (limbJoints)
    jointSize = (
        distance.returnDistanceBetweenObjects(limbJoints[0], limbJoints[-1]) /
        6)
    for jnt in limbJoints:
        mc.setAttr((jnt + '.radi'), jointSize * .2)
        #>>>>>>> TEMP
        joints.toggleJntLocalAxisDisplay(jnt)

    print 'to orientation'
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    #>>> Storing data
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    skinJointsNull = modules.returnInfoTypeNull(moduleNull, 'skinJoints')
    skinJointsNullData = attributes.returnUserAttrsToList(skinJointsNull)
    existingSkinJoints = lists.removeMatchedIndexEntries(
        skinJointsNullData, 'cgm')
    print existingSkinJoints
    if len(existingSkinJoints) > 0:
        for entry in existingSkinJoints:
            attrBuffer = (skinJointsNull + '.' + entry[0])
            print attrBuffer
            attributes.doDeleteAttr(skinJointsNull, entry[0])

    for i in range(len(limbJoints)):
        buffer = ('%s%s' % ('joint_', i))
        attributes.storeInfo(skinJointsNull, buffer, limbJoints[i])

    return limbJoints
Example #16
0
i_rig = Rig.go(m1,forceNew=False)#call to do general rig
m1.templateNull.handles

rUtils.createEyeballRig('l_eye_rigHelper',aimTargetObject = 'l_eye_ik_anim', buildIK=True)

i_rig.build(i_rig,buildTo = 'controls')
i_rig.buildModule.build_rigSkeleton(i_rig)
i_rig.buildModule.build_shapes(i_rig)
i_rig.buildModule.build_controls(i_rig)
i_rig.buildModule.build_FKIK(i_rig)
i_rig.buildModule.build_deformation(i_rig)
i_rig.buildModule.build_rig(i_rig)
i_rig.buildModule.__build__(i_rig)
from cgm.lib import distance
l_constrainTargetJoints = [u'l_left_index_1_blend_jnt', u'l_left_index_2_blend_jnt', u'l_left_index_3_blend_jnt', u'l_left_index_4_blend_jnt', u'l_left_index_5_blend_jnt']
distance.returnClosestObject('l_left_index_1_rig_jnt',l_constrainTargetJoints)
m1.rigNull.getMessage('blendJoints',False)
m1.moduleParent.rigNull.rigJoints[-1]
i_rig.buildModule.build_matchSystem(i_rig)
reload(Rig)
from cgm.lib import cgmMath
cgmMath.isFloatEquivalent(0.002,0,2)
rUtils.matchValue_iterator(drivenAttr='l_left_index_2_ik_jnt.rz',driverAttr='left_index_noFlip_ikH.twist',minIn = -179, maxIn = 179, maxIterations = 5,matchValue=0)
cgmMeta.cgmObject('l_ankle_ik_anim').scalePivotY = 0
i_rig._i_deformNull.controlsIK

ml_ikJoints = m1.rigNull.ikJoints
ml_fkJoints = m1.rigNull.fkJoints
ml_blendJoints = m1.rigNull.blendJoints
mi_settings = m1.rigNull.settings
Example #17
0
def build_rig(goInstance = None):
    class fncWrap(modUtils.rigStep):
	def __init__(self,goInstance = None):
	    super(fncWrap, self).__init__(goInstance)
	    self._str_funcName = 'build_rig(%s)'%self.d_kws['goInstance']._strShortName	
	    self.__dataBind__()
	    self.l_funcSteps = [{'step':'Build NOT BROKEN UP YET','call':self.build}]	
	    #=================================================================
	    
	def build(self):#================================================================================   	
		    
	    try:#>>>Get data
		orientation = self._go._jointOrientation or modules.returnSettingsData('jointOrientation')
		mi_moduleParent = False
		if self._go._mi_module.getMessage('moduleParent'):
		    mi_moduleParent = self._go._mi_module.moduleParent
		    
		mi_controlIK = self._go._i_rigNull.controlIK
		ml_controlsFK =  self._go._i_rigNull.msgList_get('controlsFK')    
		ml_rigJoints = self._go._i_rigNull.msgList_get('rigJoints')
		ml_blendJoints = self._go._i_rigNull.msgList_get('blendJoints')
		mi_settings = self._go._i_rigNull.settings
		
		log.info("mi_controlIK: %s"%mi_controlIK.getShortName())
		log.info("ml_controlsFK: %s"%[o.getShortName() for o in ml_controlsFK])
		log.info("mi_settings: %s"%mi_settings.getShortName())
		
		log.info("ml_rigJoints: %s"%[o.getShortName() for o in ml_rigJoints])
		log.info("ml_blendJoints: %s"%[o.getShortName() for o in ml_blendJoints])
		
		ml_segmentHandleChains = self._go._get_segmentHandleChains()
		ml_segmentChains = self._go._get_segmentChains()
		ml_influenceChains = self._go._get_influenceChains()	
		
		aimVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[0])
		upVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[1]) 
		
		#Build our contrain to pool
		l_constrainTargetJoints = []
		"""
		for ml_chain in ml_segmentChains:
		    l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_chain[:-1]])
		l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_blendJoints[-2:]])
		"""
		if not l_constrainTargetJoints:
		    l_constrainTargetJoints = [i_jnt.mNode for i_jnt in ml_blendJoints]
		    
		for i_jnt in ml_blendJoints:
		    attributes.doSetLockHideKeyableAttr(i_jnt.mNode,lock=True, visible=True, keyable=False)
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2
		    
		for i_jnt in ml_controlsFK:
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2		    
		    
		#Set group lockks
		for mCtrl in self._go._i_rigNull.msgList_get('controlsAll'):
		    try:mCtrl._setControlGroupLocks()	
		    except Exception,error:log.error("%s _setControlGroupLocks failed on object: %s"%(self._str_reportStart,mCtrl.p_nameShort))
	    	    
	    except Exception,error:
		log.error("finger.build_rig>> Gather data fail!")
		raise Exception,error
	    

	    #Dynamic parent groups
	    #====================================================================================
	    try:#>>>> IK
		ml_fingerDynParents = []
		#Build our dynamic groups
		"""
		1)wrist
		2)fk root
		3)...
		4)world
		"""
		if mi_moduleParent:
		    mi_blendEndJoint = mi_moduleParent.rigNull.msgList_get('blendJoints')[-1]	    
		    mi_parentRigNull = mi_moduleParent.rigNull
		    if mi_moduleParent:
			mi_parentRigNull = mi_moduleParent.rigNull
			buffer = mi_parentRigNull.msgList_get('moduleJoints')
			if buffer:
			    ml_fingerDynParents.append( buffer[-1])	
			
		ml_fingerDynParents.append( ml_controlsFK[0])	
			
		mi_spine = self._go._mi_module.modulePuppet.getModuleFromDict(moduleType= ['torso','spine'])
		if mi_spine:
		    log.info("spine found: %s"%mi_spine)	    
		    mi_spineRigNull = mi_spine.rigNull
		    ml_fingerDynParents.append( mi_spineRigNull.handleIK )	    
		    ml_fingerDynParents.append( mi_spineRigNull.cog )
		    ml_fingerDynParents.append( mi_spineRigNull.hips )	    
		    
		ml_fingerDynParents.append(self._go._i_masterControl)
		if mi_controlIK.getMessage('spacePivots'):
		    ml_fingerDynParents.extend(mi_controlIK.msgList_get('spacePivots',asMeta = True))	
		log.info("%s.build_rig>>> Dynamic parents to add: %s"%(self._go._strShortName,[i_obj.getShortName() for i_obj in ml_fingerDynParents]))
		
	    
		#Add our parents
		i_dynGroup = mi_controlIK.dynParentGroup
		log.info("Dyn group at setup: %s"%i_dynGroup)
		i_dynGroup.dynMode = 0
		
		for o in ml_fingerDynParents:
		    i_dynGroup.addDynParent(o)
		i_dynGroup.rebuild()
		
	    except Exception,error:
		log.error("finger.build_rig>> finger ik dynamic parent setup fail!")
		raise Exception,error
	    
            self._go.collect_worldDynDrivers()#...collect world dyn drivers
	
	    #Make some connections
	    #====================================================================================
	    
	    #Parent and constrain joints
	    #====================================================================================
	    ml_rigJoints[0].parent = self._go._i_deformNull.mNode#shoulder
	    #ml_rigJoints[-1].parent = self._go._i_deformNull.mNode#wrist
	
	    #For each of our rig joints, find the closest constraint target joint
	    log.info("targetJoints: %s"%l_constrainTargetJoints)
	    l_rigJoints = [i_jnt.mNode for i_jnt in ml_rigJoints]
	    for i,i_jnt in enumerate(ml_rigJoints):
		#Don't try scale constraints in here, they're not viable
		log.info("Checking: '%s'"%i_jnt.getShortName())
		attachJoint = distance.returnClosestObject(i_jnt.mNode,l_constrainTargetJoints)
		log.info("'%s'<< drives <<'%s'"%(i_jnt.getShortName(),cgmMeta.cgmNode(attachJoint).getShortName()))
		pntConstBuffer = mc.pointConstraint(attachJoint,i_jnt.mNode,maintainOffset=False,weight=1)
		orConstBuffer = mc.orientConstraint(attachJoint,i_jnt.mNode,maintainOffset=False,weight=1)
		mc.connectAttr((attachJoint+'.s'),(i_jnt.mNode+'.s'))
	     
	    #Setup finger scaling
	    #==================================================================================== 
	    #Parent deform Null to last blend parent
	    if mi_moduleParent:
		mi_blendEndJoint = mi_moduleParent.rigNull.msgList_get('blendJoints')[-1]
		mi_parentBlendPlug = cgmMeta.cgmAttr(mi_blendEndJoint,'scale')
		self._go._i_deformNull.parent = mi_blendEndJoint.mNode
	    
		#connect blend joint scale to the finger blend joints
		for i_jnt in ml_blendJoints:
		    mi_parentBlendPlug.doConnectOut("%s.scale"%i_jnt.mNode)
		    
		#intercept world scale on finger IK and add in the blend wrist scale
		mPlug_moduleMasterScale = cgmMeta.cgmAttr(self._go._i_rigNull,'masterScale',value = 1.0,defaultValue=1.0)
		mPlug_globalScale = cgmMeta.cgmAttr(self._go._i_masterControl.mNode,'scaleY')
		mPlug_globalScale.doConnectOut(mPlug_moduleMasterScale)
		NodeF.argsToNodes("%s = %s * %s.sy"%(mPlug_moduleMasterScale.p_combinedShortName,
			                             mPlug_globalScale.p_combinedShortName,
			                             mi_blendEndJoint.p_nameShort)).doBuild()
	    
	    try:#Vis Network, lock and hide
		#====================================================================================
		#Segment handles need to lock
		for ml_chain in ml_segmentHandleChains:
		    for i_obj in ml_chain:
			attributes.doSetLockHideKeyableAttr(i_obj.mNode,lock=True,
			                                    visible=False, keyable=False,
			                                    channels=['s%s'%orientation[1],
			                                              's%s'%orientation[2]])
			
		attributes.doSetLockHideKeyableAttr(mi_settings.mNode,lock=True,
		                                    visible=False, keyable=False)
		attributes.doSetLockHideKeyableAttr(ml_blendJoints[0].mNode,lock=True,
		                                    visible=True, keyable=False)
		
		for i,mCtrl in enumerate(ml_controlsFK):
		    l_attrs = ['sx','sy','sz','v']
		    if i != 0:
			l_attrs.extend(['tx','ty','tz'])
			
		    attributes.doSetLockHideKeyableAttr(mCtrl.mNode,channels=l_attrs,
		                                        lock=True, visible=False, keyable=False)
		    

		
		attributes.doSetLockHideKeyableAttr(mi_controlIK.mNode,channels=['sx','sy','sz','v'],
	                                            lock=True, visible=False, keyable=False)	    
	    except Exception,error:
		raise Exception,"Lock and hide fail! | {0}".format(error)	 
Example #18
0
def simpleControlSurfaceSmoothWeights(surface,maxBlend = 3):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Early version of a weight smoother for a

    ARGUMENTS:
    surface(string)

    RETURNS:
    Nada
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    cvList = (mc.ls ([surface+'.cv[*][*]'],flatten=True))
    skinCluster = querySkinCluster (surface)
    influenceObjects = queryInfluences (skinCluster)

    #find the closest influence object to the start
    startObject =  (distance.returnClosestObjToCV (cvList[0], influenceObjects))
    #find the closest influence object to the end
    endObject = (distance.returnClosestObjToCV (cvList[-1], influenceObjects))
    #getting the last cv list number
    cvChainLength =  ((len(cvList)-1)/2)

    #Smooth interior weights
    """ get our interior CVs """
    interiorCvList = []
    cnt = 1
    for i in range(cvChainLength):
        interiorCvList.append('%s%s%i%s' % (surface,'.cv[0][',cnt,']'))
        interiorCvList.append('%s%s%i%s' % (surface,'.cv[1][',cnt,']'))
        cnt += 1

    """ overall blend """
    for cv in interiorCvList:
        closestObject = (distance.returnClosestObjToCV (cv, influenceObjects))
        closestObjectsDict = distance.returnClosestObjectsFromAim(closestObject,influenceObjects)
        upObjects = closestObjectsDict.get('up')
        downObjects = closestObjectsDict.get('dn')
        objectsToCheck = []
        if upObjects != None:
            objectsToCheck += upObjects
        if downObjects != None:
            objectsToCheck += downObjects
        blendInfluences =[]
        blendInfluences.append(closestObject)
        distances = []
        cnt = 1
        print objectsToCheck
        while cnt < maxBlend and cnt < len(objectsToCheck):
            closestSubObj = distance.returnClosestObject(closestObject, objectsToCheck)
            blendInfluences.append(closestSubObj)
            objectsToCheck.remove(closestSubObj)
            cnt+=1

        """ get our distances to normalize """
        locBuffer = locators.locMeSurfaceCV(cv)
        for obj in blendInfluences:
            distances.append(distance.returnDistanceBetweenObjects(locBuffer,obj))
        normalizedDistances = cgmMath.normList(distances, normalizeTo=1)
        cnt = 0
        for obj in blendInfluences:
            mc.skinPercent (skinCluster,cv, tv = [obj,normalizedDistances[cnt]])
            cnt +=1
        mc.delete(locBuffer)

    """ Set closest cv's to respective infuences to max """
    cvList1 = []
    cvList2 = []
    for i in range(cvChainLength):
        cvList1.append('%s%s%i%s' % (surface,'.cv[0][',cnt,']'))
        cvList2.append('%s%s%i%s' % (surface,'.cv[1][',cnt,']'))
        cnt += 1
    for obj in influenceObjects:
        closestCV1 = distance.returnClosestCVFromList(obj, cvList1)
        mc.skinPercent (skinCluster,closestCV1, tv = [obj,1])
        closestCV2 = distance.returnClosestCVFromList(obj, cvList2)
        mc.skinPercent (skinCluster,closestCV2, tv = [obj,1])

    #set the skin weights for the top and bottom
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][0:1]'), tv = [startObject,1])
    mc.skinPercent (skinCluster,('%s%s%i%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-1),':',cvChainLength,']')), tv = [endObject,1])
    #Blend in the nearest row to the start and end
    mc.skinPercent (skinCluster,(surface+'.cv[0:1][2]'), tv = [startObject,1])
    mc.skinPercent (skinCluster,('%s%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-2),']')), tv = [endObject,1])

    mc.skinPercent (skinCluster,(surface+'.cv[0:1][3]'), tv = [startObject,.7])
    mc.skinPercent (skinCluster,('%s%s%i%s' % (surface,'.cv[0:1][',(cvChainLength-3),']')), tv = [endObject,.7])