예제 #1
0
def createNurbs(firstJnt='', secondJnt='', jntNum=5):
    posList = []
    posJnt = []
    curveList = []
    # nameing nameRbn
    nameRbn = gn.nameingRbn(firstJnt)
    # get pos form jnt
    posList.extend(list(map(gn.getWorldPosition, [firstJnt, secondJnt])))
    # create posJnt
    mc.select(cl=True)
    jnt = mc.joint(n='pos_CNT_jnt', p=[0, 0, 0])
    mc.select(cl=True)
    ampCon = mc.parentConstraint([firstJnt, secondJnt], jnt)
    posList.append(gn.getWorldPosition(jnt))
    posJnt.append(jnt)
    mc.delete(ampCon)
    # delete posJnt
    map(mc.delete, posJnt)
    # create ampCurve
    ampCurve = mc.curve(n='ampCurve',
                        d=3,
                        ep=[posList[0], posList[2], posList[1]])
    # create NURBS
    for i in range(0, 2):
        curve = mc.duplicate(ampCurve)
        curve = mc.rename(curve, 'curve' + str(i + 1))
        curveList.append(curve)
    curveList.append(ampCurve)
    mc.setAttr(curveList[0] + '.tx', 0.4)
    mc.setAttr(curveList[1] + '.tx', -0.4)
    # loft
    mc.loft(curveList[1],
            curveList[0],
            n=nameRbn,
            ch=True,
            u=True,
            c=False,
            ar=1,
            d=1,
            ss=1,
            rn=False,
            po=False,
            rsn=True)
    # delete curveList
    map(mc.delete, curveList)
    # rebuild Surface
    mc.rebuildSurface(nameRbn,
                      ch=1,
                      rpo=1,
                      end=1,
                      kr=0,
                      kcp=0,
                      su=0,
                      du=3,
                      sv=0,
                      dv=1,
                      tol=0.01,
                      fr=0,
                      dir=2)
    return nameRbn
예제 #2
0
def createRibbonFromNodes(sName, lNodes, bAuto = False, sDirection = 'x', fWidth = 1, bNormalize = True, sParent = None):
	sCrvA = curves.createCurveOnNodes('RIBBON_TEMP_001', lNodes, iDegree = 3)
	sCrvB = curves.createCurveOnNodes('RIBBON_TEMP_002', lNodes, iDegree = 3)
	if bAuto:
		sJntA = joints.createJntOnExistingNode(lNodes[0], lNodes[0], 'RIBBON_TEMP_AIM_001')
		sJntB = joints.createJntOnExistingNode(lNodes[-1], lNodes[-1], 'RIBBON_TEMP_AIM_002')
		cmds.parent(sJntB, sJntA)
		cmds.joint(sJntA, edit = True, oj = 'xyz', secondaryAxisOrient = 'yup', ch = True, zso = True)
		sOffsetA = transforms.createTransformNode('RIBBON_TEMP_OFFSET_001', sParent = sJntA, sPos = sJntA)
		sOffsetB = transforms.createTransformNode('RIBBON_TEMP_OFFSET_002', sParent = sJntA, sPos = sJntA)
		cmds.parent(sCrvA, sOffsetA)
		cmds.parent(sCrvB, sOffsetB)
		cmds.setAttr('%s.tz' %sOffsetA, fWidth * 0.5)
		cmds.setAttr('%s.tz' %sOffsetB, -fWidth * 0.5)
		cmds.parent(sCrvA, world = True)
		cmds.parent(sCrvB, world = True)
		cmds.makeIdentity(sCrvA, t = 1, r = 1, s = 1, apply = True)
		cmds.makeIdentity(sCrvB, t = 1, r = 1, s = 1, apply = True)
		cmds.delete(sJntA)
	else:
		cmds.setAttr('%s.t%s' %(sCrvA, sDirection), fWidth * 0.5)
		cmds.setAttr('%s.t%s' %(sCrvB, sDirection), -fWidth * 0.5)
	cmds.loft(sCrvA, sCrvB, ch=False, u = True, c = False, rn=False, ar=True, d = 3, ss = 1, rsn = True,name = sName)

	if bNormalize:
		cmds.rebuildSurface(sName, ch = False, su = len(lNodes) - 1, sv = 1, dv = 3, du = 3)
	cmds.delete(sCrvA, sCrvB)
	if sParent and cmds.objExists(sParent):
		cmds.parent(sName, sParent)

	return sName
예제 #3
0
    def ribbonFromCrv(cls, crv, span):
        '''
		Create nurbs ribbon with a curve.
		'''

        # Attach stroke to curve.
        strkDens = 1
        strkWidth = 0.1

        cmds.select(crv, r=True)

        cmds.AttachBrushToCurves()
        strk = cmds.ls(sl=True)[0]
        strkShp = cmds.listRelatives(strk, s=True)[0]
        brush = cmds.listConnections(strkShp, s=True, type='brush')[0]

        cmds.setAttr('%s.sampleDensity' % strkShp, strkDens)
        cmds.setAttr('%s.smoothing' % strkShp, 1)
        cmds.setAttr('%s.brushWidth' % brush, strkWidth)
        cmds.setAttr('%s.flatness1' % brush, 1)

        # Convert stroke paint effect to ribbon.
        cmds.select(strk, r=True)
        mel.eval('doPaintEffectsToNurbs(1);')
        cmds.hyperShade(assign='lambert1')

        # Rebuild nurbs plane
        ribbon = cmds.listRelatives(c=True)[0]
        cmds.rebuildSurface(ribbon,
                            ch=1,
                            rpo=1,
                            rt=0,
                            end=1,
                            kr=0,
                            kcp=0,
                            kc=0,
                            su=1,
                            du=3,
                            sv=span,
                            dv=3,
                            tol=0.01,
                            fr=0,
                            dir=2)
        cls.ribbon = cmds.rename(ribbon, crv + '_ribbon')

        # Clean up
        cmds.parent(cls.ribbon, w=True)
        cmds.delete(cls.ribbon, ch=True)
        cmds.delete(strk, strkShp + 'Surfaces')
        cmds.delete(brush + 'Shader', brush + 'ShaderSG')

        return cls.ribbon
예제 #4
0
파일: hair.py 프로젝트: akoon/OldPipeline
    def rebuildSurface(self):
        #rebuildSurface -ch 1 -rpo 1 -rt 0 -end 1 -kr 0 -kcp 0 -kc 0 
        #    -su 20 -du 3 -sv 10 -dv 3 -tol 0.0001 -fr 0  -dir 2 "nurbsSphere1";
        uspans = 20
        vspans = 10
        try:
            uspans = int(str(self.rebuiltU.text()))
            vspans = int(str(self.rebuiltV.text()))
        except:
            return False

        selects = mc.ls(sl = True)
        for select in selects:
            mc.rebuildSurface(select, ch = False, rpo = True, rt = 0, end = 1, kr = 0, kcp = False,\
                                kc = False, su = uspans, du = 3, sv = vspans, dv = 3, tol = 0.0001,\
                                fr = 0, dir = 2)

        mc.select(selects, r = True)
예제 #5
0
파일: KstRig.py 프로젝트: Leopardob/Kistie
    def create_surface_from_curves(self, curves_list, surface_degree = 'linear', surface_type = 'nurbs', normalize = True, surface_name=''):
        '''
        Description: create a surface (poly or nurbs) froma a curve list
        curve_list = curve list
        surface_degree = surface degree can be: "linear" or "cubic"
        surface_type = type of surface output can be: "mesh" or "nurbs"
        normalize = if True normalize the surface from 0 to 1, reccomended, default in fact is True

        return surface
        '''

        # Check if curve_list is valid
        if(curves_list):
            # Create and empty var for loft command
            loft_srf = ''

            # Define variables for loft based on inputs
            # degree
            if surface_degree == 'linear':
                srf_deg = 1

            elif surface_degree == 'cubic':
                srf_deg = 3

            # output surface
            if surface_type == 'mesh':
                srf_type = 1

            elif surface_type == 'nurbs':
                srf_type = 0

            # Build the command that will be execute
            str_loft = "loft_srf = cmds.loft("
            for crv in curves_list:
                str_loft += "'%s'," % crv
            str_loft += "ch=True, u=True, c=False, ar=True, d=%s, ss=True, rn=False, po=%s" % (srf_deg, srf_type)
            str_loft +=')'
            KstOut.debug(KstRig._debug, 'Command that will be executed:')
            #print(str_loft)
            #print ''

            # Execute the builded command
            try:
                exec(str_loft)
            except:
                KstOut.debug(KstRig._debug, 'Error on execute command !!!')
                pass

            loft_srf = cmds.rename(loft_srf[0], surface_name+'_SRF')

            if normalize:
                loft_srf = cmds.rebuildSurface(loft_srf, ch=True, rpo=True, rt=0, end=1, kr=0, kcp=True, kc=False, su=3, du=1, sv=1, dv=1, tol=0.01, fr=0, dir=2)

            return loft_srf
        else:
            KstOut.debug(KstRig._debug, 'Check if input are valid')
            KstOut.error(KstRig._debug, 'Check if input are valid')
def doCreate(*args):
    sl = api2.MGlobal.getActiveSelectionList()
    if sl.length() == 0L:
        return
    dag,obj = sl.getComponent(0)
    sic = api2.MFnSingleIndexedComponent(obj)
    ids = sic.getElements()

    faceIter = api2.MItMeshPolygon(dag)

    srfs = []
    fullPath = dag.fullPathName()
    for i in xrange(len(ids)):
        faceIter.setIndex(ids[i])
        intArray = faceIter.getEdges()
        patch = cmds.loft('%s.e[%d]' %(fullPath,intArray[2]),'%s.e[%d]' %(fullPath,intArray[0]),d=1,ch=False)
        cmds.rebuildSurface(patch,ch=False,rpo=1,rt=0,end=1,kr=0,kcp=1,kc=0,su=0,du=1,sv=0,dv=1,fr=0,dir=2)
        srfs.append(patch[0])
    cmds.select(srfs)
    return 0
예제 #7
0
def buildRibbonSurface(locators,name = '',close = False,vector = [1,0,0],width = 10):

    lineCrvs = []
    
    for locator in locators:
    
        pos = cmds.xform(locator,q = True,ws = True,rp = True)
        
        posVector = om.MVector(pos[0],pos[1],pos[2])
        
        inverseWidth = width * -1
        
        translateVectorForward = om.MVector(vector[0] * width,vector[1] * width,vector[2] * width)
        translateVectorBackward = om.MVector((vector[0] * inverseWidth),(vector[1] * inverseWidth),(vector[2] * inverseWidth))
        
        startTransformationMatrix = om.MTransformationMatrix()
        startTransformationMatrix.setTranslation(posVector,om.MSpace.kWorld)
        startTransformationMatrix.addTranslation(translateVectorForward,om.MSpace.kObject)
        startPosVector = startTransformationMatrix.getTranslation(om.MSpace.kWorld)
        
        endTransformationMatrix = om.MTransformationMatrix()
        endTransformationMatrix.setTranslation(posVector,om.MSpace.kWorld)
        endTransformationMatrix.addTranslation(translateVectorBackward,om.MSpace.kObject)
        endPosVector = endTransformationMatrix.getTranslation(om.MSpace.kWorld)
        
        startPos = [startPosVector.x,startPosVector.y,startPosVector.z]
        endPos = [endPosVector.x,endPosVector.y,endPosVector.z]
        lineCrv = cmds.curve(d = 1,p = (startPos,endPos))
        lineCrvs.append(lineCrv)
        
    ribbonOrig = cmds.loft(lineCrvs,ch = 1,u = 1,c = close,ar = 1,d = 3,ss = 1,rn = 0 ,po = 0, rsn = True,n = '%s_Surface'%name)
    ribbonRebuild = cmds.rebuildSurface(ribbonOrig[0],ch = 1,rpo = 1,rt = 0,end = 1,kr = 0,kcp = 1,kc = 0,su = 8,du = 1,sv = 2,dv = 3,tol = 0.01,fr = 0, dir = 2)
    
    ribbon = []
    
    shape = cmds.listRelatives(ribbonRebuild[0], type = 'shape')[0]
    ribbon.append(ribbonRebuild[0])
    ribbon.append(shape)
    cmds.delete(ribbonOrig[0],ch = True)
    cmds.delete(lineCrvs)
    return ribbon
예제 #8
0
def makeRibbon(point1, point2, width, module, side, u, v):
    #crear curva
    
    point1 = cmds.xform(point1, ws=True, q=True, t=True)
    point2 = cmds.xform(point2, ws=True, q=True, t=True)
    
    
    cur = cmds.curve(p=[point1, point2], degree=1)    
    
        #crear NURBS
    cur1 = cmds.duplicate(cur)
    cmds.move(width, cur1, x=True)
    
    cur2 = cmds.duplicate(cur)   
    cmds.move(width*(-1), cur2, x=True) 
    
    nurb = cmds.loft(cur1, cur2)
    cmds.delete(nurb[1])
    nurb = cmds.rename(nurb[0], '{}_{}_nurbs'.format(module, side))
    for c in [cur1, cur2, cur]:
        cmds.delete(c)
        #rebuild NURBS
    reb = cmds.rebuildSurface(nurb, su=u, sv=v)    
    return reb
예제 #9
0
def makeVolumeEars(smartParentTarget, smartDupTargets, side, sides):

    ###############################################################################################################################################
    # --- ears smart Rig
    #smartParentTarget = 'head_gimbal_ctrl'
    #smartDupTargets = ['L_ear_fk_ctrl_01_orig','R_ear_fk_ctrl_01_orig']
    earsNoXformGrp = 'ears_ctrl_noXformGrp'
    WORLDGrp = 'WORLD'
    ## --- create noXform Grp for ears
    mc.group(n=earsNoXformGrp, em=True)
    mc.parent(earsNoXformGrp, WORLDGrp)
    mc.hide(earsNoXformGrp)

    # --- duplicate the base of the fkHierarchy, will be use as base of smart hierarchy
    smartParent = mc.duplicate(smartParentTarget,
                               po=True,
                               n='%s_smart' % smartParentTarget)[0]
    mc.parent(smartParent, earsNoXformGrp)
    # --- duplicate all of the fks in one go to create fk_smarts
    smartsList = mc.duplicate(smartDupTargets)
    for i, each in enumerate(smartDupTargets):
        mc.parent(smartsList[i], w=True)

    # --- goes into the hierarchy of duplicated Fks and counts the depth of the hierarchy. stops when arrived at end of hierarchy
    hierarchyDepthList = []
    for i, each in enumerate(smartDupTargets):
        hierarchyDepth = 0
        nexChild = ''
        stopLoop = False
        for j in range(0, 20):
            if j == 0:
                nexChild = each
            getChild = mc.listRelatives(nexChild, c=True, f=True)
            if getChild:
                for child in getChild:
                    if not mc.objectType(child) == 'nurbsCurve':
                        if mc.objectType(child) == 'joint':
                            splittedName1 = child.rsplit('|')[-1]
                            splittedName2 = splittedName1.split('offset')

                            checkEnd = splittedName1.rsplit('_', 1)[-1]

                            if not len(splittedName2) > 1:
                                if not checkEnd == 'end':
                                    nexChild = child
                                else:
                                    stopLoop = True
                                    hierarchyDepthList.append(j)
                                    break
            if stopLoop == True:
                break
        mc.delete(smartsList[i])
    # --- derives controls loop from hierarchy depth
    smartLoopLenthList = []
    for each in hierarchyDepthList:
        loopLength = (each / 2) + 2
        smartLoopLenthList.append(loopLength)

    # --- recreates hierarchy as smart nodes

    for i, each in enumerate(smartDupTargets):
        loop = smartLoopLenthList[i]
        baseName = each.split('_ctrl_', 1)[0]
        ctrlName = 'ctrl'
        offsetName = 'offset'
        suff = '_smart'
        makeShape = False
        color = None

        parentNext = smartParent
        for j in range(0, loop):
            num = j + 1

            if j < loop - 1:
                if j == 0:
                    doOffset = False
                    newCtrls = createFKSection(baseName, ctrlName, offsetName,
                                               num, suff, doOffset, makeShape,
                                               color)
                    mc.parent(newCtrls[1], parentNext)

                    trgt = newCtrls[0].rsplit('_', 1)[0]
                    origTrgt = newCtrls[1].rsplit('_', 1)[0]
                    smartConnect(trgt, newCtrls[0])
                    smartConnect(origTrgt, newCtrls[1])
                    parentNext = newCtrls[0]

                else:
                    doOffset = True
                    newCtrls = createFKSection(baseName, ctrlName, offsetName,
                                               num, suff, doOffset, makeShape,
                                               color)
                    mc.parent(newCtrls[0][1], parentNext)

                    trgt = newCtrls[0][0].rsplit('_', 1)[0]
                    origTrgt = newCtrls[0][1].rsplit('_', 1)[0]
                    offsetTrgt = newCtrls[1][0].rsplit('_', 1)[0]
                    origOffsetTrgt = newCtrls[1][1].rsplit('_', 1)[0]
                    smartConnect(trgt, newCtrls[0][0])
                    smartConnect(origTrgt, newCtrls[0][1])
                    smartConnect(offsetTrgt, newCtrls[1][0])
                    smartConnect(origOffsetTrgt, newCtrls[1][1])
                    parentNext = newCtrls[0][0]

            if j == loop - 1:
                mc.select(cl=True)
                endJoint = mc.joint(n='%s_%s_end_smart' % (baseName, ctrlName))
                endOffsetOrig = mc.joint(
                    n='%s_%s_%s_%02d_orig_smart' %
                    (baseName, offsetName, ctrlName, loop))
                endOffset = mc.joint(n='%s_%s_%s_%02d_smart' %
                                     (baseName, offsetName, ctrlName, loop))

                mc.setAttr('%s.radius' % endJoint, 0.1)
                mc.setAttr('%s.radius' % endOffsetOrig, 0.1)
                mc.setAttr('%s.drawStyle' % endOffsetOrig, 2)
                mc.setAttr('%s.radius' % endOffset, 0.1)

                mc.parent(endJoint, parentNext)
                smartConnect('%s_%s_end' % (baseName, ctrlName), endJoint)
                smartConnect(
                    '%s_%s_%s_%02d_orig' %
                    (baseName, offsetName, ctrlName, loop), endOffsetOrig)
                smartConnect(
                    '%s_%s_%s_%02d' % (baseName, offsetName, ctrlName, loop),
                    endOffset)

    # --- creates volumeSurf and deforms for ears //temporary use of firstSurf
    rigPart = 'ear'
    deformGrp = 'ctrl_DeformGrp'
    endSurfDeformGrp = 'ears_endSurf_%s' % deformGrp

    # --- assign values for columeSurf characteristics
    volspansV = 16
    volspansU = 8
    volDeg = 3
    ## ---creates ears volSurfaces
    earCurveGUIDEList = [
        'L_topEar_curve_GUIDE', 'L_topMidtEar_curve_GUIDE',
        'L_midtEar_curve_GUIDE', 'L_botMidEar_curve_GUIDE',
        'L_BotEar_curve_GUIDE'
    ]
    earVolSurfList = []
    # --- create left volume surface
    duplicatedCurves = mc.duplicate(earCurveGUIDEList)
    loftCurves = []
    mc.parent(duplicatedCurves, w=True)
    for u, curve in enumerate(duplicatedCurves):
        curveName = str(curve)
        strippedName = curveName.rsplit('_', 1)[0]
        loftCurves.append(mc.rename(curve, '%s_loftCurve' % strippedName))
    loftCurves = loftCurves[::-1]
    volSurf = mc.loft(loftCurves,
                      ch=False,
                      ar=False,
                      d=3,
                      u=True,
                      n='L_%s_volume_surfNurbs' % rigPart)[0]
    mc.rebuildSurface(volSurf,
                      rt=0,
                      su=volspansU,
                      sv=volspansV,
                      kc=True,
                      ch=False)
    mc.delete(loftCurves)
    mc.parent(volSurf, earsNoXformGrp)
    earVolSurfList.append(volSurf)
    # --- creates right ear surf from scale
    rVolsurf = mc.duplicate(volSurf, n='R_%s_volume_surfNurbs' % rigPart)[0]
    rVolsurfUSpans = mc.getAttr('%s.spansU' % rVolsurf)
    rVolsurfVSpans = mc.getAttr('%s.spansV' % rVolsurf)
    rVolsurfUDeg = mc.getAttr('%s.degreeU' % rVolsurf)
    rVolsurfVDeg = mc.getAttr('%s.degreeV' % rVolsurf)
    rVolsurfUCount = rVolsurfUSpans + rVolsurfUDeg
    rVolsurfVCount = rVolsurfVSpans
    for u in range(0, rVolsurfUCount):
        for v in range(0, rVolsurfVCount):
            pointPos = mc.pointPosition('%s.cv[%d][%d]' % (rVolsurf, u, v))
            mc.move(-pointPos[0],
                    pointPos[1],
                    pointPos[2],
                    '%s.cv[%d][%d]' % (rVolsurf, u, v),
                    a=True,
                    ws=True)
    mc.reverseSurface(rVolsurf, d=1, ch=False)
    earVolSurfList.append(rVolsurf)

    mc.group(n=endSurfDeformGrp, em=True)
    mc.parent(endSurfDeformGrp, smartParentTarget)
    volumeEarsDeformSKNList = []
    for s, surf in enumerate(earVolSurfList):
        ## --- creates and attaches jointsCloud
        side = sides[s]
        sideEndSurfDeformGrp = '%s_%s' % (side, endSurfDeformGrp)
        mc.group(n=sideEndSurfDeformGrp, em=True)
        mc.parent(sideEndSurfDeformGrp, endSurfDeformGrp)

        UDeformsCount = 9
        VDeformCount = 10
        endSurf = surf
        tempPOSI = tempPOSI = mc.createNode('pointOnSurfaceInfo',
                                            n='volumeSpine_temp_posi')
        mc.setAttr('%s.turnOnPercentage' % tempPOSI, True)
        mc.connectAttr('%s.worldSpace[0]' % endSurf,
                       '%s.inputSurface' % tempPOSI)
        for i in range(0, UDeformsCount - 1):
            for j in range(0, VDeformCount - 1):
                ## --- creates deform ctrl/skin hierarchy
                mc.select(cl=True)
                deformSkn = mc.joint(n='%s_%s_deform_U%02d_V%02d_SKN' %
                                     (side, rigPart, i, j))
                mc.setAttr('%s.radius' % deformSkn, 0.01)
                mc.select(cl=True)
                deformCtrl = mc.joint(n='%s_%s_deform_U%02d_V%02d_ctrl' %
                                      (side, rigPart, i, j))
                mc.setAttr('%s.radius' % deformCtrl, 0.01)
                mc.setAttr('%s.drawStyle' % deformCtrl, 2)
                smartConnect(deformCtrl, deformSkn)
                shapes.create(deformCtrl,
                              shape='pyramidDouble',
                              size=0.05,
                              scale=[1, 1, 1],
                              axis='y',
                              twist=0,
                              offset=[0, 0, 0],
                              color=[0.5, 0, 0.5],
                              colorDegradeTo=None,
                              replace=True,
                              middle=False)
                deformOrig = orig.orig(objlist=[deformCtrl],
                                       suffix=['_orig'],
                                       origtype='joint',
                                       fromsel=False,
                                       viz=False,
                                       get_ssc=False,
                                       rtyp='auto')[0]
                deformAuto = orig.orig(objlist=[deformCtrl],
                                       suffix=['_auto'],
                                       origtype='joint',
                                       fromsel=False,
                                       viz=False,
                                       get_ssc=False,
                                       rtyp='auto')[0]
                mc.parent(deformSkn, deformAuto)
                volumeEarsDeformSKNList.append(deformSkn)
                ## --- getWorld Position placement for deform orig from UV
                UValue = ((1.000 / (UDeformsCount - 1)) * i)
                VValue = ((1.000 / (VDeformCount - 1)) * j)
                mc.setAttr('%s.parameterU' % tempPOSI, UValue)
                mc.setAttr('%s.parameterV' % tempPOSI, VValue)
                ctrlPos = mc.getAttr('%s.position' % tempPOSI)[0]
                mc.setAttr('%s.translate' % deformOrig, ctrlPos[0], ctrlPos[1],
                           ctrlPos[2])
                ## --- attach deformer ctrl/joints to endSurface
                xrivetTrOnNurbs(deformOrig,
                                endSurf,
                                mainDirection=1,
                                out='worldSpace[0]',
                                u=None,
                                v=None,
                                offsetOrient=[0, 0, 0],
                                min=False)
                ## --- reparent deform origs into rig
                mc.parent(deformOrig, sideEndSurfDeformGrp)
        mc.select(cl=True)
        mc.delete(tempPOSI)

    ## --- TempCleanup of ears sets
    volumeEarsSkinSet = 'volume_ears_skin_set'
    mc.sets(volumeEarsDeformSKNList, n=volumeEarsSkinSet)
    mc.sets(volumeEarsSkinSet, add='skin_set')
    ### --- disconnect inverseScale on ears to allow headScale
    fkEarsOrigs = ['L_ear_fk_ctrl_01_orig', 'R_ear_fk_ctrl_01_orig']
    for earOrig in fkEarsOrigs:
        mc.disconnectAttr('head_gimbal_ctrl.scale',
                          '%s.inverseScale' % earOrig)
예제 #10
0
def buildEyeballGeo():
    #     try:
    # create eyeball controler-----------------------------------------------------------------------------------------
    gEyeballCtrler = cmds.spaceLocator()[0]
    cmds.addAttr(longName='pupilSize', attributeType='float', keyable=True, defaultValue=gDefaultPupilValue)
    cmds.addAttr(longName='irisSize', attributeType='float', keyable=True, defaultValue=gDefaultIrisValue)
    cmds.addAttr(longName='irisConcave', attributeType='float', keyable=True, defaultValue=gDefaultIrisConcaveValue)
    cmds.addAttr(longName='corneaBulge', attributeType='float', keyable=True, defaultValue=gDefaultCorneaBulgeValue)

    # cornea-----------------------------------------------------------------------------------------
    # create eyeball base geometry and detach
    eyeballSphere = cmds.sphere(sections=20, spans=20, axis=(0, 0, 1), radius=0.5)[0]
    #     eyeballSphere=eyeballSphere[0]
    pieceNames = cmds.detachSurface(eyeballSphere, ch=1, rpo=1, parameter=(0.1, 20))
    corneaGeo = pieceNames[0];
    corneaDetach = pieceNames[2];
    cmds.parent(eyeballSphere, gEyeballCtrler, relative=True)
    cmds.parent(corneaGeo, gEyeballCtrler, relative=True)

    # rebuild corneaGeo
    cmds.rebuildSurface(corneaGeo, ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kc=0, su=36, du=3, sv=1, dv=3, tol=0.01, fr=0,
                        dir=0)

    # add lattice and deform cornea
    cmds.select(corneaGeo)
    (corneaLat, corneaLatGeo, corneaLatGeoBase) = cmds.lattice(dv=(2, 2, 6), oc=False)
    cmds.setAttr(corneaLatGeo + '.scale', 1.1, 1.1, 1.1)
    cmds.setAttr(corneaLatGeoBase + '.scale', 1.1, 1.1, 1.1)
    cmds.setAttr(corneaGeo + '.overrideEnabled', 1)
    cmds.setAttr(corneaGeo + '.overrideColor', 3)

    corneaDetachRider = cmds.createNode('transform')
    corneaDeformGrp = cmds.createNode('transform')
    corneaRadius = cmds.createNode('transform')

    cmds.parent(corneaDeformGrp, corneaDetachRider, relative=True)
    cmds.parent(corneaRadius, corneaDetachRider, relative=True)
    cmds.parent(corneaLatGeo, corneaDeformGrp, relative=True)
    cmds.parent(corneaLatGeoBase, corneaDeformGrp, relative=True)
    cmds.parent(corneaDetachRider, gEyeballCtrler, relative=True)

    cmds.hide(corneaDetachRider)

    # set opaque for Arnold render
    if gRenderer == 'mtoa':
        corneaGeoShape = cmds.listRelatives(corneaGeo, shapes=True)[0]
        cmds.setAttr(corneaGeoShape + '.aiOpaque', 0)


        # iris-----------------------------------------------------------------------------------------
    # create eyeball base geometry and detach
    eyeballSphere2 = cmds.sphere(sections=20, spans=20, axis=(0, 0, 1), radius=0.5)[0]
    pieceNames = cmds.detachSurface(eyeballSphere2, ch=1, rpo=1, parameter=(0.1, 20))
    irisGeo = pieceNames[0]
    irisDetach = pieceNames[2]
    cmds.delete(eyeballSphere2)
    cmds.parent(irisGeo, gEyeballCtrler, relative=True)

    # add lattice and deform iris
    cmds.select(irisGeo)
    (irisLat, irisLatGeo, irisLatGeoBase) = cmds.lattice(dv=(2, 2, 2), oc=False)
    cmds.setAttr(irisLatGeo + '.scale', 1.1, 1.1, -2)
    cmds.setAttr(irisLatGeoBase + '.scale', 1.1, 1.1, 2)
    cmds.setAttr(irisLatGeo + '.translateZ', -0.5)
    cmds.setAttr(irisLatGeoBase + '.translateZ', -0.5)
    cmds.setAttr(irisGeo + '.overrideEnabled', 1)
    cmds.setAttr(irisGeo + '.overrideColor', 13)

    irisDetachRider = cmds.createNode('transform')
    irisDeformGrp = cmds.createNode('transform')
    irisRadius = cmds.createNode('transform')

    cmds.parent(irisDeformGrp, irisDetachRider, relative=True)
    cmds.parent(irisRadius, irisDetachRider, relative=True)
    cmds.parent(irisLatGeo, irisDeformGrp, relative=True)
    cmds.parent(irisLatGeoBase, irisDeformGrp, relative=True)
    cmds.parent(irisDetachRider, gEyeballCtrler, relative=True)

    cmds.hide(irisDetachRider)

    # pupil-----------------------------------------------------------------------------------------
    # detach from iris geometry
    pieceNames = cmds.detachSurface(irisGeo, ch=1, rpo=1, parameter=(0.1, 20))
    pupilGeo = pieceNames[0]
    pupilDetach = pieceNames[2]
    cmds.parent(pupilGeo, gEyeballCtrler, relative=True)
    cmds.setAttr(pupilGeo + '.overrideEnabled', 1)
    cmds.setAttr(pupilGeo + '.overrideColor', 17)

    # connect attributes-----------------------------------------------------------------------------------------
    expressionStr = '''
                        //calculate cornea-related parameters
                        //cornea translate Z
                        float $cornea_tz = (cos(deg_to_rad(''' + gEyeballCtrler + '''.irisSize*9.0))) * 0.5;
                        //cornea radius
                        float $cornea_rad  = (sin(deg_to_rad(''' + gEyeballCtrler + '''.irisSize*9.0))) * 0.5;
                        //define nurbs surface cornea detach position
                        float $cornea_par  = ((1.0 - linstep( 0.0,10.0,''' + gEyeballCtrler + '''.irisSize)) * 10.0 ) + 10.0;
                        ''' + corneaDetach + '''.parameter[0] = $cornea_par;
                        ''' + corneaDetachRider + '''.translateZ = $cornea_tz;
                        ''' + corneaRadius + '''.translateX = $cornea_rad;
                        ''' + corneaDeformGrp + '''.translateZ = ( 0.5 - $cornea_tz ) * 0.5;
                        ''' + corneaDeformGrp + '''.scaleX = ''' + corneaDeformGrp + '''.scaleY = $cornea_rad * 2.0;
                        ''' + corneaDeformGrp + '''.scaleZ = ( 0.5 - $cornea_tz );
                        ''' + corneaLat + '''.envelope = (1.0 - (smoothstep(0.0,11.0,''' + gEyeballCtrler + '''.irisSize))) * (''' + gEyeballCtrler + '''.corneaBulge * 0.1);
                        
                        //calculate iris-related parameters
                        float $iris_tz   = ( cos(deg_to_rad((''' + gEyeballCtrler + '''.irisSize+0.3)*9.0)) ) * 0.485;
                        float $iris_rad  = ( sin(deg_to_rad((''' + gEyeballCtrler + '''.irisSize+0.3)*9.0)) ) * 0.485;
                        float $iris_par  = ((1.0 - ((''' + gEyeballCtrler + '''.irisSize+0.3)*0.1)) * 10.0 ) + 10.0;
                        ''' + irisDetach + '''.parameter[0] = $iris_par;
                        ''' + irisDetachRider + '''.translateZ = $iris_tz;
                        ''' + irisRadius + '''.translateX = $iris_rad;
                        ''' + irisDeformGrp + '''.translateZ = ( 0.5 - $iris_tz ) * 0.5;
                        ''' + irisDeformGrp + '''.scaleX = ''' + irisDeformGrp + '''.scaleY = $iris_rad * 2.0;
                        ''' + irisDeformGrp + '''.scaleZ = ( 0.5 - $iris_tz );
                        ''' + irisLat + '''.envelope = ''' + gEyeballCtrler + '''.irisConcave * 0.1;
                        
                        float $pupil_par = max( (((1.0 - ((''' + gEyeballCtrler + '''.pupilSize)*0.1)) * 10.0 ) + 10.0), $iris_par + 0.1 );
                        ''' + pupilDetach + '''.parameter[0] = $pupil_par;
                        '''

    cmds.expression(s=expressionStr)

    # deform latticeGeo
    for x in range(0, 2):
        for y in range(0, 2):
            for z in range(3, 6):
                pointNameStr = corneaLatGeo + '.pt[' + str(x) + '][' + str(y) + '][' + str(z) + ']'
                ptTranslateZ = cmds.getAttr(pointNameStr + '.zValue')
                cmds.setAttr(pointNameStr + '.zValue', ptTranslateZ * 2 + 0.319)
            #                     cmds.select(pointNameStr)
            #                     cmds.move(0, 0, 0.05, r=True)

            # rename objects------------------------------------
    gEyeballCtrlerName = 'eyeballCtrler'

    cmds.rename(gEyeballCtrler, gEyeballCtrlerName)
    cmds.rename(pupilGeo, 'pupilGeo')
    cmds.rename(pupilDetach, 'pupilDetach')

    cmds.rename(irisLat, 'irisLat')
    cmds.rename(irisLatGeo, 'irisLatGeo')
    cmds.rename(irisLatGeoBase, 'irisLatGeoBase')
    cmds.rename(irisGeo, 'irisGeo')
    cmds.rename(irisDetach, 'irisDetach')
    cmds.rename(irisDetachRider, 'irisDetachRider')
    cmds.rename(irisDeformGrp, 'irisDeformGrp')
    cmds.rename(irisRadius, 'irisRadius')
    cmds.rename(corneaLat, 'corneaLat')
    cmds.rename(corneaLatGeo, 'corneaLatGeo')
    cmds.rename(corneaLatGeoBase, 'corneaLatGeoBase')
    cmds.rename(eyeballSphere, 'eyeballSphere')
    cmds.rename(corneaGeo, 'corneaGeo')
    cmds.rename(corneaDetach, 'corneaDetach')
    cmds.rename(corneaDetachRider, 'corneaDetachRider')
    cmds.rename(corneaDeformGrp, 'corneaDeformGrp')
    cmds.rename(corneaRadius, 'corneaRadius')
예제 #11
0
파일: generic.py 프로젝트: BenBarker/mpyr
    def build(self):
        self.addPinParent()
        self.addAttrLimb(ln='noStretch',
                         at='float',
                         min=0,
                         max=1,
                         dv=0,
                         k=True,
                         s=1)
        self.addAttrLimb(ln='slideAlong',
                         at='float',
                         min=-1,
                         max=1,
                         dv=0,
                         k=True,
                         s=1)
        jointList = mpJoint.getJointList(self.startJoint, self.endJoint)
        if len(jointList) < 2:
            raise RuntimeError(
                'NurbsStrip requires at least 2 joints in chain. Got %s' %
                len(jointList))

        #Create NURBS strip by making curves along joints, and a cross section crv, then extruding
        crv = mpNurbs.curveFromNodes(jointList)
        crossCurve = cmds.curve(d=1,
                                p=[(0, 0, -0.5 * self.stripWidth),
                                   (0, 0, 0.5 * self.stripWidth)],
                                k=(0, 1))
        cmds.select([crossCurve, crv], r=1)
        surf = cmds.extrude(ch=False,
                            po=0,
                            et=2,
                            ucp=1,
                            fpt=1,
                            upn=1,
                            rotation=0,
                            scale=1,
                            rsp=1)[0]
        cmds.delete([crv, crossCurve])
        self.name.desc = 'driverSurf'
        surf = cmds.rename(surf, self.name.get())
        cmds.parent(surf, self.noXform)

        #Rebuild strip to proper number of spans
        cmds.rebuildSurface(surf,
                            ch=0,
                            rpo=1,
                            rt=0,
                            end=1,
                            kr=0,
                            kcp=0,
                            kc=1,
                            sv=self.numSpans,
                            su=0,
                            du=1,
                            tol=0.01,
                            fr=0,
                            dir=2)

        #make live curve on surface down the middle
        #this is used later for noStretch
        curvMaker = cmds.createNode('curveFromSurfaceIso', n=surf + "CurveIso")
        cmds.setAttr(curvMaker + ".isoparmValue", 0.5)
        cmds.setAttr(curvMaker + ".isoparmDirection", 1)
        cmds.connectAttr(surf + ".worldSpace[0]", curvMaker + ".inputSurface")
        offsetCrvShp = cmds.createNode("nurbsCurve",
                                       n=crv + "_driverSurfCrvShape")
        offsetCrv = cmds.listRelatives(p=1)[0]
        offsetCrv = cmds.rename(offsetCrv, crv + "_driverSurfCrv")
        cmds.connectAttr(curvMaker + ".outputCurve", offsetCrvShp + ".create")
        cmds.parent(offsetCrv, self.noXform)

        #Measure curve length and divide by start length
        #to get a normalized value that is useful later to control stretch
        crvInfo = cmds.createNode('curveInfo', n=offsetCrv + "Info")
        cmds.connectAttr(offsetCrv + ".worldSpace[0]", crvInfo + ".ic")
        arcLength = cmds.getAttr(crvInfo + ".al")
        stretchAmountNode = cmds.createNode('multiplyDivide',
                                            n=offsetCrv + "Stretch")
        cmds.setAttr(stretchAmountNode + ".op", 2)  #divide
        cmds.setAttr(stretchAmountNode + ".input1X", arcLength)
        cmds.connectAttr(crvInfo + ".al", stretchAmountNode + ".input2X")

        #Stretch Blender blends start length with current length
        #and pipes it back into stretchAmoundNode's startLength, so user can turn
        #stretch behavior on or off
        stretchBlender = cmds.createNode('blendColors',
                                         n=offsetCrv + "StretchBlender")
        cmds.setAttr(stretchBlender + ".c1r", arcLength)
        cmds.connectAttr(crvInfo + ".al", stretchBlender + ".c2r")
        cmds.connectAttr(stretchBlender + ".opr",
                         stretchAmountNode + ".input1X")
        cmds.connectAttr(self.limbNode + ".noStretch",
                         stretchBlender + ".blender")

        #attach joints to surface
        closestPoint = cmds.createNode('closestPointOnSurface', n='tempClose')
        cmds.connectAttr(surf + ".worldSpace[0]",
                         closestPoint + ".inputSurface")
        for idx, jnt in enumerate(jointList):
            self.name.desc = 'jnt%02dOffset' % idx
            locator = cmds.spaceLocator(n=self.name.get())[0]
            cmds.setAttr(locator + '.localScale', self.stripWidth,
                         self.stripWidth, self.stripWidth)
            cmds.parent(locator, self.noXform)
            #Use closest point to to find jnt's percent along the curve
            cmds.setAttr(closestPoint + '.ip',
                         *cmds.xform(jnt, q=True, t=True, ws=True))
            percentage = cmds.getAttr(closestPoint + '.r.v')
            #attach to surface
            posNode, aimCnss, moPath, slider = self.attachObjToSurf(
                locator, surf, offsetCrv, stretchAmountNode, percentage)

            cmds.connectAttr(self.limbNode + ".slideAlong", slider + ".i2")
            cmds.parentConstraint(locator, jnt, mo=True)
        cmds.delete(closestPoint)

        #add controls.These drive new joints which skinCluster the NURBS strips
        stripJoints = []
        stripJointParent = cmds.createNode('transform',
                                           n=crv + "_stripJoints",
                                           p=self.noXform)
        ctrlParent = cmds.createNode('transform',
                                     n=crv + "_Ctrls",
                                     p=self.pinParent)
        cmds.xform(ctrlParent,
                   ws=True,
                   m=[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])

        prevCtrl = None
        for i in range(self.numCtrls):
            ctrlXform = mpMath.Transform(jointList[0])
            zero, ctrl = self.addCtrl('Ctrl%02d' % i,
                                      type='FK',
                                      shape='box',
                                      parent=ctrlParent,
                                      xform=ctrlXform)
            ctrlXform.scale(0.8, 0.8, 0.8)
            tZero, tCtrl = self.addCtrl('TweakCtrl%02d' % i,
                                        type='FK',
                                        shape='cross',
                                        parent=ctrl,
                                        xform=ctrlXform)

            #Make the new joint for the control to drive
            cmds.select(clear=True)
            self.name.desc = 'StripJnt%02d' % i
            jnt = cmds.joint(p=(0, 0, 0), n=self.name.get())
            cmds.parentConstraint(tCtrl, jnt, mo=False)

            #briefly attach ctrls to strip to align them
            percentage = float(i) / (self.numCtrls - 1.0)
            if i > 0 and i < self.numCtrls - 1:
                percentage = self.uMin + (percentage * (self.uMax - self.uMin))
            cmds.delete(
                self.attachObjToSurf(zero, surf, offsetCrv, stretchAmountNode,
                                     percentage))
            cmds.parent(jnt, stripJointParent)
            stripJoints.append(jnt)

            if prevCtrl:
                cmds.parent(zero, prevCtrl)
                mpRig.addPickParent(ctrl, prevCtrl)
            prevCtrl = ctrl

        #skin strip to controls
        #Can get some different behavior by chaning the strip's weights
        #or perhaps using dual quat. mode on the skinCluster
        skinObjs = stripJoints + [surf]
        cmds.skinCluster(
            skinObjs,
            bindMethod=0,  #closest Point
            sm=0,  #standard bind method
            ih=True,  #ignore hierarchy
        )
예제 #12
0
def create_basic(length=10.0,width=0.5,mainCtrls=4,subCtrls=10,surface=True,curve=False,prefix=''):
	'''
	Create a basic ribbon rig with a single base control
	@param length: Ribbon length 
	@type length: float
	@param width: Ribbon width 
	@type width: float
	@param mainCtrls: Number of main ribbon controls
	@type mainCtrls: int
	@param subCtrls: Number of ribbon sub controls
	@type subCtrls: int
	@param surface: Output ribbon surface
	@type surface: bool
	@param curve: Output ribbon curve
	@type curve: bool
	@param prefix: Name prefix for created nodes
	@type prefix: str
	'''
	# Check prefix
	if not prefix: prefix = 'ribbon'
	
	# -----------------
	# - Create Groups -
	# -----------------
	
	ctrl_grp = mc.group(em=True,n=prefix+'_ctrl_grp')
	hist_grp = mc.group(em=True,n=prefix+'_hist_grp')
	out_grp = mc.group(em=True,n=prefix+'_out_grp')
	rig_grp = mc.group([ctrl_grp,hist_grp,out_grp],n=prefix+'_grp')
	
	mc.setAttr(hist_grp+'.v',0)
	
	# ----------------------
	# - Create Base Ribbon -
	# ----------------------
	
	base_pts = []
	base_inc = length / (mainCtrls-1)
	for i in range(mainCtrls): base_pts.append([width*.5,base_inc*i,0.0])
	
	# Curve 0
	base_crv_0 = mc.curve(d=1,p=base_pts,k=range(len(base_pts)),n=prefix+'_base0_crv')
	mc.rebuildCurve(base_crv_0,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
	base_crv_0_locs = glTools.utils.curve.locatorCurve(base_crv_0,prefix=prefix+'_base0')
	glTools.utils.shape.createIntermediate(base_crv_0)
	mc.rebuildCurve(base_crv_0,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(mainCtrls-1),d=3,tol=0)
	
	# Flip CV array
	base_pts = [(-i[0],i[1],i[2]) for i in base_pts]
	
	# Curve 1
	base_crv_1 = mc.curve(d=1,p=base_pts,k=range(len(base_pts)),n=prefix+'_base1_crv')
	mc.rebuildCurve(base_crv_1,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
	base_crv_1_locs = glTools.utils.curve.locatorCurve(base_crv_1,prefix=prefix+'_base1')
	glTools.utils.shape.createIntermediate(base_crv_1)
	mc.rebuildCurve(base_crv_1,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(mainCtrls-1),d=3,tol=0)
	
	# Loft
	base_loft = mc.loft([base_crv_0,base_crv_1],d=1,n=prefix+'_base_surface')
	base_surface = base_loft[0]
	base_loft = mc.rename(base_loft[1],prefix+'_base_loft')
	
	# Rebuild
	base_rebuild = mc.rebuildSurface(base_surface,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=1,kc=1,su=0,du=0,sv=0,dv=0,tol=0,fr=0,dir=2,n=prefix+'_base_rebuildSurface')
	
	mc.parent([base_crv_0,base_crv_1,base_surface],hist_grp)
	
	# -----------------------
	# - Create Base Control -
	# -----------------------
	
	ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()
	
	mc.select(cl=True)
	base_jnt = mc.joint(n=prefix+'_base_jnt',radius=0.0)
	base_grp = mc.group(base_jnt,n=prefix+'_base_grp')
	mc.parent(base_grp,ctrl_grp)
	
	ctrlBuilder.controlShape(base_jnt,'circle',rotate=(90,0,0),scale=0.2*length)
	
	# ------------------------
	# - Create Main Controls -
	# ------------------------
	
	main_ctrl_list = []
	main_grp_list = []
	main_ctrl_grp = mc.group(em=True,n=prefix+'_mainCtrl_grp')
	for i in range(mainCtrls):
		
		# Clear selection
		mc.select(cl=True)
		
		# Create main control joint
		index = glTools.utils.stringUtils.alphaIndex(int(math.floor(i)),True)
		jnt = mc.joint(n=prefix+'_main'+index+'_jnt',radius=0.0)
		grp = mc.group(jnt,n=prefix+'_main'+index+'_grp')
		
		ctrlBuilder.controlShape(jnt,'square',rotate=(90,0,0),scale=0.125*length)
		
		# Position main control joint
		locs = [base_crv_0_locs[i],base_crv_1_locs[i]]
		mc.delete( mc.pointConstraint(locs,grp) )
		mc.parent(locs,jnt)
		mc.makeIdentity(locs,apply=True,t=1,r=1,s=1,n=0)
		for loc in locs: mc.setAttr(loc+'.v',0)
		
		# Append list
		main_ctrl_list.append(jnt)
		main_grp_list.append(grp)
	
	mc.parent(main_grp_list,main_ctrl_grp)
	mc.parent(main_ctrl_grp,base_jnt)
	
	# ----------------------
	# - Build Sub Controls -
	# ----------------------
	
	sub_ctrl_list = []
	sub_grp_list = []
	sub_ctrl_grp = mc.group(em=True,n=prefix+'_subCtrl_grp')
	
	sub_inc = length / (subCtrls - 1)
	
	for i in range(subCtrls):
		
		# Clear selection
		mc.select(cl=True)
		
		# Create sub control joint
		index = glTools.utils.stringUtils.alphaIndex(i,True)
		sub_jnt = mc.joint(n=prefix+'_sub'+index+'_jnt',radius=0.0)
		sub_grp = mc.group(sub_jnt,n=prefix+'_sub'+index+'_grp')
		
		ctrlBuilder.controlShape(sub_jnt,'box',scale=0.025*length)
		
		# Position and attach sub controls
		mc.setAttr(sub_grp+'.t',0.0,(sub_inc*i),0.0)
		glTools.utils.attach.attachToSurface(base_surface,sub_grp,uValue=0.0,vValue=0.0,useClosestPoint=True,orient=True,uAxis='y',vAxis='x',uAttr='uCoord',vAttr='vCoord',alignTo='v',prefix=prefix+'_sub'+index)
		
		# Connect scale
		mc.connectAttr(base_jnt+'.scale',sub_grp+'.scale')
		
		# Append list
		sub_ctrl_list.append(sub_jnt)
		sub_grp_list.append(sub_grp)
	
	mc.parent(sub_grp_list,sub_ctrl_grp)
	mc.parent(sub_ctrl_grp,ctrl_grp)
	
	# ----------------
	# - Build Output -
	# ----------------
	
	# Build point array
	sub_inc = length / (subCtrls - 1)
	pts = [[0,(sub_inc*i),0] for i in range(subCtrls)]
		
	# -----
	# Curve
	
	if curve:
	
		# Build curve
		ribbon_crv = mc.curve(d=1,p=pts,n=prefix+'_ribbon_curve')
		mc.rebuildCurve(ribbon_crv,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
		
		# Create curve locators
		crv_locs = glTools.utils.curve.locatorCurve(ribbon_crv,prefix=prefix)
		glTools.utils.shape.createIntermediate(ribbon_crv)
		
		# Rebuild ribbon curve
		mc.rebuildCurve(ribbon_crv,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(subCtrls-1),d=3,tol=0,n=prefix+'_ribbon_rebuildCurve')
		
		# Parent curve locators
		for i in range(len(crv_locs)):
			mc.parent(crv_locs[i],sub_ctrl_list[i])
			mc.setAttr(crv_locs[i]+'.v',0)
			
		mc.parent(ribbon_crv,out_grp)
		
	# -----------
	# - Surface -
	
	if surface:
		
		# Offset CV array
		pts = [(width*.5,i[1],i[2]) for i in pts]
		
		# Sub Curve 0
		sub_crv_0 = mc.curve(d=1,p=pts,k=range(len(pts)),n=prefix+'_sub0_crv')
		mc.rebuildCurve(sub_crv_0,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
		sub_crv_0_locs = glTools.utils.curve.locatorCurve(sub_crv_0,prefix=prefix+'_sub0')
		glTools.utils.shape.createIntermediate(sub_crv_0)
		mc.rebuildCurve(sub_crv_0,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(subCtrls-1),d=3,tol=0,n=prefix+'_sub0_rebuildCurve')
		
		# Flip CV array
		pts = [(-i[0],i[1],i[2]) for i in pts]
		
		# Curve 1
		sub_crv_1 = mc.curve(d=1,p=pts,k=range(len(pts)),n=prefix+'_sub1_crv')
		mc.rebuildCurve(sub_crv_1,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
		sub_crv_1_locs = glTools.utils.curve.locatorCurve(sub_crv_1,prefix=prefix+'_sub1')
		glTools.utils.shape.createIntermediate(sub_crv_1)
		mc.rebuildCurve(sub_crv_1,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(subCtrls-1),d=3,tol=0,n=prefix+'_sub1_rebuildCurve')
		
		# Loft
		ribbon_loft = mc.loft([sub_crv_0,sub_crv_1],d=1,n=prefix+'_ribbon_surface')
		ribbon_surface = ribbon_loft[0]
		ribbon_loft = mc.rename(ribbon_loft[1],prefix+'_ribbon_loft')
			
		# Parent curve locators
		for i in range(len(pts)):
			locs = [sub_crv_0_locs[i],sub_crv_1_locs[i]]
			mc.parent(locs,sub_ctrl_list[i])
			mc.makeIdentity(locs,apply=True,t=1,r=1,s=1,n=0)
			for loc in locs: mc.setAttr(loc+'.v',0)
			
		mc.parent([sub_crv_0,sub_crv_1],hist_grp)
		mc.parent(ribbon_surface,out_grp)
예제 #13
0
def SK_createBlendShapeCon(JNTS=[]):

    for UpJnt in JNTS:
        sign = UpJnt.split('_')[0] + UpJnt.split('_')[1]
        UpGrp = rig.listRelatives(UpJnt, p=True)[0]

        scaleValCon = UpGrp.split('_')[0]
        if ('Arm' in scaleValCon):
            scaleValCon = scaleValCon + '_Wrist_IK'
        else:
            scaleValCon = scaleValCon + '_Leg_IK'
        scaleVal = rig.getAttr(scaleValCon + '.scaleVal')

        UpGrpJnt = rig.listRelatives(UpGrp, p=True)[0]
        dnJnt = sign + '_MidJoint_jnt'
        Loc = sign + '_Curve2_LocShape'

        BSsphere = rig.sphere(n=sign + '_Nurbs_Project',
                              ch=False,
                              o=1,
                              ax=(0, 0, -1),
                              r=0.2,
                              nsp=4,
                              ssw=90,
                              endSweep=270)[0]
        BSsphereShape = rig.listRelatives(BSsphere, s=True)[0]
        rig.setAttr(BSsphere + '.visibility', 0)

        if ('Lf' in sign):
            rig.setAttr(BSsphere + '.ry', 180)
        SK_freezeObj(BSsphere)
        SK_snapToObj(UpGrp, BSsphere)
        rig.parent(BSsphere, UpGrpJnt)
        rig.rebuildSurface(BSsphere,
                           ch=False,
                           rpo=1,
                           rt=0,
                           end=1,
                           kr=0,
                           kc=0,
                           su=6,
                           du=3,
                           sv=6,
                           dv=3,
                           tol=0.01,
                           fr=0,
                           dir=2)

        CPS = rig.createNode('closestPointOnSurface', n=sign + '_CPS', ss=True)
        rig.connectAttr(BSsphereShape + '.worldSpace', CPS + '.inputSurface')
        rig.connectAttr(Loc + '.worldPosition[0]', CPS + '.inPosition')
        rig.addAttr(UpGrp, at='float', ln='Up', min=0, max=1, k=True)
        rig.addAttr(UpGrp, at='float', ln='Dn', min=0, max=1, k=True)
        rig.addAttr(UpGrp, at='float', ln='Fn', min=0, max=1, k=True)
        rig.addAttr(UpGrp, at='float', ln='Bc', min=0, max=1, k=True)

        UpPOF = rig.createNode('pointOnSurfaceInfo', n=sign + '_Up_POF')
        rig.connectAttr(BSsphereShape + '.worldSpace', UpPOF + '.inputSurface')
        rig.setAttr(UpPOF + '.parameterU', 0.5)
        rig.setAttr(UpPOF + '.parameterV', 1)
        DnPOF = rig.createNode('pointOnSurfaceInfo', n=sign + '_Dn_POF')
        rig.connectAttr(BSsphereShape + '.worldSpace', DnPOF + '.inputSurface')
        rig.setAttr(DnPOF + '.parameterU', 0.5)
        rig.setAttr(DnPOF + '.parameterV', 0)
        FnPOF = rig.createNode('pointOnSurfaceInfo', n=sign + '_Fn_POF')
        rig.connectAttr(BSsphereShape + '.worldSpace', FnPOF + '.inputSurface')
        rig.setAttr(FnPOF + '.parameterU', 1)
        rig.setAttr(FnPOF + '.parameterV', 1)
        BcPOF = rig.createNode('pointOnSurfaceInfo', n=sign + '_Bc_POF')
        rig.connectAttr(BSsphereShape + '.worldSpace', BcPOF + '.inputSurface')
        rig.setAttr(BcPOF + '.parameterU', 0)
        rig.setAttr(BcPOF + '.parameterV', 0)

        UpDSB = rig.createNode('distanceBetween', n=sign + '_Up_DSB', ss=True)
        DnDSB = rig.createNode('distanceBetween', n=sign + '_Dn_DSB', ss=True)
        FnDSB = rig.createNode('distanceBetween', n=sign + '_Fn_DSB', ss=True)
        BcDSB = rig.createNode('distanceBetween', n=sign + '_Bc_DSB', ss=True)

        if ('Lf' in sign):
            rig.setAttr(BSsphere + '.sy', -1)
        rig.xform(BSsphere, s=(scaleVal, scaleVal, scaleVal), wd=True, r=True)

        rig.connectAttr(UpPOF + '.result.position', UpDSB + '.point1')
        rig.connectAttr(CPS + '.position', UpDSB + '.point2')
        disLength = rig.getAttr(UpDSB + '.distance')
        LengthMD = rig.createNode('multiplyDivide', n=sign + '_MD')
        rig.connectAttr('ScaleConstraints_GRP.scaleX', LengthMD + '.input1X')
        rig.setAttr(LengthMD + '.input2X', disLength)
        UpRV = rig.createNode('remapValue', n=sign + '_Up_RV', ss=True)
        rig.setAttr(UpRV + '.inputMin', 0)
        rig.connectAttr(LengthMD + '.outputX', UpRV + '.inputMax')
        rig.setAttr(UpRV + '.outputMin', 0)
        rig.setAttr(UpRV + '.outputMax', 1)
        rig.setAttr(UpRV + '.value[0].value_Position', 0)
        rig.setAttr(UpRV + '.value[0].value_FloatValue', 1)
        rig.setAttr(UpRV + '.value[1].value_Position', 1)
        rig.setAttr(UpRV + '.value[1].value_FloatValue', 0)
        rig.connectAttr(UpRV + '.outValue', UpGrp + '.Up')
        rig.connectAttr(UpDSB + '.distance', UpRV + '.inputValue')

        rig.connectAttr(DnPOF + '.result.position', DnDSB + '.point1')
        rig.connectAttr(CPS + '.position', DnDSB + '.point2')
        DnRV = rig.createNode('remapValue', n=sign + '_Dn_RV', ss=True)
        rig.setAttr(DnRV + '.inputMin', 0)
        rig.connectAttr(LengthMD + '.outputX', DnRV + '.inputMax')
        rig.setAttr(DnRV + '.outputMin', 0)
        rig.setAttr(DnRV + '.outputMax', 1)
        rig.setAttr(DnRV + '.value[0].value_Position', 0)
        rig.setAttr(DnRV + '.value[0].value_FloatValue', 1)
        rig.setAttr(DnRV + '.value[1].value_Position', 1)
        rig.setAttr(DnRV + '.value[1].value_FloatValue', 0)
        rig.connectAttr(DnRV + '.outValue', UpGrp + '.Dn')
        rig.connectAttr(DnDSB + '.distance', DnRV + '.inputValue')

        rig.connectAttr(FnPOF + '.result.position', FnDSB + '.point1')
        rig.connectAttr(CPS + '.position', FnDSB + '.point2')
        FnRV = rig.createNode('remapValue', n=sign + '_Fn_RV', ss=True)
        rig.setAttr(FnRV + '.inputMin', 0)
        rig.connectAttr(LengthMD + '.outputX', FnRV + '.inputMax')
        rig.setAttr(FnRV + '.outputMin', 0)
        rig.setAttr(FnRV + '.outputMax', 1)
        rig.setAttr(FnRV + '.value[0].value_Position', 0)
        rig.setAttr(FnRV + '.value[0].value_FloatValue', 1)
        rig.setAttr(FnRV + '.value[1].value_Position', 1)
        rig.setAttr(FnRV + '.value[1].value_FloatValue', 0)
        rig.connectAttr(FnRV + '.outValue', UpGrp + '.Fn')
        rig.connectAttr(FnDSB + '.distance', FnRV + '.inputValue')

        rig.connectAttr(BcPOF + '.result.position', BcDSB + '.point1')
        rig.connectAttr(CPS + '.position', BcDSB + '.point2')
        BcRV = rig.createNode('remapValue', n=sign + '_Bc_RV', ss=True)
        rig.setAttr(BcRV + '.inputMin', 0)
        rig.connectAttr(LengthMD + '.outputX', BcRV + '.inputMax')
        rig.setAttr(BcRV + '.outputMin', 0)
        rig.setAttr(BcRV + '.outputMax', 1)
        rig.setAttr(BcRV + '.value[0].value_Position', 0)
        rig.setAttr(BcRV + '.value[0].value_FloatValue', 1)
        rig.setAttr(BcRV + '.value[1].value_Position', 1)
        rig.setAttr(BcRV + '.value[1].value_FloatValue', 0)
        rig.connectAttr(BcRV + '.outValue', UpGrp + '.Bc')
        rig.connectAttr(BcDSB + '.distance', BcRV + '.inputValue')
예제 #14
0
def rebuildSurface(*args, **kwargs):
    res = cmds.rebuildSurface(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    return res
예제 #15
0
def rebuild(surface,spansU=0,spansV=0,fullRebuildU=False,fullRebuildV=False,rebuildUfirst=True,replaceOrig=False):
	'''
	Do brute force surface rebuild for even parameterization
	@param surface: Nurbs surface to rebuild
	@type surface: str
	@param spansU: Number of spans along U. If 0, keep original value.
	@type spansU: int
	@param spansV: Number of spans along V. If 0, keep original value.
	@type spansV: int
	@param replaceOrig: Replace original surface, or create new rebuilt surface.
	@type replaceOrig: bool
	'''
	# Check surface
	if not isSurface(surface):
		raise Exception('Object "'+surface+'" is not a valid surface!')
	
	# Check spans
	if not spansU: spansU = mc.getAttr(surface+'.spansU')
	if not spansV: spansV = mc.getAttr(surface+'.spansV')
	
	# -------------
	# - Rebuild U -
	
	# Get V range
	if rebuildUfirst:
		dir = 'u'
		opp = 'v'
		spans = spansU
		min = mc.getAttr(surface+'.minValueV')
		max = mc.getAttr(surface+'.maxValueV')
	else:
		dir = 'v'
		opp = 'u'
		spans = spansV
		min = mc.getAttr(surface+'.minValueU')
		max = mc.getAttr(surface+'.maxValueU')
	val = min + (max - min) * 0.5
	
	# Caluculate surface length
	iso_crv = mc.duplicateCurve(surface+'.'+opp+'['+str(val)+']',ch=0,rn=0,local=0)[0]
	iso_len = mc.arclen(iso_crv)
	iso_inc = iso_len / spans
	
	# Get spaced isoparm list
	curveFn = glTools.utils.curve.getCurveFn(iso_crv)
	iso_list = [surface+'.'+dir+'['+str(curveFn.findParamFromLength(iso_inc*i))+']' for i in range(spans+1)]
	mc.delete(iso_crv)
	
	# Check full rebuild
	if fullRebuildV:
		# Extract isoparm curves
		iso_crv_list = [mc.duplicateCurve(iso,ch=False,rn=False,local=False)[0] for iso in iso_list]
		# Rebuild isoparm curves
		for iso_crv in iso_crv_list:
			mc.rebuildCurve(iso_crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=0,d=3,tol=0)
		# Loft final surface
		int_surface = mc.loft(iso_crv_list,ch=0,u=1,c=0,ar=1,d=3,ss=1,rn=0,po=0,rsn=True)[0]
		# Delete intermediate curves
		mc.delete(iso_crv_list)
	else:
		# Loft intermediate surface
		int_surface = mc.loft(iso_list,ch=0,u=1,c=0,ar=1,d=3,ss=1,rn=0,po=0,rsn=True)[0]
	
	# -------------
	# - Rebuild V -
	
	# Get V range (intermediate surface)
	if rebuildUfirst:
		dir = 'u'
		opp = 'v'
		spans = spansV
		min = mc.getAttr(int_surface+'.minValueU')
		max = mc.getAttr(int_surface+'.maxValueU')
	else:
		dir = 'v'
		opp = 'u'
		spans = spansU
		min = mc.getAttr(int_surface+'.minValueV')
		max = mc.getAttr(int_surface+'.maxValueV')
	val = min + (max - min) * 0.5
	
	# Caluculate surface length (intermediate surface)
	iso_crv = mc.duplicateCurve(int_surface+'.'+opp+'['+str(val)+']',ch=0,rn=0,local=0)[0]
	iso_len = mc.arclen(iso_crv)
	iso_inc = iso_len / spans
	
	# Get spaced isoparm list
	curveFn = glTools.utils.curve.getCurveFn(iso_crv)
	iso_list = [int_surface+'.'+dir+'['+str(curveFn.findParamFromLength(iso_inc*i))+']' for i in range(spans+1)]
	mc.delete(iso_crv)
	
	# Check full rebuild
	if fullRebuildU:
		# Extract isoparm curves
		iso_crv_list = [mc.duplicateCurve(iso,ch=False,rn=False,local=False)[0] for iso in iso_list]
		# Rebuild isoparm curves
		for iso_crv in iso_crv_list:
			mc.rebuildCurve(iso_crv,ch=False,rpo=True,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=0,d=3,tol=0)
		# Loft final surface
		rebuild_surface = mc.loft(iso_crv_list,ch=0,u=1,c=0,ar=1,d=3,ss=1,rn=0,po=0,rsn=True)[0]
		# Delete intermediate curves
		mc.delete(iso_crv_list)
	else:
		# Loft final surface
		rebuild_surface = mc.loft(iso_list,ch=0,u=1,c=0,ar=1,d=3,ss=1,rn=0,po=0,rsn=True)[0]
	
	# Rename rebuilt surface
	rebuild_surface = mc.rename(rebuild_surface,surface+'_rebuild')
	rebuild_surfaceShape = mc.listRelatives(surface,s=True,ni=True)[0]
	mc.delete(int_surface)
	
	# Re-parameterize 0-1
	mc.rebuildSurface(rebuild_surface,ch=False,rpo=True,dir=2,rt=0,end=1,kr=0,kcp=1,kc=1,tol=0,fr=0)
	
	# Initialize return value
	outputShape = rebuild_surfaceShape
	
	# --------------------
	# - Replace Original -
	
	if replaceOrig:
	
		"""
		# Get original shape
		shapes = glTools.utils.shape.getShapes(surface,nonIntermediates=True,intermediates=False)
		if not shapes:
			# Find Intermediate Shapes
			shapes = glTools.utils.shape.listIntermediates(surface)
		
		# Check shapes
		if not shapes:
			raise Exception('Unable to determine shape for surface "'+surface+'"!')
		# Check connections
		if mc.listConnections(shapes[0]+'.create',s=True,d=False):
			# Find Intermediate Shapes
			shapes = glTools.utils.shape.findInputShape(shapes[0])
		"""
	
		# Check history
		shapes = mc.listRelatives(surface,s=True,ni=True)
		if not shapes: raise Exception('Unable to determine shape for surface "'+surface+'"!')
		shape = shapes[0]
		shapeHist = mc.listHistory(shape)
		if shapeHist.count(shape): shapeHist.remove(shape)
		if shapeHist: print('Surface "" contains construction history, creating new shape!')
		
		# Override shape info and delete intermediate
		mc.connectAttr(rebuild_surfaceShape+'.local',shape+'.create',f=True)
		outputShape = shape
	
	# Return result
	return outputShape
예제 #16
0
def createNrb():
    #Get all name from UI#
    nameObj = mc.textField( Name , q = True , tx = True )
    sideObj = mc.textField( Side , q = True , tx = True )
    ParentObj1 = mc.textField( Parent1 , q = True, tx = True )
    ParentObj2 = mc.textField( Parent2 , q = True, tx = True ) 
    
    # Create Locator #
    baseLoc = mc.spaceLocator(p=(0, 0, 0), n = ( nameObj + 'Base'+ sideObj +'_loc' ))[0]
    tipLoc = mc.spaceLocator(p=(0, 0, 0), n = ( nameObj + 'Tip'+ sideObj +'_loc' ))[0]
    midLoc = mc.spaceLocator(p=(0, 0, 0), n = ( nameObj + 'Mid'+ sideObj +'_loc' ))[0]
    mc.setAttr((tipLoc + '.ty') , 5)
    mc.setAttr((midLoc + '.ty') , 2.5)
    
    # Get Position Attr #
    posBaseLoc = mc.xform(baseLoc,q=True,ws=True,rp=True)
    posTipLoc = mc.xform(tipLoc,q=True,ws=True,rp=True)
    
    # get position for arcLen #    
    if len(ParentObj1) > 0 :
        arcLenCurve1 = mc.xform(ParentObj1,q=True,ws=True,rp=True)
        arcLenCurve2 = mc.xform(ParentObj2,q=True,ws=True,rp=True)
    elif len(ParentObj1) == 0 :
        arcLenCurve1 = posBaseLoc
        arcLenCurve2 = posTipLoc
    # Create Nurb #
    crv1 = mc.curve(d=1,p=(posTipLoc,posBaseLoc),n="rbn1_crv")
    mc.rename('curveShape1',crv1+'Shape')
    crv2 = mc.curve(d=1,p=(posTipLoc,posBaseLoc),n="rbn2_crv")
    mc.rename('curveShape1',crv2+'Shape')
    crvGlobal = mc.curve(d=1,p=(arcLenCurve1,arcLenCurve2),n= nameObj + 'rbnGlobal'+ sideObj +'_crv')
    mc.rename('curveShape1',crvGlobal+'Shape')
    crvMaster = mc.curve(d=1,p=(arcLenCurve1,arcLenCurve1),n=nameObj + 'rbn'+ sideObj +'_crv')
    mc.rename('curveShape1',crvMaster+'Shape')
    mc.setAttr(crvGlobal+'.v',0)
    mc.setAttr(crvMaster+'.v',0)
    mc.setAttr(crv1 + ".tx" , 1)
    mc.setAttr(crv2 + ".tx" , -1)
    RibbonNrb = mc.loft(crv2,crv1,u=True,ch=False,ss=1,rn=False,po=0,rsn=True,n = (nameObj + 'Ribbon'+ sideObj +'_nrb'))[0]
    mc.rebuildSurface(RibbonNrb,su=5,sv=0)
    mc.setAttr(RibbonNrb+'.visibility',0)
    mc.delete(crv1,crv2)
    paraU = 0.1
    allposi = []
    allDetailjnt = []  
    allDetailGrp = []
    
    for i in range(1,6) :
        # Create pointOnSurfaceInfo & Group #
        Posi = mc.createNode('pointOnSurfaceInfo' , n = (nameObj + str(i) +'Rbn' + sideObj + '_posi')) 
        RbnPos = mc.createNode('transform', n = (nameObj + str(i) +'RbnPos' + sideObj + '_grp' ))
        mc.connectAttr( RibbonNrb + 'Shape.worldSpace' , Posi + '.inputSurface' )
        mc.setAttr(Posi + '.parameterU' , paraU )
        mc.setAttr(Posi + '.parameterV' , 0.5 )
        mc.select(cl=True)
        paraU += 0.2
        # Connect pointOnSurfaceInfo to Group #
        mc.connectAttr(Posi + '.position' , RbnPos + '.translate')
        AimRbnPos = mc.createNode('aimConstraint' , n = (nameObj + str(i) +'RbnPosGrp' + sideObj + '_aimCons'))
        mc.parent(AimRbnPos , RbnPos)
        mc.setAttr(AimRbnPos + '.t' , 0 , 0 , 0 )
        mc.setAttr(AimRbnPos + '.r' , 0 , 0 , 0 )
        mc.connectAttr(Posi + '.normal' , AimRbnPos + '.worldUpVector')
        mc.connectAttr(Posi + '.tangentU' , AimRbnPos + '.target[0].targetTranslate')
        mc.connectAttr(AimRbnPos + '.constraintRotate' , RbnPos + '.rotate' )
        mc.setAttr(AimRbnPos + '.upVectorY' , 0)
        mc.setAttr(AimRbnPos + '.upVectorZ' , 1)
        allposi.append(RbnPos)
        mc.select(cl=True)
        
        # create detail joint #
        posiPosition = mc.xform(RbnPos,q=True,ws=True,rp=True)
        detailJnt = mc.joint(p = posiPosition, n = (nameObj + str(i) + 'Detail' + sideObj + '_jnt'))
        #testCube = mc.polyCube(w=.5,h=.5,d=1)
        allDetailjnt.append(detailJnt)
        #mc.parentConstraint(detailJnt,testCube)
        #mc.scaleConstraint(detailJnt,testCube)
        mc.select(cl=True)
        
        # create deetail control #
        detailCtrlPosi = mc.xform(detailJnt,q=True,ws=True,rp=True)
        detailCtrl = mc.curve(d = 1, p =[(-1.25, 0, 0), (-1.004121, 0, 0), (-0.991758, 0, -0.157079), (-0.954976, 0, -0.31029), (-0.894678, 0, -0.455861),(-0.812351, 0, -0.590207), (-0.710021, 0, -0.710021), (-0.590207, 0, -0.812351), (-0.455861, 0, -0.894678), (-0.31029, 0, -0.954976),(-0.157079, 0, -0.991758), (0, 0, -1.004121), (0, 0, -1.25), (0, 0, -1.004121), (0.157079, 0, -0.991758), (0.31029, 0, -0.954976),(0.455861, 0, -0.894678),(0.590207, 0, -0.812351), (0.710021, 0, -0.710021), (0.812351, 0, -0.590207), (0.894678, 0, -0.455861),(0.954976, 0, -0.31029), (0.991758, 0, -0.157079), (1.004121, 0, 0), (1.25, 0, 0), (1.004121, 0, 0), (0.991758, 0, 0.157079), (0.954976, 0, 0.31029), (0.894678, 0, 0.455861), (0.812351, 0, 0.590207), (0.710021, 0, 0.710021), (0.590207, 0, 0.812351), (0.455861, 0, 0.894678), (0.31029, 0, 0.954976),(0.157079, 0, 0.991758),(0, 0, 1.004121), (0, 0, 1.25), (0, 0, 1.004121), (-0.157079, 0, 0.991758), (-0.31029, 0, 0.954976), (-0.455861, 0, 0.894678), (-0.590207, 0, 0.812351), (-0.710021, 0, 0.710021), (-0.812351, 0, 0.590207), (-0.894678, 0, 0.455861), (-0.954976, 0, 0.31029),(-0.991758,0,0.157079),(-1.004121,0,0)], n = (nameObj + str(i) + 'Rbn' + sideObj + '_ctrl'))
        mc.rename('curveShape1' , (nameObj + str(i) + 'Rbn' + sideObj + '_ctrlShape'))
        mc.addAttr(detailCtrl,ln='squash',at='float',dv=0,k=True)
        mc.setAttr(detailCtrl+'.sx', l = True , keyable = False )
        mc.setAttr(detailCtrl+'.sy', l = True , keyable = False )
        mc.setAttr(detailCtrl+'.sz', l = True , keyable = False )
        mc.setAttr(detailCtrl+'.v', l = True , k = False )
        mc.setAttr(detailCtrl + 'Shape.overrideEnabled' , 1)
        mc.setAttr(detailCtrl + 'Shape.overrideColor' , 18)
        detailRotGrp = mc.group(detailCtrl, n = (nameObj + str(i) +'DetailRot' + sideObj + '_grp' ))
        detailGrp = mc.group(detailRotGrp, n = (nameObj + str(i) +'DetailCtrlZro' + sideObj + '_grp' ))
        mc.parentConstraint(detailJnt,detailGrp)
        mc.delete( (nameObj + str(i) + 'DetailCtrlZro' + sideObj + '_grp_parentConstraint1'))
        allDetailGrp.append(detailGrp)
        mc.select(cl=True)
        mc.parentConstraint(RbnPos,detailGrp,mo = True)
        mc.parentConstraint(detailCtrl,detailJnt,mo = True)
    
    
    
    
    # Base Control #
    baseJnt = mc.joint(n = (nameObj + 'Base' + sideObj + '_jnt'))
    baseJntAimGrp = mc.group(n = (nameObj + 'RbnBaseAim' + sideObj + '_grp'))
    baseCtrl = mc.curve( d = 1 , p = [(1,0,0),(-1,0,0),(0,0,0),(0,0,-1),(0,0,1),(0,0,0),(0,1,0),(0,-1,0),(0,0,0)] , n = (nameObj + 'Base' + sideObj + '_ctrl'))
    mc.rename('curveShape1' , (nameObj + 'Base' + sideObj + '_ctrlShape'))
    mc.setAttr(baseCtrl+'.rx', l = True , keyable = False )
    mc.setAttr(baseCtrl+'.ry', l = True , keyable = False )
    mc.setAttr(baseCtrl+'.rz', l = True , keyable = False )
    mc.setAttr(baseCtrl+'.sx', l = True , keyable = False )
    mc.setAttr(baseCtrl+'.sy', l = True , keyable = False )
    mc.setAttr(baseCtrl+'.sz', l = True , keyable = False )
    mc.setAttr(baseCtrl+'.v',0, l = True , k = False )
    mc.setAttr(baseCtrl + 'Shape.overrideEnabled' , 1)
    mc.setAttr(baseCtrl + 'Shape.overrideColor' , 17)
    baseJntZroGrp = mc.group(n = (nameObj + 'RbnBaseZro' + sideObj + '_grp'))
    mc.parent(baseJntAimGrp,baseCtrl)
    parCon = mc.parentConstraint(baseLoc,baseJntZroGrp)
    mc.delete(parCon)
    mc.select(cl=True)
    
    # Middle Control #
    midJnt = mc.joint(n = (nameObj + 'RbnMid' + sideObj + '_jnt'))
    midCtrl = mc.curve( d = 1 , p = [(-1, 0, -1),(-1, 0, 0),(-1.25, 0, 0),(-1, 0, 0),(-1, 0, 1),(0, 0, 1),(0, 0, 1.25),(0, 0, 1),(1, 0, 1),(1, 0, 0),(1.25, 0, 0),(1, 0, 0),(1, 0, -1),(0, 0, -1),(0, 0, -1.25),(0, 0, -1),(-1, 0, -1)] , n = (nameObj + 'RbnMid' + sideObj + '_ctrl'))
    midCtrlList = mc.listRelatives(midCtrl, shapes = True)[0]
    midCtrlShape = mc.rename(midCtrlList , (nameObj + 'RbnMid' + sideObj + '_ctrlShape'))
    mc.setAttr(midCtrl + 'Shape.overrideEnabled' , 1)
    mc.setAttr(midCtrl + 'Shape.overrideColor' , 17)
    mc.addAttr(midCtrl,ln='autoTwist',at='long',min=0,max=1,dv=0,k=True)
    mc.addAttr(midCtrl,ln='rootTwist',at='float',dv=0,k=True)
    mc.addAttr(midCtrl,ln='endTwist',at='float',dv=0,k=True)
    mc.addAttr(midCtrl,ln='autoSquash',at='long',min=0,max=1,dv=0,k=True)
    mc.addAttr(midCtrl,ln='squash',at='float',dv=0,k=True)
    mc.addAttr(midCtrlShape,ln='detailControl',at='bool',dv=0,k=True)
    mc.addAttr(midCtrlShape,ln='rootTwist',at='float',dv=0,k=True)
    mc.addAttr(midCtrlShape,ln='endTwist',at='float',dv=0,k=True)
    mc.setAttr(midCtrl+'.sx', l = True , keyable = False )
    mc.setAttr(midCtrl+'.sy', l = True , keyable = False )
    mc.setAttr(midCtrl+'.sz', l = True , keyable = False )
    mc.setAttr(midCtrl+'.v',1, l = True , k = False )
    midJntAimGrp = mc.group(n = (nameObj + 'RbnMidAim' + sideObj + '_grp'))
    midJntZroGrp = mc.group(n = (nameObj + 'RbnMidZro' + sideObj + '_grp'))
    mc.parent(midJnt,midCtrl)
    parCon = mc.parentConstraint(midLoc,midJntZroGrp)
    mc.delete(parCon)
    mc.select(cl=True)
    
    # Tip Control #
    tipCtrl = mc.curve( d = 1 , p = [(1,0,0),(-1,0,0),(0,0,0),(0,0,-1),(0,0,1),(0,0,0),(0,1,0),(0,-1,0),(0,0,0)] , n = (nameObj + 'Tip' + sideObj + '_ctrl'))
    mc.rename('curveShape1' , (nameObj + 'Tip' + sideObj + '_ctrlShape'))
    mc.setAttr(tipCtrl+'.rx', l = True , keyable = False )
    mc.setAttr(tipCtrl+'.ry', l = True , keyable = False )
    mc.setAttr(tipCtrl+'.rz', l = True , keyable = False )
    mc.setAttr(tipCtrl+'.sx', l = True , keyable = False )
    mc.setAttr(tipCtrl+'.sy', l = True , keyable = False )
    mc.setAttr(tipCtrl+'.sz', l = True , keyable = False )
    mc.setAttr(tipCtrl+'.v',0, l = True , k = False )
    mc.setAttr(tipCtrl + 'Shape.overrideEnabled' , 1)
    mc.setAttr(tipCtrl + 'Shape.overrideColor' , 17)
    tipJntZroGrp = mc.group(n = (nameObj + 'RbnTipZro' + sideObj + '_grp'))
    tipJnt = mc.joint(n = (nameObj + 'Tip' + sideObj + '_jnt') , p = (0,0,0))
    tipJntAimGrp = mc.group(n = (nameObj + 'RbnTipAim' + sideObj + '_grp'))
    mc.parent(tipJntAimGrp,tipCtrl)
    parCon = mc.parentConstraint(tipLoc,tipJntZroGrp)
    mc.delete(parCon)
    mc.delete(baseLoc,midLoc,tipLoc)
    mc.select(cl=True)
    
    # Create Twist #
    
    rbnTwistMdv = mc.createNode('multiplyDivide', n = (nameObj + 'RbnTwist' + sideObj + '_mdv'))
    rbnAutoTwistMdv = mc.createNode('multiplyDivide', n = (nameObj + 'RbnAutoTwist' + sideObj + '_mdv'))
    rbnAutoTwistPma = mc.createNode('plusMinusAverage', n = (nameObj + 'RbnAutoTwist' + sideObj + '_pma'))
    mc.setAttr(rbnAutoTwistMdv+'.input2X',-1)
    mc.connectAttr(midCtrl+'.autoTwist',rbnTwistMdv+'.input2Y')
    mc.connectAttr(midCtrl+'.autoTwist',rbnTwistMdv+'.input2X')
    mc.connectAttr(midCtrl+'Shape.rootTwist',rbnAutoTwistMdv+'.input1X')
    mc.connectAttr(midCtrl+'Shape.endTwist',rbnAutoTwistMdv+'.input1Y')
    mc.connectAttr(midCtrl+'.rootTwist',rbnAutoTwistPma+'.input3D[0].input3Dx')
    mc.connectAttr(midCtrl+'.endTwist',rbnAutoTwistPma+'.input3D[0].input3Dy')
    mc.connectAttr(rbnTwistMdv+'.output',rbnAutoTwistPma+'.input3D[1]')
    mc.connectAttr(rbnAutoTwistMdv+'.output',rbnTwistMdv+'.input1')
    
    for i in range(1,6) :
        detailRotGrp = (nameObj + str(i) +'DetailRot' + sideObj + '_grp' )
        rbnTwistMdv = mc.createNode('multiplyDivide', n = (nameObj + str(i) + 'DetailTwist' + sideObj + '_mdv'))
        rbnTwistPma = mc.createNode('plusMinusAverage', n = (nameObj + str(i) + 'DetailTwist' + sideObj + '_pma'))
        mc.setAttr(rbnTwistMdv+'.input2Y',(0.25*(i-1)))
        mc.setAttr(rbnTwistMdv+'.input2X',(1-(0.25*(i-1))))
        mc.connectAttr(rbnAutoTwistPma+'.output3Dx',rbnTwistMdv+'.input1.input1Y')
        mc.connectAttr(rbnAutoTwistPma+'.output3Dy',rbnTwistMdv+'.input1.input1X')
        mc.connectAttr(rbnTwistMdv+'.output.outputX',rbnTwistPma+'.input2D[0].input2Dx')
        mc.connectAttr(rbnTwistMdv+'.output.outputY',rbnTwistPma+'.input2D[1].input2Dx')
        mc.connectAttr(rbnTwistPma+'.output2D.output2Dx',detailRotGrp+'.rotate.rotateY')
        
    if len(ParentObj1) > 0 :
        mc.connectAttr(ParentObj1 +'.rotate.rotateY',midCtrl+'Shape.rootTwist')
        mc.connectAttr(ParentObj2 +'.rotate.rotateY',midCtrl+'Shape.endTwist')
    mc.setAttr(midCtrl+'Shape.rootTwist', l = True )
    mc.setAttr(midCtrl+'Shape.endTwist', l = True )
        
    # Create Squash #
    cfs = mc.createNode('curveFromSurfaceIso',n = (nameObj + 'Rbn' + sideObj + '_cfs'))
    mc.connectAttr(RibbonNrb + 'Shape.worldSpace' ,cfs + '.inputSurface')
    mc.setAttr(cfs+'.isoparmValue',0.5)
    mc.connectAttr(cfs + '.outputCurve' ,crvMaster + 'Shape.create')
    CurveGlobalInfo = mc.arclen(crvGlobal, ch=True )
    rbnCurveGlobalInfo = mc.rename(CurveGlobalInfo,(nameObj + 'RbnGlobal' + sideObj + '_cif'))
    CurveMasterInfo = mc.arclen(crvMaster, ch=True )
    rbnCurveMasterInfo = mc.rename(CurveMasterInfo,(nameObj + 'Rbn' + sideObj + '_cif'))
    
    rbnAutoSquashMdv = mc.createNode('multiplyDivide', n = (nameObj + 'RbnAutoSquash' + sideObj + '_mdv'))
    rbnAutoSquashPma = mc.createNode('plusMinusAverage', n = (nameObj + 'RbnAutoSquash' + sideObj + '_pma'))
    rbnAutoSquashPowMdv = mc.createNode('multiplyDivide', n = (nameObj + 'RbnAutoSquashPow' + sideObj + '_mdv'))
    rbnAutoSquashDivMdv = mc.createNode('multiplyDivide', n = (nameObj + 'RbnAutoSquashDiv' + sideObj + '_mdv'))
    rbnAutoSquashGlobalMdv = mc.createNode('multiplyDivide', n = (nameObj + 'RbnAutoSquashGlobal' + sideObj + '_mdv'))
    mc.setAttr(rbnAutoSquashPma+'.input2D[1].input2Dx',-1)
    mc.setAttr(rbnAutoSquashPma+'.input2D[1].input2Dy',-1)
    mc.setAttr(rbnAutoSquashPowMdv+'.input2X',0.5)
    mc.setAttr(rbnAutoSquashPowMdv+'.operation',3)
    mc.setAttr(rbnAutoSquashDivMdv+'.operation',2)
    mc.setAttr(rbnAutoSquashGlobalMdv+'.operation',2)
    mc.setAttr(rbnAutoSquashDivMdv+'.input1X',1)
    
    mc.connectAttr(rbnCurveMasterInfo + '.arcLength',rbnAutoSquashGlobalMdv + '.input1X')
    mc.connectAttr(rbnCurveGlobalInfo + '.arcLength',rbnAutoSquashGlobalMdv + '.input2X')
    
    mc.connectAttr(rbnAutoSquashGlobalMdv +'.outputX',rbnAutoSquashDivMdv + '.input2X')
    mc.connectAttr(rbnAutoSquashDivMdv +'.outputX',rbnAutoSquashPowMdv + '.input1X')
    mc.connectAttr(midCtrl +'.autoSquash',rbnAutoSquashMdv + '.input2X')
    mc.connectAttr(rbnAutoSquashPma +'.output2Dx',rbnAutoSquashMdv + '.input1X')
    mc.connectAttr(rbnAutoSquashPowMdv +'.outputX',rbnAutoSquashPma + '.input2D[0].input2Dx')
    
    
    amp = 0.3333
    for i in range(1,6) :
        detailCtrl = (nameObj + str(i) + 'Rbn' + sideObj + '_ctrl')
        rbnStSqMdv = mc.createNode('multiplyDivide', n = (nameObj + str(i) + 'RbnCtrlStSq' + sideObj + '_mdv'))
        rbnStSqPma = mc.createNode('plusMinusAverage', n = (nameObj + str(i) + 'RbnCtrlStSq' + sideObj + '_pma'))
        mc.setAttr(rbnStSqPma+'.input2D[0].input2Dy',1)
        mc.connectAttr(detailCtrl +'.squash',rbnStSqMdv + '.input1Y')
        mc.connectAttr(rbnStSqMdv +'.outputX',rbnStSqPma + '.input2D[1].input2Dy')
        mc.connectAttr(rbnStSqMdv +'.outputY',rbnStSqPma + '.input2D[2].input2Dy')
        mc.connectAttr(rbnStSqMdv +'.outputZ',rbnStSqPma + '.input2D[3].input2Dy')
        mc.connectAttr(rbnAutoSquashMdv+'.outputX' ,rbnStSqMdv +'.input1X' )
        mc.connectAttr(midCtrl+'.squash' ,rbnStSqMdv +'.input1Z' )
        detailJnt = (nameObj + str(i) + 'Detail' + sideObj + '_jnt')
        mc.connectAttr(rbnStSqPma+'.output2Dy',detailJnt+'.scaleX')
        mc.connectAttr(rbnStSqPma+'.output2Dy',detailJnt+'.scaleZ')
        
        
        if i < 3 :
            mc.setAttr(rbnStSqMdv+'.input2X' , amp)
            mc.setAttr(rbnStSqMdv+'.input2Z' , amp)
            amp += 0.3333
            
        if i > 3 :
            amp -= 0.3333
            mc.setAttr(rbnStSqMdv+'.input2X' , amp)
            mc.setAttr(rbnStSqMdv+'.input2Z' , amp)
            
        
        
    mc.aimConstraint(baseJntAimGrp,tipJntAimGrp, wuo = tipJntZroGrp ,aim = [0,-1,0] , u = [0,1,0] , wut = 'objectrotation' , wu = [0,1,0])
    mc.aimConstraint(tipJntAimGrp,baseJntAimGrp, wuo = baseJntZroGrp ,aim = [0,1,0] , u = [0,1,0] , wut = 'objectrotation' , wu = [0,1,0])
    mc.aimConstraint(tipJntAimGrp,midJntAimGrp, wuo = midJntZroGrp ,aim = [0,1,0] , u = [0,1,0] , wut = 'objectrotation' , wu = [0,1,0])
    mc.pointConstraint( baseJnt, tipJnt, midJntZroGrp )
    
    
    
    #skin nurb#
    NurbsSkin = mc.skinCluster( baseJnt, midJnt, tipJnt , RibbonNrb , dr=16, nw=2 , n = (nameObj + 'RbnNrb' + sideObj + '_skc') , tsb = True) 
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[0][0:3]'), tv = (tipJnt, 1))
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[1][0:3]'), tv = (midJnt, .13))
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[2][0:3]'), tv = (midJnt, .4))
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[3][0:3]'), tv = (midJnt, .8))
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[4][0:3]'), tv = (midJnt, .8))
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[5][0:3]'), tv = (midJnt, .4))
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[6][0:3]'), tv = (midJnt, .13))
    mc.skinPercent (NurbsSkin[0], (RibbonNrb + '.cv[7][0:3]'), tv = (baseJnt, 1))
    
    
    detailZroGrp = mc.group(allDetailGrp , n = (nameObj + 'RbnDetailZro' + sideObj + '_grp'))
    mc.select( clear=True )
    rbnCtrlGrp = mc.group(detailZroGrp,baseJntZroGrp,midJntZroGrp,tipJntZroGrp,crvGlobal, n = (nameObj + 'RbnCtrl' + sideObj + '_grp'))
    mc.select( clear=True )
    rbnStillGrp = mc.group(allposi,RibbonNrb ,crvMaster, n = (nameObj + 'RbnStill' + sideObj + '_grp'))
    mc.select(cl=True)    
    rbnSkinGrp = mc.group(allDetailjnt , n = (nameObj + 'RbnSkin' + sideObj + '_grp'))
    mc.select(cl=True)
    mc.connectAttr(midCtrlShape+'.detailControl',detailZroGrp+'.v')
    
    mc.parentConstraint( rbnCtrlGrp, rbnSkinGrp , mo=0 )
    if len(ParentObj1) > 0 :
        mc.pointConstraint( ParentObj1, baseJntZroGrp , mo=0 )
        mc.pointConstraint( ParentObj2, tipJntZroGrp , mo=0 )
        mc.parentConstraint( ParentObj1, rbnCtrlGrp , mo=0 )
    def createRibbon(self, *args):
        self.name = cmds.textFieldGrp(self.widgets["ribbonNameTFG"], q=True, tx=True)
        self.numDiv = (cmds.intFieldGrp(self.widgets["jointsIFG"], q=True, v=True)[0]) - 1
        # self.fk = cmds.checkBox(self.widgets["fkSetupCB"], q=True, v=True)
        self.height = cmds.floatFieldGrp(self.widgets["heightFFG"], q=True, v1=True)
        self.ratio = cmds.floatFieldGrp(self.widgets["ratioFFG"], q=True, v1=True)
        # self.axis = cmds.radioButtonGrp(self.widgets["axis"] , q=True, sl=True)

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

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

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

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

        # if self.own == 0:
        width = self.height / self.ratio

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

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

        # else:
        # 	self.ribbonName = self.myGeo

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

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

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

            self.follicleList.append(follicle)

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

            # create controls here:
            # create a loop that runs through the cvs in v, 0 to 6
        origClusterList = [
            "top_CLS",
            "topBez_CLS",
            "centerTop_CLS",
            "center_CLS",
            "centerEnd_CLS",
            "endBez_CLS",
            "end_CLS",
        ]
        origControlList = [
            "top_CTRL",
            "topBez_CTRL",
            "centerTop_CTRL",
            "center_CTRL",
            "centerEnd_CTRL",
            "endBez_CTRL",
            "end_CTRL",
        ]

        clusterList = []
        controlList = []
        constrGrpList = []
        attachGrpList = []

        for v in range(0, 7):
            cmds.select(clear=True)
            clusNodeName = self.name + "_" + origClusterList[v] + "Base"
            # select u (0 and 1) for each v and cluster them
            fullCls = cmds.cluster("%s.cv[0:1][%d]" % (self.ribbonName, v), relative=False, n=clusNodeName)[0]
            clusHandle = clusNodeName + "Handle"
            clusName = clusHandle.rstrip("BaseHandle")
            cmds.rename(clusHandle, clusName)
            clusterList.append(clusName)
            # now setup the controls and groups for the clusters
            # goes control,group (const), group(attach)
            control = self.name + "_" + origControlList[v]
            constrGrp = self.name + "_" + origControlList[v] + "_const_GRP"
            attachGrp = self.name + "_" + origControlList[v] + "_attach_GRP"

            rig.createControl(name=control, type="circle", axis="y", color="darkGreen", *args)
            oldGrp = rig.groupOrient(clusName, control)
            cmds.rename(oldGrp, constrGrp)

            # parent clus to control
            cmds.parent(clusName, control)

            # get cluster position
            clusPos = cmds.pointPosition(clusName + ".rotatePivot")
            cmds.xform(constrGrp, ws=True, piv=(clusPos[0], clusPos[1], clusPos[2]))

            cmds.group(constrGrp, n=attachGrp)
            cmds.xform(attachGrp, ws=True, piv=(clusPos[0], clusPos[1], clusPos[2]))

            controlList.append(control)
            constrGrpList.append(constrGrp)
            attachGrpList.append(attachGrp)
예제 #18
0
def create(surface,spansU=0,spansV=0,prefix=None):
	'''
	'''
	# Load Plugins
	loadPlugin()
	
	# ==========
	# - Checks -
	# ==========
	
	# Check Surface
	if not glTools.utils.surface.isSurface(surface):
		raise Exception('Object "'+surface+'" is not a valid nurbs surface!')
	
	# Check Prefix
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(surface)
	
	# Get Surface Details
	if not spansU: spansU = mc.getAttr(surface+'.spansU')
	if not spansV: spansV = mc.getAttr(surface+'.spansV')
	minU = mc.getAttr(surface+'.minValueU')
	maxU = mc.getAttr(surface+'.maxValueU')
	minV = mc.getAttr(surface+'.minValueV')
	maxV = mc.getAttr(surface+'.maxValueV')
	incU = (maxU-minU)/spansU
	incV = (maxV-minV)/spansV
	
	# =============
	# - Rebuild U -
	# =============
	
	crvU = []
	for i in range(spansU+1):
		
		# Duplicate Surface Curve
		dupCurve = mc.duplicateCurve(surface+'.u['+str(incU*i)+']',ch=True,rn=False,local=False)
		dupCurveNode = mc.rename(dupCurve[1],prefix+'_spanU'+str(i)+'_duplicateCurve')
		dupCurve = mc.rename(dupCurve[0],prefix+'_spanU'+str(i)+'_crv')
		crvU.append(dupCurve)
		
		# Set Curve Length
		arcLen = mc.arclen(dupCurve)
		setLen = mc.createNode('setCurveLength',n=prefix+'_spanU'+str(i)+'_setCurveLength')
		crvInfo = mc.createNode('curveInfo',n=prefix+'_spanU'+str(i)+'_curveInfo')
		blendLen = mc.createNode('blendTwoAttr',n=prefix+'_spanU'+str(i)+'length_blendTwoAttr')
		mc.addAttr(dupCurve,ln='targetLength',dv=arcLen,k=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',crvInfo+'.inputCurve',f=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',setLen+'.inputCurve',f=True)
		mc.connectAttr(crvInfo+'.arcLength',blendLen+'.input[0]',f=True)
		mc.connectAttr(dupCurve+'.targetLength',blendLen+'.input[1]',f=True)
		mc.connectAttr(blendLen+'.output',setLen+'.length',f=True)
		mc.connectAttr(setLen+'.outputCurve',dupCurve+'.create',f=True)
		
		# Add Control Attributes
		mc.addAttr(dupCurve,ln='lockLength',min=0,max=1,dv=1,k=True)
		mc.addAttr(dupCurve,ln='lengthBias',min=0,max=1,dv=0,k=True)
		mc.connectAttr(dupCurve+'.lockLength',blendLen+'.attributesBlender',f=True)
		mc.connectAttr(dupCurve+'.lengthBias',setLen+'.bias',f=True)
	
	# Loft New Surface
	srfU = mc.loft(crvU,ch=True,uniform=True,close=False,autoReverse=False,degree=3)
	srfUloft = mc.rename(srfU[1],prefix+'_rebuildU_loft')
	srfU = mc.rename(srfU[0],prefix+'_rebuildU_srf')
	
	# Rebuild 0-1
	rebuildSrf = mc.rebuildSurface(srfU,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=1,su=0,du=3,sv=0,dv=3,tol=0)
	rebuildSrfNode = mc.rename(rebuildSrf[1],prefix+'_rebuildU_rebuildSurface')
	
	# Add Control Attributes
	mc.addAttr(srfU,ln='lockLength',min=0,max=1,dv=1,k=True)
	mc.addAttr(srfU,ln='lengthBias',min=0,max=1,dv=0,k=True)
	for crv in crvU:
		mc.connectAttr(srfU+'.lockLength',crv+'.lockLength',f=True)
		mc.connectAttr(srfU+'.lengthBias',crv+'.lengthBias',f=True)
	
	# =============
	# - Rebuild V -
	# =============
	
	crvV = []
	for i in range(spansV+1):
		
		# Duplicate Surface Curve
		dupCurve = mc.duplicateCurve(srfU+'.v['+str(incV*i)+']',ch=True,rn=False,local=False)
		dupCurveNode = mc.rename(dupCurve[1],prefix+'_spanV'+str(i)+'_duplicateCurve')
		dupCurve = mc.rename(dupCurve[0],prefix+'_spanV'+str(i)+'_crv')
		crvV.append(dupCurve)
		
		# Set Curve Length
		arcLen = mc.arclen(dupCurve)
		setLen = mc.createNode('setCurveLength',n=prefix+'_spanV'+str(i)+'_setCurveLength')
		crvInfo = mc.createNode('curveInfo',n=prefix+'_spanV'+str(i)+'_curveInfo')
		blendLen = mc.createNode('blendTwoAttr',n=prefix+'_spanV'+str(i)+'length_blendTwoAttr')
		mc.addAttr(dupCurve,ln='targetLength',dv=arcLen,k=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',crvInfo+'.inputCurve',f=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',setLen+'.inputCurve',f=True)
		mc.connectAttr(crvInfo+'.arcLength',blendLen+'.input[0]',f=True)
		mc.connectAttr(dupCurve+'.targetLength',blendLen+'.input[1]',f=True)
		mc.connectAttr(blendLen+'.output',setLen+'.length',f=True)
		mc.connectAttr(setLen+'.outputCurve',dupCurve+'.create',f=True)
		
		# Add Control Attribute
		mc.addAttr(dupCurve,ln='lockLength',min=0,max=1,dv=1,k=True)
		mc.addAttr(dupCurve,ln='lengthBias',min=0,max=1,dv=0,k=True)
		mc.connectAttr(dupCurve+'.lockLength',blendLen+'.attributesBlender',f=True)
		mc.connectAttr(dupCurve+'.lengthBias',setLen+'.bias',f=True)
	
	# Loft New Surface
	srfV = mc.loft(crvV,ch=True,uniform=True,close=False,autoReverse=False,degree=3)
	srfVloft = mc.rename(srfV[1],prefix+'_rebuildV_loft')
	srfV = mc.rename(srfV[0],prefix+'_rebuildV_srf')
	
	# Rebuild 0-1
	rebuildSrf = mc.rebuildSurface(srfV,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=1,su=0,du=3,sv=0,dv=3,tol=0)
	rebuildSrfNode = mc.rename(rebuildSrf[1],prefix+'_rebuildV_rebuildSurface')
	
	# Add Control Attribute
	mc.addAttr(srfV,ln='lockLength',min=0,max=1,dv=1,k=True)
	mc.addAttr(srfV,ln='lengthBias',min=0,max=1,dv=0,k=True)
	for crv in crvV:
		mc.connectAttr(srfV+'.lockLength',crv+'.lockLength',f=True)
		mc.connectAttr(srfV+'.lengthBias',crv+'.lengthBias',f=True)
	
	# ===================
	# - Build Hierarchy -
	# ===================
	
	rebuildUGrp = mc.group(em=True,n=prefix+'_rebuildU_grp')
	mc.parent(crvU,rebuildUGrp)
	mc.parent(srfU,rebuildUGrp)
	
	rebuildVGrp = mc.group(em=True,n=prefix+'_rebuildV_grp')
	mc.parent(crvV,rebuildVGrp)
	mc.parent(srfV,rebuildVGrp)
	
	rebuildGrp = mc.group(em=True,n=prefix+'_lockLength_grp')
	mc.parent(rebuildUGrp,rebuildGrp)
	mc.parent(rebuildVGrp,rebuildGrp)
	
	# =================
	# - Return Result -
	# =================
	
	return rebuildGrp
예제 #19
0
                                    lengthRatio=dist,
                                    d=3,
                                    u=1,
                                    v=spans,
                                    ax=normal)[0]
            if self.logger:
                self.logger.info('_createPlane(): Created plane: %s' % plane)
        except Exception, e:
            if self.logger:
                self.logger.error('_createPlane(): Error creating plane: %s' %
                                  e)
            raise Exception(e)

        #--- Rebuild the plane
        try:
            cmds.rebuildSurface(plane, rt=1, du=1, dv=3)
            cmds.rebuildSurface(plane, rt=0, su=1, sv=spans, du=1, dv=3)
            if self.logger:
                self.logger.info('_createPlane(): Rebuilt surface.')
        except Exception, e:
            if self.logger:
                self.logger.error('_createPlane(): Error creating plane: %s' %
                                  e)
            raise Exception(e)

        #--- Delete history
        try:
            cmds.select(plane, r=True)
            mel.eval('DeleteHistory;')
            cmds.select(clear=True)
            if self.logger:
예제 #20
0
파일: surface.py 프로젝트: jonntd/japeto
def createFromPoints(points, degree=3, direction="x", name="newSurface", spansU=0, spansV=0):
    """ 
    Build curve from transforms 
    
    Example: 
    #        >>> createFromTransforms (["transform1", "transform2"], 1, "newSurface")
        
        
    @param transforms: Transform object to place point to draw the curve
    @type transforms: *list*
    
    @param degree: degree of the curve, linear or cubic
    @type degree: *int*
    """

    if not isinstance(points, list):
        raise RuntimeError, "There needs to be more then one transform, transforms argument must be a type *list*"

    # generate the first curve
    curve_one = curve.createFromPoints(points, degree, "tmpCurve1")
    # move curve in the proper direction
    cmds.move(
        transform.AXES[direction][0], transform.AXES[direction][1], transform.AXES[direction][2], curve_one, r=True
    )
    # generate the first curve
    curve_two = curve.createFromPoints(points, degree, "tmpCurve2")
    # move curve in the proper direction
    cmds.move(
        transform.AXES["-%s" % direction][0],
        transform.AXES["-%s" % direction][1],
        transform.AXES["-%s" % direction][2],
        curve_two,
        r=True,
    )

    if degree == 3:
        surface = cmds.loft(curve_one, curve_two, ch=False, ss=0, n=name)[0]
        cmds.rebuildSurface(surface, kr=0, kcp=True)
    elif degree == 1:
        surface = cmds.loft(curve_one, curve_two, ch=False, ss=0, degree=1, rebuild=True, n=name)[0]
        cmds.rebuildSurface(
            surface,
            ch=False,
            rpo=1,
            rt=0,
            end=1,
            kr=0,
            kcp=0,
            kc=0,
            tol=0.01,
            fr=0,
            dir=2,
            du=degree,
            dv=degree,
            su=spansU,
            sv=spansV,
        )

    # delete curves
    cmds.delete((curve_one, curve_two))

    return surface
예제 #21
0
def createNormPlane(prefix,
                    driven,
                    basePlane,
                    numLayers,
                    surfLyr,
                    densityU,
                    densityV,
                    connectionLayerNode,
                    sAttributeName):
    #return list with surf names
    layerSurfaces = []
    #layerNum = 1 #tmp
    #Create conlyr
    conlyr = mc.createNode('transform', n=prefix + 'surfaces_connectionLayer' + driven)
    mc.parent(conlyr, connectionLayerNode)

    #Create sufaces parent
    surfGrp = mc.createNode('transform', n=prefix + 'surfaces_grp' + driven)

    for layerNum in range(1, numLayers + 1):

        lyrTag = surfLyr[layerNum - 1]

        #plane name and
        surface = prefix + 'plane_' + lyrTag + '_surf' + driven
        surface = mc.duplicate(basePlane, n=surface)[0]
        mc.parent(surface, surfGrp)
        layerSurfaces.append(surface)
        #Add message attr
        connectMessageAttr(conlyr, surface, sAttributeName)

        #num of spans
        spansU = densityU[layerNum - 1]
        spansV = densityV[layerNum - 1]

        #misc
        rebuildType = 0
        degreeU = 1
        degreeV = 1

        #Create linear first to get the right spacing
        mc.rebuildSurface(
            surface,
            constructionHistory=0,
            replaceOriginal=1,
            rebuildType=rebuildType,
            endKnots=1,
            keepRange=0,
            keepControlPoints=0,
            keepCorners=0,
            spansU=spansU,
            degreeU=degreeU,
            spansV=spansV,
            degreeV=degreeV,
            tolerance=0,
            fitRebuild=0,
            direction=2
        )
        #Rebuild it to quadratic maintaining cvs pos
        #Check if lyr A is linear
        if spansU != 1:
            degreeU = 2
        if spansV != 1:
            degreeV = 2

        mc.rebuildSurface(
            surface,
            constructionHistory=0,
            replaceOriginal=1,
            rebuildType=rebuildType,
            endKnots=1,
            keepRange=0,
            keepControlPoints=1,
            keepCorners=0,
            spansU=spansU,
            degreeU=degreeU,
            spansV=spansV,
            degreeV=degreeV,
            tolerance=0,
            fitRebuild=0,
            direction=2
        )

    #mc.delete(basePlane)

    return (layerSurfaces, surfGrp)
예제 #22
0
def build(
        pelvis_jnt,
        spine_jnts,
        prefix='spine',
        rig_scale=1.0,
        base_rig=None
        ):
    
    """
    @param spine_jnts: list(str), list of 6 spine jnts
    @param root_jnt: str, root_jnt
    @param prefix: str, prefix to name new object
    @param rig_scale: float, scale factor for size of controls
    @param base_rig: instance of base.module.Base class
    @return: dictionary with rig module objects 
    """
    
    #make rig module
    rig_module = module.Module(prefix=prefix, base_obj=base_rig, create_dnt_grp=True)
    
    
    #make spine controls
    body_ctrl = control.Control(shape='body_ctrl_template', prefix='body',
                                translate_to=pelvis_jnt, scale=rig_scale,
                                parent=rig_module.ctrl_grp, lock_channels=['s', 'v'])
    
    hip_ctrl = control.Control(shape='hip_ctrl_template', prefix='hip',
                                translate_to=pelvis_jnt, scale=rig_scale,
                                parent=body_ctrl.ctrl, lock_channels=['s', 'v'])
    ctrl_shape = cmds.listRelatives(hip_ctrl.ctrl, shapes=True)[0]
    cmds.setAttr(ctrl_shape + '.ove', 1)
    cmds.setAttr(ctrl_shape + '.ovc', 18)
    
    chest_ctrl = control.Control(shape='chest_ctrl_template', prefix='chest',
                                translate_to=spine_jnts[len(spine_jnts)-1], scale=rig_scale,
                                parent=body_ctrl.ctrl, lock_channels=['s', 'v'])
    
    spine_ctrl = control.Control(shape='spine_ctrl_template', prefix=prefix,
                                translate_to=[hip_ctrl.ctrl, chest_ctrl.ctrl], scale=rig_scale,
                                parent=body_ctrl.ctrl, lock_channels=['s', 'r', 'v'])
    ctrl_shape = cmds.listRelatives(spine_ctrl.ctrl, shapes=True)[0]
    cmds.setAttr(ctrl_shape + '.ove', 1)
    cmds.setAttr(ctrl_shape + '.ovc', 18)
    
    
    #SET UP RIBBON
    #create ribbon surface and add follicles
    ribbon.create_cv_curve('temp_spine_ribbon_crv_01', spine_jnts)
    ribbon_sfc = ribbon.loft_using_curve('temp_spine_ribbon_crv_01', 8, 'x', prefix)
    cmds.rebuildSurface(ribbon_sfc, su=0, sv=3, du=1, dv=3, ch=True)
    spine_follicles = ribbon.add_follicles(ribbon_sfc, 4, on_edges=True)
    spine_ik_jnts = joint.duplicate(spine_jnts, prefix='ik')

    spine_follicles_grp = '_'.join([prefix,'follicles','grp'])
    cmds.group(spine_follicles, n=spine_follicles_grp)
    
    for i in range(len(spine_ik_jnts)):
        cmds.parent(spine_ik_jnts[i], spine_follicles[i])
    
    #create ribbon_wire_curve to drive the surface using wire deformer
    ribbon_wire_curve = 'ribbon_wire_crv'
    create_ep_curve(curve=ribbon_wire_curve, 
                          pos_ref_list=[spine_jnts[0], spine_jnts[len(spine_jnts)-1]],
                           degree=2)
    
    #create and add clusters
    ribbon_clstr_list = []
    for i in range(ribbon.get_curve_num_cvs(ribbon_wire_curve)):
        cmds.select(ribbon_wire_curve+'.cv[%d]' % i)
        temp_clstr_name = 'ribbon_clstr_'+str(i).zfill(2)+'_'
        ribbon_clstr_list.append(cmds.cluster(name=temp_clstr_name)[1])
        cmds.setAttr(temp_clstr_name+'Handle.visibility', 0)
        
    ribbon_clstrs_grp = cmds.group(ribbon_clstr_list, n='ribbon_clstrs_grp')
    
    #create wire deformer
    cmds.wire(ribbon_sfc, w=ribbon_wire_curve, dds=(0,50))
    ribbon_wire_grp = cmds.group([ribbon_wire_curve, ribbon_wire_curve+'BaseWire'],
                                  n='ribbon_wire_grp')
    
    #fix orientations for spine_ik_jnts
    for i in range(1,len(spine_ik_jnts))[::-1]:
        temp_jnt_driver = '_'.join(['ik', prefix, str(i+1).zfill(2)])
        temp_jnt_driven = '_'.join(['ik', prefix, str(i).zfill(2)])
        cmds.aimConstraint(temp_jnt_driver, temp_jnt_driven, 
                            aim=(1.0,0.0,0.0), wut='objectrotation', 
                            wuo=temp_jnt_driver)

    #setup ribbon twist
    ribbon_twist_sfc = 'spine_ribbon_twist_surface'
    cmds.duplicate(ribbon_sfc, n=ribbon_twist_sfc)
    twist_handle = ribbon.create_twist_deformer(sfc=ribbon_twist_sfc, prefix=prefix)

    twist_angle_plus_minus_node = connect_body_ctrl_to_ribbon(body_ctrl, twist_handle)

    connect_twist_ribbon(prefix, hip_ctrl, twist_angle_plus_minus_node, 'start')
    connect_twist_ribbon(prefix, chest_ctrl, twist_angle_plus_minus_node, 'end')
    
    twist_mult_node = 'spine_twist_master_mult_node'
    cmds.createNode('multiplyDivide', n=twist_mult_node)
    cmds.connectAttr(base_rig.master_ctrl.ctrl+'.rotateY', twist_mult_node+'.input1X')
    cmds.setAttr(twist_mult_node+'.input2X', -1)
    cmds.connectAttr(twist_mult_node+'.outputX', 'start'+twist_angle_plus_minus_node+'.input1D[2]')
    cmds.connectAttr(twist_mult_node+'.outputX', 'end'+twist_angle_plus_minus_node+'.input1D[2]')
    
    ribbon_bs = prefix+'_ribbon_blendshape'
    cmds.blendShape(ribbon_twist_sfc, ribbon_sfc, n=ribbon_bs)
    cmds.setAttr(ribbon_bs+'.'+ribbon_twist_sfc, 1)
    
    cmds.select(hip_ctrl.ctrl, chest_ctrl.ctrl)
    cmds.xform(rotateOrder='yzx')
    
    cmds.select(ribbon_sfc)
    cmds.reorderDeformers('wire1', ribbon_bs)
    
    
    #set up skel constraints
    cmds.select(d=True)
    for i in range(len(spine_jnts)-1):
        driver = spine_ik_jnts[i]
        driven = spine_jnts[i]
        cmds.pointConstraint(driver, driven, maintainOffset=False)
        cmds.orientConstraint(driver, driven, maintainOffset=False)
    
    ik_spine_04_orient_jnt = spine_ik_jnts[3]+'_orient'
    cmds.duplicate(spine_ik_jnts[3], n=ik_spine_04_orient_jnt)
    cmds.parent(ik_spine_04_orient_jnt, chest_ctrl.ctrl)
    cmds.makeIdentity(ik_spine_04_orient_jnt, t=0, r=1, s=0, apply=True)
    cmds.pointConstraint(ik_spine_04_orient_jnt, spine_jnts[3], maintainOffset=False)
    cmds.orientConstraint(ik_spine_04_orient_jnt, spine_jnts[3], maintainOffset=False)
    
    pelvis_orient_jnt = 'pelvis_orient'
    cmds.duplicate('pelvis', n=pelvis_orient_jnt, rc=True)
    cmds.delete(cmds.listRelatives(pelvis_orient_jnt))
    
    cmds.parent(pelvis_orient_jnt, hip_ctrl.ctrl)
    cmds.makeIdentity(pelvis_orient_jnt, t=0, r=1, s=0, apply=True)
    cmds.pointConstraint(pelvis_orient_jnt, 'pelvis', maintainOffset=False)
    cmds.orientConstraint(pelvis_orient_jnt, 'pelvis', maintainOffset=False)
    
    #AUTO MOVEMENT FOR spine_ctrl
    spine_ctrl_drv = 'spine_ctrl_drv'
    cmds.select(d=True)
    cmds.group(n=spine_ctrl_drv, em=True)
    
    cmds.delete(cmds.parentConstraint(spine_ctrl.ofst, spine_ctrl_drv))
    cmds.parent(spine_ctrl_drv, spine_ctrl.ofst)
    cmds.parent(spine_ctrl.ctrl, spine_ctrl_drv)
    
    #create joint for spine_ctrl
    create_spine_ctrl_auto_jnts(hip_ctrl, 'bottom', spine_ctrl, spine_ctrl_drv)
    create_spine_ctrl_auto_jnts(chest_ctrl, 'top', spine_ctrl, spine_ctrl_drv)
        
    #spine_ctrl auto switch
    cmds.addAttr(chest_ctrl.ctrl, shortName='midInfluence', keyable=True, 
                 defaultValue=0.0, minValue=0.0, maxValue=1.0)

    create_spine_ctrl_auto_switch(chest_ctrl, spine_ctrl_drv)
     
    
    #set up ctrl constraints
    cmds.parentConstraint(hip_ctrl.ctrl, ribbon_clstr_list[0], mo=True)
    cmds.parentConstraint(spine_ctrl.ctrl, ribbon_clstr_list[1], mo=True)
    cmds.parentConstraint(chest_ctrl.ctrl, ribbon_clstr_list[2], mo=True)


    #cleanup
    spine_sfc_grp = 'spine_sfc_grp'
    spine_deformers_grp = 'spine_deformers_grp'
    cmds.group([ribbon_sfc, ribbon_twist_sfc], name=spine_sfc_grp)
    cmds.group(twist_handle, name=spine_deformers_grp)
    cmds.parent([spine_follicles_grp, ribbon_wire_grp, 
                    ribbon_clstrs_grp, spine_sfc_grp, spine_deformers_grp],
                 rig_module.dnt_grp)
    
    return [chest_ctrl, spine_ctrl, hip_ctrl, body_ctrl]
예제 #23
0
    def createRibbon(self, *args):
        self.name = cmds.textFieldGrp(self.widgets["ribbonNameTFG"],
                                      q=True,
                                      tx=True)
        self.numDiv = (cmds.intFieldGrp(
            self.widgets["jointsIFG"], q=True, v=True)[0]) - 1
        self.fk = cmds.checkBox(self.widgets["fkSetupCB"], q=True, v=True)
        self.height = cmds.floatFieldGrp(self.widgets["heightFFG"],
                                         q=True,
                                         v1=True)
        self.ratio = cmds.floatFieldGrp(self.widgets["ratioFFG"],
                                        q=True,
                                        v1=True)
        self.axis = cmds.radioButtonGrp(self.widgets["axis"], q=True, sl=True)

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

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

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

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

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

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

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

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

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

            self.follicleList.append(follicle)

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

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

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

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

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

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

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

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

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

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

            cmds.parent(locName, groupName)

            #create a parent constraint locator under the aim locator

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        cmds.select(ribbonGroup)
예제 #24
0
    def nurbCreation(self,
                     name,
                     directionAxi=[0, 1, 0],
                     splitU=1,
                     splitV=5,
                     width=0.1,
                     lengthRatio=0.5,
                     jnt=2):
        joints = []
        #Positions and direction joints
        if directionAxi == [0, 0, 1]:
            print(
                'Aun no se desarrollo esta direccion de la nurbs, comuniquese con el desarrollador. Gracias.'
            )  #creo controles en los huesos del espacio con una direccion x
        elif directionAxi == [1, 0, 0]:
            print(
                'Aun no se desarrollo esta direccion de la nurbs, comuniquese con el desarrollador. Gracias.'
            )  #creo controles en los huesos del espacio con una direccion x
        elif directionAxi == [0, 1, 0]:
            x = int(splitV)  #maximo de distancia de cada lado para el array
            lista = range(-x, x + 1, jnt)
            for j in lista:
                pos = j / float((splitV / (splitV / 2)) / width)
                side = 'B' if j < 0 else 'C' if j == 0 else 'T'
                joints.append(
                    self.JointInSpace(name + side + str(j), [0, 0, pos],
                                      width + 0.2 / 2))
        self.grpCtroles = []
        self.grpCtroles.append(
            self.createCnt(joints, [0, 0, 1], width, True)
        )  #creo controles en los huesos del espacio con una direccion z
        #Create nurb with folicles
        self.nurb = cmds.nurbsPlane(ax=directionAxi,
                                    w=width,
                                    lr=splitV,
                                    u=splitU,
                                    v=splitV,
                                    n=name + '_NSK')
        self.nurbName = cmds.rebuildSurface(self.nurb,
                                            rpo=1,
                                            rt=0,
                                            end=1,
                                            kr=0,
                                            kcp=0,
                                            kc=1,
                                            su=splitU,
                                            du=1,
                                            sv=splitV,
                                            dv=3,
                                            tol=0.01,
                                            fr=0,
                                            dir=2)  #reconstruyo la build
        cmds.setAttr(str(self.nurbName[0]) + '.inheritsTransform', 0)
        mel.eval('createHair ' + str(splitU) + ' ' + str(splitV) +
                 ' 5 0 0 0 0 ' + str(splitU) + ' 0 2 2 1')
        cmds.delete('hairSystem1', 'hairSystem1OutputCurves', 'nucleus1')
        self.grpFoll = cmds.rename('hairSystem1Follicles',
                                   (name + '_Follicles' + '_GRP'))
        cmds.setAttr(str(self.grpFoll) + '.inheritsTransform', False)
        cmds.setAttr(str(self.grpFoll) + '.visibility', False)
        self.follicles = cmds.listRelatives(self.grpFoll, children=True)
        self.jntsToSkin = []
        for f in range(len(self.follicles)):
            self.foll = cmds.rename(self.follicles[f], name + str(f) + '_FLC')
            cmds.delete(cmds.listRelatives(self.foll, children=1)[1])
            self.jnt = cmds.joint(name=name + str(f) + '_JSK',
                                  absolute=1,
                                  radius=float(width) / 2,
                                  rotationOrder='xyz')
            self.jntsToSkin.append(self.jnt)
            cmds.connectAttr(self.foll + '.outTranslate',
                             self.jnt + '.translate',
                             f=1)
            cmds.connectAttr(self.foll + '.outRotate',
                             self.jnt + '.rotate',
                             f=1)
        cmds.parent(self.jntsToSkin[1:], w=1)
        for j in self.jntsToSkin:  #Fix bones rotation axis
            cmds.setAttr(j + '.jointOrientX', 0)
            cmds.setAttr(j + '.jointOrientY', 0)
            cmds.setAttr(j + '.jointOrientZ', 0)
        #create skin #Prune weights #Remove unused influences
        self.scl = cmds.skinCluster(joints,
                                    self.nurbName[0],
                                    n=name + '_SCL',
                                    mi=3,
                                    dr=14.0)[0]
        cmds.select(self.nurbName[0])
        mel.eval('doPruneSkinClusterWeightsArgList 1 { "' + str(0.2) + '" }')
        mel.eval('removeUnusedInfluences')
        cmds.select(cl=1)
        #Creation Groups
        self.gJoints = self.grupoDe(self.jntsToSkin,
                                    name + '_jointsToSkin',
                                    inherits=False,
                                    vis=False)
        self.gJntsRig = self.grupoDe(joints,
                                     name + '_joint',
                                     inherits=False,
                                     vis=False)
        self.follicles = cmds.listRelatives(self.grpFoll, children=True)
        self.gCnts = self.grupoDe(self.grpCtroles[0],
                                  name + '_controls',
                                  inherits=True,
                                  shape=True)
        self.gNurb = self.grupoDe(self.nurbName,
                                  name=name + '_NURBS',
                                  inherits=False)
        self.gMaster = self.grupoDe([
            self.grpFoll, self.gJoints, self.gJntsRig, self.gCnts, self.gNurb
        ], name)

        return [
            self.nurbName[0], self.follicles, self.jntsToSkin, joints,
            self.scl, self.gCnts
        ]
예제 #25
0
    def createRibbon(self, *args):
        self.name = cmds.textFieldGrp(self.widgets["ribbonNameTFG"],
                                      q=True,
                                      tx=True)
        self.numDiv = (cmds.intFieldGrp(
            self.widgets["jointsIFG"], q=True, v=True)[0]) - 1
        #self.fk = cmds.checkBox(self.widgets["fkSetupCB"], q=True, v=True)
        self.height = cmds.floatFieldGrp(self.widgets["heightFFG"],
                                         q=True,
                                         v1=True)
        self.ratio = cmds.floatFieldGrp(self.widgets["ratioFFG"],
                                        q=True,
                                        v1=True)
        #self.axis = cmds.radioButtonGrp(self.widgets["axis"] , q=True, sl=True)

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

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

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

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

        #if self.own == 0:
        width = self.height / self.ratio

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

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

        # else:
        # 	self.ribbonName = self.myGeo

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

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

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

            self.follicleList.append(follicle)

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

        #create controls here:
        #create a loop that runs through the cvs in v, 0 to 6
        origClusterList = [
            "top_CLS", "topBez_CLS", "centerTop_CLS", "center_CLS",
            "centerEnd_CLS", "endBez_CLS", "end_CLS"
        ]
        origControlList = [
            "top_CTRL", "topBez_CTRL", "centerTop_CTRL", "center_CTRL",
            "centerEnd_CTRL", "endBez_CTRL", "end_CTRL"
        ]

        clusterList = []
        controlList = []
        constrGrpList = []
        attachGrpList = []

        for v in range(0, 7):
            cmds.select(clear=True)
            clusNodeName = self.name + "_" + origClusterList[v] + "Base"
            #select u (0 and 1) for each v and cluster them
            fullCls = cmds.cluster("%s.cv[0:1][%d]" % (self.ribbonName, v),
                                   relative=False,
                                   n=clusNodeName)[0]
            clusHandle = clusNodeName + "Handle"
            clusName = clusHandle.rstrip("BaseHandle")
            cmds.rename(clusHandle, clusName)
            clusterList.append(clusName)
            #now setup the controls and groups for the clusters
            #goes control,group (const), group(attach)
            control = self.name + "_" + origControlList[v]
            constrGrp = self.name + "_" + origControlList[v] + "_const_GRP"
            attachGrp = self.name + "_" + origControlList[v] + "_attach_GRP"

            rig.createControl(name=control,
                              type="circle",
                              axis="y",
                              color="darkGreen",
                              *args)
            oldGrp = rig.groupOrient(clusName, control)
            cmds.rename(oldGrp, constrGrp)

            #parent clus to control
            cmds.parent(clusName, control)

            #get cluster position
            clusPos = cmds.pointPosition(clusName + ".rotatePivot")
            cmds.xform(constrGrp,
                       ws=True,
                       piv=(clusPos[0], clusPos[1], clusPos[2]))

            cmds.group(constrGrp, n=attachGrp)
            cmds.xform(attachGrp,
                       ws=True,
                       piv=(clusPos[0], clusPos[1], clusPos[2]))

            controlList.append(control)
            constrGrpList.append(constrGrp)
            attachGrpList.append(attachGrp)
def createNurb(uNumber=5, vNumber=5, side=None, name=None, mX=0, mY=0, mZ=0):
    name = '{}_{}_nurb'.format(name, side)

    try:
        crv = cmds.polyToCurve(n='deletableCurve',
                               form=2,
                               degree=3,
                               conformToSmoothMeshPreview=1)[0]

        degs = cmds.getAttr('{}.degree'.format(crv))
        spans = cmds.getAttr('{}.spans'.format(crv))

        cvs = degs + spans
        #
        #crv1 = cmds.duplicate(crv, n='deletableCurve1')[0]
        #cmds.select('{}.cv[0:{}]'.format(crv1, cvs))

        #cmds.move(mX, mY, mZ, r=True, os=True, wd=True)

        #crv2 = cmds.duplicate(crv, n='deletableCurve2')[0]
        #cmds.select('{}.cv[0:{}]'.format(crv2, cvs))

        #mX= mX*(-1)
        #mY= mY*(-1)
        #mZ= mZ*(-1)

        #cmds.move(mX, mY, mZ, r=True, os=True, wd=True)
        mnX = mX * (-1)
        offst_curve1 = cmds.offsetCurve(crv, d=mX)[0]
        offst_curve2 = cmds.offsetCurve(crv, d=mnX)[0]

        surf = cmds.loft(offst_curve1,
                         offst_curve2,
                         ch=1,
                         u=1,
                         c=0,
                         ar=1,
                         d=3,
                         ss=1,
                         rn=0,
                         po=0,
                         rsn=True,
                         n=name)[0]
        cmds.rebuildSurface(surf,
                            ch=1,
                            rpo=1,
                            rt=0,
                            end=1,
                            kr=0,
                            kcp=0,
                            kc=0,
                            su=uNumber,
                            du=3,
                            sv=vNumber,
                            dv=3,
                            tol=0.01,
                            fr=0,
                            dir=2)
        cmds.delete(surf, ch=True)
        for c in [crv, offst_curve1, offst_curve2]:
            cmds.delete(c)

    except:
        cmds.nurbsPlane(n=name,
                        ax=(0, 1, 0),
                        w=True,
                        lr=True,
                        d=3,
                        u=uNumber,
                        v=vNumber,
                        ch=1)
예제 #27
0
         self.logger.error('_createPlane(): Error getting distance from start to end transforms: %s'%e)
     raise Exception(e)  
 
 #--- Create the plane
 try:
     plane = cmds.nurbsPlane(name=name+'_rbbnPlane', w=1, lengthRatio=dist, d=3, u=1, v=spans, ax=normal)[0]
     if self.logger:
         self.logger.info('_createPlane(): Created plane: %s'%plane)            
 except Exception,e:
     if self.logger:
         self.logger.error('_createPlane(): Error creating plane: %s'%e)
     raise Exception(e)
 
 #--- Rebuild the plane
 try:
     cmds.rebuildSurface(plane,rt=1,du=1,dv=3)
     cmds.rebuildSurface(plane,rt=0,su=1,sv=spans,du=1,dv=3)
     if self.logger:
         self.logger.info('_createPlane(): Rebuilt surface.')           
 except Exception,e:
     if self.logger:
         self.logger.error('_createPlane(): Error creating plane: %s'%e)     
     raise Exception(e)
 
 #--- Delete history
 try:
     cmds.select(plane,r=True)
     mel.eval('DeleteHistory;')
     cmds.select(clear=True)
     if self.logger:
         self.logger.info('_createPlane(): Deleted surface history.')           
예제 #28
0
def SpineSetUp(BIND_Spine_Joints, path, FK_Spine_Joints):
	print "In Spine Set Up using a ribbon spine"

	JntPos = []
	x = 0
	for each in BIND_Spine_Joints:
		JntPos.append(cmds.xform(BIND_Spine_Joints[x], q=True, translation=True))
		x += 1

	RibbonLen = JntPos[0][0] + JntPos[1][0] + JntPos[2][0] + JntPos[3][0] + JntPos[4][0]
	RibbonLen = RibbonLen + (RibbonLen/5)


	# Create group for ribbon rig
	ribbonRigGrp = cmds.group(em=True, n=("Ribbon_Spine_Grp"))

	# Create group for follicles
	folGrp = cmds.group(em=True, n="Spine_Follicles_Grp")

	
	# Create nurbs plane
	ribbonPlane = cmds.nurbsPlane (n=("Ribbon_Spine_Plane"), p=[0, 0, 0], ax= [0, 0 ,1], w=1 ,lr=RibbonLen ,d=3, u=1, v=5, ch=0)
	cmds.rebuildSurface(rebuildType=0, direction=0, spansU=1, spansV=5, degreeU=1, degreeV=3, keepRange=0)

	cmds.parent(ribbonPlane, ribbonRigGrp)

	pc = cmds.pointConstraint(BIND_Spine_Joints[2], ribbonPlane, mo=False)
	cmds.delete(pc)
	
	# Get the shape node
	ribbonPlaneShape = cmds.listRelatives(ribbonPlane, c=True, s=True)


	folList = []
	IK_Spine_Joints = []
	x=0

	# Create a list for the follicles
	spineList = [BIND_Spine_Joints[0], BIND_Spine_Joints[1], BIND_Spine_Joints[2], BIND_Spine_Joints[3], BIND_Spine_Joints[4]]


	# Creates a follicle for each of the spine joints
	# Creates a joint for each follicle and parents it under the follicles
	for each in spineList:
		follicle = cmds.createNode("follicle", n=each + "_follicleShape")
		follicleTransform = cmds.listRelatives(follicle, p=True)
		
		cmds.connectAttr(ribbonPlaneShape[0] + ".local", follicle + ".inputSurface")
		cmds.connectAttr(ribbonPlaneShape[0] + ".worldMatrix[0]", follicle + ".inputWorldMatrix")
		cmds.connectAttr(follicle + ".outRotate", follicleTransform[0] + ".rotate")
		cmds.connectAttr(follicle + ".outTranslate", follicleTransform[0] + ".translate")

		#position the follicles along the plane
		cmds.setAttr(follicle + ".parameterU", 0.5)
		vSpanHeight = ((x+1.0)/5.0) - .1
		cmds.setAttr(follicle + ".parameterV", vSpanHeight)

		cmds.parent(follicleTransform[0], folGrp)
		folList.append(follicle)


		jntName = "IK_" + str(each).partition("_")[2]
		jnt = cmds.joint(n=jntName)
		pc = cmds.parentConstraint(follicle, jnt)
		cmds.delete(pc)

		cmds.makeIdentity(jnt, apply=True, t=True, r=True, s=True, n=False)

		cmds.setAttr(str(jnt)+".jointOrientZ", 90)

		IK_Spine_Joints.append(cmds.ls(sl=True))

		x+=1

	
	cmds.select(cl=True)



	# Creates controls to drive the joints
	# import the cube controls and circle control, rename, and add it to Ctl list
	Ctl = []
	CtlGrp = []

	cmds.file(path, i=True)
	cmds.select("curve1", r=True)
	cmds.rename("Hips_CTRL")
	Ctl.append(cmds.ls(sl=True))
	cmds.group(n="Hips_CTRL_zero_rg")
	CtlGrp.append(cmds.ls(sl=True))

	cmds.circle(n="Midriff_CTRL")
	cmds.setAttr("Midriff_CTRL.rotateY", 90)
	cmds.makeIdentity(apply=True, t=True, r=True, s=True, n=False)

	Ctl.append(cmds.ls(sl=True))
	cmds.group(n="Midriff_CTRL_zero_rg")
	CtlGrp.append(cmds.ls(sl=True))

	cmds.file(path, i=True)
	cmds.select("curve1", r=True)
	cmds.rename("Chest_CTRL")
	Ctl.append(cmds.ls(sl=True))
	cmds.group(n="Chest_CTRL_zero_rg")
	CtlGrp.append(cmds.ls(sl=True))



	# Creates locators to be used as aim constraints
	locHipAim = cmds.spaceLocator(n="HipsAim_LOC")
	cmds.parent(locHipAim, Ctl[0][0])
	locHipUp = cmds.spaceLocator(n="HipsUp_LOC")
	cmds.xform(locHipUp, translation=(0, -1, 0))
	cmds.makeIdentity(apply=True, t=True, r=True, s=True, n=False)
	cmds.parent(locHipUp, Ctl[0][0])

	locMidAim = cmds.spaceLocator(n="MidriffAim_LOC")
	cmds.parent(locMidAim, Ctl[1][0])
	locMidUp = cmds.spaceLocator(n="MidriffUp_LOC")
	cmds.xform(locMidUp, translation=(0, -1, 0))
	cmds.makeIdentity(apply=True, t=True, r=True, s=True, n=False)
	cmds.parent(locMidUp, Ctl[1][0])

	locChestAim = cmds.spaceLocator(n="ChestAim_LOC")
	cmds.parent(locChestAim, Ctl[2][0])
	locChestUp = cmds.spaceLocator(n="ChestUp_LOC")
	cmds.xform(locChestUp, translation=(0, -1, 0))
	cmds.makeIdentity(apply=True, t=True, r=True, s=True, n=False)
	cmds.parent(locChestUp, Ctl[2][0])



	# Place the ribbon spine controls
	pc = cmds.parentConstraint(spineList[0], CtlGrp[0][0], mo=False)
	cmds.delete(pc)

	pc = cmds.parentConstraint(spineList[2], CtlGrp[1][0], mo=False)
	cmds.delete(pc)

	pc = cmds.parentConstraint(spineList[4], CtlGrp[2][0], mo=False)
	cmds.delete(pc)

	cmds.select(cl=True)


	DriveJnts = []

	# Create the driver for the ribbon spine rig
	TopDrv1 = cmds.joint(n="topDriver_01_rgJnt")
	DriveJnts.append(cmds.ls(sl=True))
	pc = cmds.pointConstraint(spineList[4], TopDrv1, mo=False)
	cmds.delete(pc)

	TopDrv2 = cmds.joint(n="topDriver_02_rgJnt")
	DriveJnts.append(cmds.ls(sl=True))
	pc = cmds.pointConstraint(spineList[3], TopDrv2, mo=False)
	cmds.delete(pc)
	

	cmds.select(cl=True)

	BotDrv1 = cmds.joint(n="bottomDriver_01_rgJnt")
	DriveJnts.append(cmds.ls(sl=True))
	pc = cmds.pointConstraint(spineList[0], BotDrv1, mo=False)
	cmds.delete(pc)

	BotDrv2 = cmds.joint(n="bottomDriver_02_rgJnt")
	DriveJnts.append(cmds.ls(sl=True))
	pc = cmds.pointConstraint(spineList[1], BotDrv2, mo=False)
	cmds.delete(pc)

	cmds.select(cl=True)
	
	MidDrv = cmds.joint(n="midDriver_rgJnt")
	DriveJnts.append(cmds.ls(sl=True))
	pc = cmds.pointConstraint(spineList[2], MidDrv, mo=False)
	cmds.delete(pc)


	for each in DriveJnts:
		print each[0]
		cmds.joint( each[0], e=True, zso=True, oj='xyz', sao = 'yup' )

	cmds.setAttr(str(DriveJnts[1][0])+".jointOrientZ", 0)
	cmds.setAttr(str(DriveJnts[3][0])+".jointOrientZ", 0)
	cmds.setAttr(str(DriveJnts[4][0])+".jointOrientZ", 90)

	cmds.parent(TopDrv1, locChestAim)
	cmds.parent(BotDrv1, locHipAim)
	cmds.parent(MidDrv, locMidAim)

	
	# Create aim constraints
	cmds.aimConstraint( Ctl[2][0], locHipAim, aimVector=(0.0, 1.0, 0.0), upVector=(1.0, 0.0, 0.0), worldUpType="object", worldUpObject=locHipUp[0], mo=True )
	cmds.aimConstraint( Ctl[0][0], locChestAim, aimVector=(0.0, -1.0, 0.0), upVector=(1.0, 0.0, 0.0), worldUpType="object", worldUpObject=locChestUp[0], mo=True )

	# Create point constraint
	cmds.pointConstraint(Ctl[2][0], Ctl[0][0], CtlGrp[1][0])

	# Aim the middle control to the top control
	cmds.aimConstraint(Ctl[2][0], locMidAim, aimVector=(0.0, 1.0, 0.0), upVector=(1.0, 0.0, 0.0), worldUpType="object", worldUpObject=locMidUp[0] )


	# Bind joints
	cmds.skinCluster( ribbonPlane, TopDrv1, BotDrv1, MidDrv )


	# Spine Cleanup
	# constrain the IK and FK joint chains to the BIND chain
	x = 0
	bindConstraints = []
	for eachJoint in BIND_Spine_Joints:
		print eachJoint
		bindConstraints.append(cmds.parentConstraint(FK_Spine_Joints[x], IK_Spine_Joints[x], BIND_Spine_Joints[x], mo=True))
		x += 1

	# hides the FK and IK arm joints
	cmds.setAttr(str(FK_Spine_Joints[0]) + ".visibility", False)
	


	for each in IK_Spine_Joints:
		cmds.setAttr(str(each[0]) + ".visibility", False)
예제 #29
0
def create(length=10.0,width=0.5,mainCtrls=4,subCtrls=10,surface=True,curve=False,prefix=''):
	'''
	Create a ribbon rig with a primary base and tip controls
	@param length: Ribbon length 
	@type length: float
	@param width: Ribbon width 
	@type width: float
	@param mainCtrls: Number of main ribbon controls
	@type mainCtrls: int
	@param subCtrls: Number of ribbon sub controls
	@type subCtrls: int
	@param surface: Output ribbon surface
	@type surface: bool
	@param curve: Output ribbon curve
	@type curve: bool
	@param prefix: Name prefix for created nodes
	@type prefix: str
	'''
	
	# Check prefix
	if not prefix: prefix = 'ribbon'
	
	# -----------------
	# - Create Groups -
	# -----------------
	
	ctrl_grp = mc.group(em=True,n=prefix+'_ctrl_grp')
	hist_grp = mc.group(em=True,n=prefix+'_hist_grp')
	out_grp = mc.group(em=True,n=prefix+'_out_grp')
	rig_grp = mc.group([ctrl_grp,hist_grp,out_grp],n=prefix+'_grp')
	
	mc.setAttr(hist_grp+'.v',0)
	
	# ----------------------
	# - Create Base Ribbon -
	# ----------------------
	
	# Generate point array
	base_inc = float(length) / (mainCtrls-1)
	base_pts = [(width*.5,base_inc*i,0.0) for i in range(mainCtrls)]
	
	# Curve 0
	base_crv_0 = mc.curve(d=1,p=base_pts,k=range(len(base_pts)),n=prefix+'_base0_crv')
	mc.rebuildCurve(base_crv_0,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
	base_crv_0_locs = glTools.utils.curve.locatorCurve(base_crv_0,prefix=prefix+'_base0')
	glTools.utils.shape.createIntermediate(base_crv_0)
	mc.rebuildCurve(base_crv_0,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(mainCtrls-1),d=3,tol=0)
	
	# Flip CV array
	base_pts = [(-i[0],i[1],i[2]) for i in base_pts]
	
	# Curve 1
	base_crv_1 = mc.curve(d=1,p=base_pts,k=range(len(base_pts)),n=prefix+'_base1_crv')
	mc.rebuildCurve(base_crv_1,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
	base_crv_1_locs = glTools.utils.curve.locatorCurve(base_crv_1,prefix=prefix+'_base1')
	glTools.utils.shape.createIntermediate(base_crv_1)
	mc.rebuildCurve(base_crv_1,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(mainCtrls-1),d=3,tol=0)
	
	# Loft
	base_loft = mc.loft([base_crv_0,base_crv_1],d=1,n=prefix+'_base_surface')
	base_surface = base_loft[0]
	base_loft = mc.rename(base_loft[1],prefix+'_base_loft')
	
	# Rebuild
	base_rebuild = mc.rebuildSurface(base_surface,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=1,kc=1,su=0,du=0,sv=0,dv=0,tol=0,fr=0,dir=2,n=prefix+'_base_rebuildSurface')
	
	mc.parent([base_crv_0,base_crv_1,base_surface],hist_grp)
	
	# -------------------------------
	# - Create Base and Tip Control -
	# -------------------------------
	
	# Base Control
	mc.select(cl=True)
	base_jnt = mc.joint(n=prefix+'_baseA_jnt',radius=0.0)
	base_grp = mc.group(base_jnt,n=prefix+'_baseA_grp')
	mc.parent(base_grp,ctrl_grp)
	
	ctrlBuilder.controlShape(base_jnt,'circle',rotate=(90,0,0),scale=0.2*length)
	
	# Tip Control
	mc.select(cl=True)
	tip_jnt = mc.joint(n=prefix+'_tipA_jnt',radius=0.0)
	tip_grp = mc.group(tip_jnt,n=prefix+'_tipA_grp')
	mc.parent(tip_grp,ctrl_grp)
	# Position Tip
	mc.move(0,length,0,tip_grp,ws=True,a=True)
	
	ctrlBuilder.controlShape(tip_jnt,'circle',rotate=(90,0,0),scale=0.2*length)
	
	# ------------------------
	# - Create Main Controls -
	# ------------------------
	
	# Check mid control
	mid = False
	if (float(mainCtrls)/2) % 1: mid = True
	
	# Determine mid point
	if mid: split = int(math.ceil(float(mainCtrls)/2))-1
	else : split = int(mainCtrls/2)
	
	# Create controls
	for i in range(mainCtrls):
		
		# Clear selection
		mc.select(cl=True)
		
		# Create main control joint
		index = glTools.utils.stringUtils.alphaIndex(int(math.floor(i)),True)
		jnt = mc.joint(n=prefix+'_main'+index+'_jnt',radius=0.0)
		grp = mc.group(jnt,n=prefix+'_main'+index+'_grp')
		
		ctrlBuilder.controlShape(jnt,'square',rotate=(90,0,0),scale=0.125*length)
		
		# Position main control joint
		locs = [base_crv_0_locs[i],base_crv_1_locs[i]]
		mc.delete( mc.pointConstraint(locs,grp) )
		mc.parent(locs,jnt)
		mc.makeIdentity(locs,apply=True,t=1,r=1,s=1,n=0)
		for loc in locs: mc.setAttr(loc+'.v',0)
		
		# Constrain to base/tip control
		connBlend = glTools.utils.constraint.blendConstraint([base_jnt,tip_jnt],grp,jnt,blendAttr='bias',maintainOffset=True,prefix='')
		
		# Set constraint weights
		if mid and i == split:
			mc.setAttr(connBlend,0.5)
		else:
			if i < split: mc.setAttr(connBlend,0.0)
			else: mc.setAttr(connBlend,1.0)
		
		# Parent to main control group
		mc.parent(grp,ctrl_grp)
	
	# ----------------------
	# - Build Sub Controls -
	# ----------------------
	
	sub_ctrl_list = []
	sub_grp_list = []
	sub_ctrl_grp = mc.group(em=True,n=prefix+'_subCtrl_grp')
	# Turn off inheritTransform
	mc.setAttr(sub_ctrl_grp+'.inheritsTransform',0)
	
	# Build point array
	sub_inc = float(length) / (subCtrls - 1)
	pts = [[0,(sub_inc*i),0] for i in range(subCtrls)]
	
	for i in range(subCtrls):
		
		# Clear selection
		mc.select(cl=True)
		
		# Create sub control joint
		index = glTools.utils.stringUtils.alphaIndex(i,True)
		sub_jnt = mc.joint(n=prefix+'_sub'+index+'_jnt',radius=0.0)
		sub_grp = mc.group(sub_jnt,n=prefix+'_sub'+index+'_grp')
		
		ctrlBuilder.controlShape(sub_jnt,'box',scale=0.025*length)
		
		# Position and attach sub controls
		mc.setAttr(sub_grp+'.t',pts[i][0],pts[i][1],pts[i][2])
		glTools.utils.attach.attachToSurface(base_surface,sub_grp,uValue=0.0,vValue=0.0,useClosestPoint=True,orient=True,uAxis='-x',vAxis='y',uAttr='uCoord',vAttr='vCoord',alignTo='v',prefix=prefix+'_sub'+index)
		
		# Append list
		sub_ctrl_list.append(sub_jnt)
		sub_grp_list.append(sub_grp)
	
	mc.parent(sub_grp_list,sub_ctrl_grp)
	mc.parent(sub_ctrl_grp,ctrl_grp)
	
	# ----------------
	# - Build Output -
	# ----------------
	
	# -----
	# Curve
	
	if curve:
	
		# Build curve
		ribbon_crv = mc.curve(d=1,p=pts,n=prefix+'_ribbon_curve')
		mc.rebuildCurve(ribbon_crv,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
		
		# Create curve locators
		crv_locs = glTools.utils.curve.locatorCurve(ribbon_crv,prefix=prefix)
		glTools.utils.shape.createIntermediate(ribbon_crv)
		
		# Rebuild ribbon curve
		mc.rebuildCurve(ribbon_crv,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(subCtrls-1),d=3,tol=0,n=prefix+'_ribbon_rebuildCurve')
		
		# Parent curve locators
		for i in range(len(crv_locs)):
			mc.parent(crv_locs[i],sub_ctrl_list[i])
			mc.setAttr(crv_locs[i]+'.v',0)
			
		mc.parent(ribbon_crv,out_grp)
		
	# -----------
	# - Surface -
	
	if surface:
		
		# Offset CV array
		pts = [(width*.5,i[1],i[2]) for i in pts]
		
		# Sub Curve 0
		sub_crv_0 = mc.curve(d=1,p=pts,k=range(len(pts)),n=prefix+'_sub0_crv')
		mc.rebuildCurve(sub_crv_0,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
		sub_crv_0_locs = glTools.utils.curve.locatorCurve(sub_crv_0,prefix=prefix+'_sub0')
		glTools.utils.shape.createIntermediate(sub_crv_0)
		mc.rebuildCurve(sub_crv_0,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(subCtrls-1),d=3,tol=0,n=prefix+'_sub0_rebuildCurve')
		
		# Flip CV array
		pts = [(-i[0],i[1],i[2]) for i in pts]
		
		# Curve 1
		sub_crv_1 = mc.curve(d=1,p=pts,k=range(len(pts)),n=prefix+'_sub1_crv')
		mc.rebuildCurve(sub_crv_1,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=0,d=3,tol=0)
		sub_crv_1_locs = glTools.utils.curve.locatorCurve(sub_crv_1,prefix=prefix+'_sub1')
		glTools.utils.shape.createIntermediate(sub_crv_1)
		mc.rebuildCurve(sub_crv_1,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=(subCtrls-1),d=3,tol=0,n=prefix+'_sub1_rebuildCurve')
		
		# Loft
		ribbon_loft = mc.loft([sub_crv_0,sub_crv_1],d=1,n=prefix+'_ribbon_surface')
		ribbon_surface = ribbon_loft[0]
		ribbon_loft = mc.rename(ribbon_loft[1],prefix+'_ribbon_loft')
			
		# Parent curve locators
		for i in range(len(pts)):
			locs = [sub_crv_0_locs[i],sub_crv_1_locs[i]]
			mc.parent(locs,sub_ctrl_list[i])
			mc.makeIdentity(locs,apply=True,t=1,r=1,s=1,n=0)
			for loc in locs: mc.setAttr(loc+'.v',0)
			
		mc.parent([sub_crv_0,sub_crv_1],hist_grp)
		mc.parent(ribbon_surface,out_grp)
예제 #30
0
def _buildSideSplashEmitter(name='',
                            boatName='',
                            splashParticleName=[],
                            boatIntersectCurveShape='',
                            sideAnimatable='',
                            presetName=None):
    """
    New builder for sideSplash nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: List of the names of nParticleShape nodes to connect to the emitter
    @param boatIntersectCurveShape: The name of the intersection curve to emit from.
    @type name:  String
    @type splashParticleName: List
    @type boatIntersectCurveShape: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n='nPARTICLE_EMITTERS_hrc', em=True)

    debug(None,
          method='_buildSideSplashEmitter',
          message='name: %s' % name,
          verbose=False)

    # Get base flat surface
    lineCurve = cmds.curve(name='%s_extrudeCurve' % name,
                           degree=1,
                           point=[(-0.01, 0, 0), (0.01, 0, 0)])
    flatSurface = cmds.extrude(lineCurve,
                               boatIntersectCurveShape,
                               name='%s_flatSurface' % name,
                               constructionHistory=True,
                               range=False,
                               polygon=0,
                               useComponentPivot=1,
                               fixedPath=True,
                               useProfileNormal=True,
                               extrudeType=2,
                               reverseSurfaceIfPathReversed=True)[0]
    cmds.rebuildSurface(flatSurface,
                        constructionHistory=True,
                        replaceOriginal=True,
                        rebuildType=0,
                        endKnots=1,
                        keepCorners=False,
                        spansU=1,
                        degreeU=1,
                        spansV=100,
                        degreeV=3)

    # Offset upwards curve from surface
    offsetUp = cmds.offsetCurve('%s.u[0.5]' % flatSurface,
                                name='%s_offsetUp' % name,
                                distance=0,
                                constructionHistory=True,
                                range=0,
                                subdivisionDensity=1)[0]
    cmds.rebuildCurve(offsetUp,
                      constructionHistory=False,
                      replaceOriginal=True,
                      end=1,
                      keepRange=0,
                      keepControlPoints=True,
                      degree=1)
    cmds.setAttr('%s.translateY' % offsetUp, 0.01)

    # Offset from upwards curve with distance and translate down to get the 45 degree angle
    offset_distance = -0.01
    offsetOut = cmds.offsetCurve(offsetUp,
                                 name='%s_offsetOut' % name,
                                 distance=offset_distance,
                                 constructionHistory=True,
                                 range=0,
                                 subdivisionDensity=1)[0]
    cmds.setAttr('%s.translateY' % offsetOut, offset_distance)

    # Finally, loft a non-flipping surface solution (45 degree angle of the boat)
    noFlipSurface = cmds.loft(offsetUp,
                              offsetOut,
                              degree=1,
                              constructionHistory=True,
                              range=0,
                              polygon=0,
                              sectionSpans=1)[0]
    noFlipSurface = cmds.rename(noFlipSurface, '%s_noFlipSurface' % name)

    ## Build the emitter
    emitter = cmds.emitter(noFlipSurface,
                           name='%s_emitter' % name,
                           type='surface')

    # Create closestPointOnSurface for acceleration expression where front more acceleration
    cPoS = cmds.createNode('closestPointOnSurface', name='%s_cPoS' % name)
    cmds.connectAttr('%s.worldSpace' % noFlipSurface, '%s.inputSurface' % cPoS)

    ## Build the emitter group if it doesn't already exist
    emitterGroup = '%s_hrc' % name
    if not cmds.objExists(emitterGroup):
        cmds.group(lineCurve,
                   flatSurface,
                   offsetUp,
                   offsetOut,
                   noFlipSurface,
                   emitter[0],
                   n=emitterGroup)
    debug(None,
          method='_buildSideSplashEmitter',
          message='emitterName: %s' % emitter[1],
          verbose=False)

    ## Check if a custom preset has been assigned via the func flags for the emitter, if not use the default preset...
    if presetName:
        pathToPreset = '%s/%s' % (CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None,
              method='_buildSideSplashEmitter',
              message='pathToPreset: %s' % pathToPreset,
              verbose=False)
        mel.eval('applyPresetToNode "%s" "" "" "%s" 1;' %
                 (emitter[1], pathToPreset))

    ## Now parent it
    try:
        cmds.parent(emitterGroup, 'nPARTICLE_EMITTERS_hrc')
    except:
        pass

    ## Connect the emitter to the particles
    debug(None,
          method='_buildSideSplashEmitter',
          message='Connected %s: %s' % (splashParticleName, emitter[1]),
          verbose=False)
    for each in splashParticleName:
        _connect_NParticleShape_to_NParticleEmitter(particleShapeNode=each,
                                                    emitter=emitter[1])

    ## Now do the expression for the side emitter
    if 'IntersectCurveRight' in emitter[1]:
        direction = 'R'
    else:
        direction = 'L'

    expStringList = [
        'float $minSpeed = %s.minSpeed;\n' % sideAnimatable,
        'float $maxSpeed = %s.maxSpeed;\n' % sideAnimatable,
        'float $speed = %s:world_ctrl.speed;\n' % boatName,
        'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
        'float $rateMuliplier = %s.rateMultiplier%s;\n' %
        (sideAnimatable, direction),
        'float $splashMaxSpeed = %s.splashMaxSpeed%s;\n' %
        (sideAnimatable, direction),
        '\n',
        'if (%s.useSpeed == 1)\n' % sideAnimatable,
        '{\n\t',
        '%s.rate = $rateMuliplier * $curve;\n' % emitter[1],
        '\n\t\t',
        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
        'if ($emitterSpeed == 0)\n\t\t',
        '{\n\t\t\t',
        '$emitterSpeed = 0.1;\n\t\t',
        '}\n\t\t',
        '%s.speed = $emitterSpeed;\n' % emitter[1],
        '}\n',
        'else\n',
        '{\n\t',
        '%s.rate = $rateMuliplier;\n\t' % emitter[1],
        '%s.speed = $splashMaxSpeed;\n' % emitter[1],
        '}\n',
    ]
    ## Check if the expression already exists in the scene, if so delete it
    utils.checkExpressionExists('%s_sideSplashEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[1],
                    n='%s_sideSplashEmitter' % emitter[1],
                    string=utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.normalSpeed%s' % (sideAnimatable, direction),
                            '%s.normalSpeed' % emitter[1]):
        cmds.connectAttr('%s.normalSpeed%s' % (sideAnimatable, direction),
                         '%s.normalSpeed' % emitter[1])
    if not cmds.isConnected('%s.randomSpeed%s' % (sideAnimatable, direction),
                            '%s.speedRandom' % emitter[1]):
        cmds.connectAttr('%s.randomSpeed%s' % (sideAnimatable, direction),
                         '%s.speedRandom' % emitter[1])

    return cPoS
예제 #31
0
def _buildSideSplashEmitter(name = '', boatName = '', splashParticleName = [], boatIntersectCurveShape = '', sideAnimatable = '', presetName = None):
    """
    New builder for sideSplash nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: List of the names of nParticleShape nodes to connect to the emitter
    @param boatIntersectCurveShape: The name of the intersection curve to emit from.
    @type name:  String
    @type splashParticleName: List
    @type boatIntersectCurveShape: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n = 'nPARTICLE_EMITTERS_hrc', em = True)

    debug(None, method = '_buildSideSplashEmitter', message = 'name: %s' % name, verbose = False)

    # Get base flat surface
    lineCurve       = cmds.curve( name = '%s_extrudeCurve' % name, degree = 1, point = [(-0.01, 0, 0), (0.01, 0, 0)] )
    flatSurface  = cmds.extrude(lineCurve, boatIntersectCurveShape, name = '%s_flatSurface' % name, constructionHistory = True, range = False, polygon = 0, useComponentPivot = 1, fixedPath = True, useProfileNormal = True, extrudeType = 2, reverseSurfaceIfPathReversed = True)[0]
    cmds.rebuildSurface(flatSurface, constructionHistory = True, replaceOriginal = True, rebuildType = 0, endKnots = 1, keepCorners = False, spansU = 1, degreeU = 1, spansV = 100, degreeV = 3)

    # Offset upwards curve from surface
    offsetUp = cmds.offsetCurve('%s.u[0.5]' % flatSurface, name = '%s_offsetUp' % name, distance = 0, constructionHistory = True, range = 0, subdivisionDensity = 1)[0]
    cmds.rebuildCurve(offsetUp, constructionHistory = False, replaceOriginal = True, end = 1, keepRange = 0, keepControlPoints = True, degree = 1)
    cmds.setAttr('%s.translateY' % offsetUp, 0.01)

    # Offset from upwards curve with distance and translate down to get the 45 degree angle
    offset_distance = -0.01
    offsetOut = cmds.offsetCurve(offsetUp, name = '%s_offsetOut' % name, distance = offset_distance, constructionHistory = True, range = 0, subdivisionDensity = 1)[0]
    cmds.setAttr('%s.translateY' % offsetOut, offset_distance)

    # Finally, loft a non-flipping surface solution (45 degree angle of the boat)
    noFlipSurface = cmds.loft(offsetUp, offsetOut, degree = 1, constructionHistory = True, range = 0, polygon = 0, sectionSpans = 1)[0]
    noFlipSurface = cmds.rename(noFlipSurface, '%s_noFlipSurface' % name)

    ## Build the emitter
    emitter = cmds.emitter(noFlipSurface, name = '%s_emitter' % name, type = 'surface')

    # Create closestPointOnSurface for acceleration expression where front more acceleration
    cPoS = cmds.createNode('closestPointOnSurface', name = '%s_cPoS' % name)
    cmds.connectAttr('%s.worldSpace' % noFlipSurface, '%s.inputSurface' % cPoS)

    ## Build the emitter group if it doesn't already exist
    emitterGroup = '%s_hrc' % name
    if not cmds.objExists(emitterGroup):
        cmds.group(lineCurve, flatSurface, offsetUp, offsetOut, noFlipSurface, emitter[0], n = emitterGroup)
    debug(None, method = '_buildSideSplashEmitter', message = 'emitterName: %s' % emitter[1], verbose = False)

    ## Check if a custom preset has been assigned via the func flags for the emitter, if not use the default preset...
    if presetName:
        pathToPreset = '%s/%s' %(CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None, method = '_buildSideSplashEmitter', message = 'pathToPreset: %s' % pathToPreset, verbose = False)
        mel.eval( 'applyPresetToNode "%s" "" "" "%s" 1;' %(emitter[1], pathToPreset) )

    ## Now parent it
    try:    cmds.parent(emitterGroup, 'nPARTICLE_EMITTERS_hrc')
    except: pass

    ## Connect the emitter to the particles
    debug(None, method = '_buildSideSplashEmitter', message = 'Connected %s: %s' % (splashParticleName, emitter[1]), verbose = False)
    for each in splashParticleName:
        _connect_NParticleShape_to_NParticleEmitter(particleShapeNode = each, emitter = emitter[1])

    ## Now do the expression for the side emitter
    if 'IntersectCurveRight' in emitter[1]:
        direction = 'R'
    else:
        direction = 'L'

    expStringList = [
                    'float $minSpeed = %s.minSpeed;\n' % sideAnimatable,
                    'float $maxSpeed = %s.maxSpeed;\n' % sideAnimatable,
                    'float $speed = %s:world_ctrl.speed;\n' % boatName,
                    'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
                    'float $rateMuliplier = %s.rateMultiplier%s;\n' %(sideAnimatable, direction),
                    'float $splashMaxSpeed = %s.splashMaxSpeed%s;\n' %(sideAnimatable, direction),
                    '\n',
                    'if (%s.useSpeed == 1)\n' % sideAnimatable,
                    '{\n\t',
                        '%s.rate = $rateMuliplier * $curve;\n' % emitter[1],
                        '\n\t\t',
                        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
                        'if ($emitterSpeed == 0)\n\t\t',
                        '{\n\t\t\t',
                            '$emitterSpeed = 0.1;\n\t\t',
                        '}\n\t\t',
                        '%s.speed = $emitterSpeed;\n' % emitter[1],
                    '}\n',
                    'else\n',
                    '{\n\t',
                        '%s.rate = $rateMuliplier;\n\t' % emitter[1],
                        '%s.speed = $splashMaxSpeed;\n' % emitter[1],
                    '}\n',
                    ]
    ## Check if the expression already exists in the scene, if so delete it
    utils.checkExpressionExists('%s_sideSplashEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[1], n = '%s_sideSplashEmitter' % emitter[1], string = utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.normalSpeed%s' %(sideAnimatable, direction), '%s.normalSpeed' % emitter[1]):
        cmds.connectAttr('%s.normalSpeed%s' %(sideAnimatable, direction), '%s.normalSpeed' % emitter[1])
    if not cmds.isConnected('%s.randomSpeed%s' %(sideAnimatable, direction), '%s.speedRandom' % emitter[1]):
        cmds.connectAttr('%s.randomSpeed%s' %(sideAnimatable, direction), '%s.speedRandom' % emitter[1])

    return cPoS
예제 #32
0
def build(bnd_jnts,
          side='l',
          prefix='leg',
          rig_scale=1.0,
          base_rig=None,
          hip_ctrl=None):
    """
    @param spine_jnts: list(str), list of 6 spine jnts
    @param root_jnt: str, root_jnt
    @param prefix: str, prefix to name new object
    @param rig_scale: float, scale factor for size of controls
    @param base_rig: instance of base.module.Base class
    @return: dictionary with rig module objects 
    """

    #make rig module
    rig_module = module.Module(prefix=side + '_' + prefix,
                               base_obj=base_rig,
                               create_dnt_grp=True,
                               drv_pos_obj='pelvis')

    #create drv skels
    ik_leg_jnts = joint.duplicate(bnd_jnts,
                                  prefix='ik',
                                  maintain_hierarchy=True)
    fk_leg_jnts = joint.duplicate(bnd_jnts,
                                  prefix='fk',
                                  maintain_hierarchy=True)
    cmds.parent(ik_leg_jnts[0], fk_leg_jnts[0], rig_module.drv_grp)
    cmds.parentConstraint(hip_ctrl.ctrl, rig_module.drv_grp, mo=True)

    #create IK controls
    ik_anim_grp = side + '_' + prefix + '_ik_anim_grp'
    cmds.group(n=ik_anim_grp, em=True, p=rig_module.ctrl_grp)

    temp_pole_loc = limbs.create_pole_vector_locator(side + '_' + prefix,
                                                     bnd_jnts[1], [0, -30, 0])
    ik_foot_ctrl = control.Control(shape=side + '_foot_ctrl_template',
                                   prefix=side + '_foot_IK',
                                   translate_to=bnd_jnts[2],
                                   scale=rig_scale,
                                   parent=ik_anim_grp,
                                   lock_channels=['s', 'v'])

    ik_knee_ctrl = control.Control(shape='sphere_ctrl_template',
                                   prefix=side + '_knee_IK',
                                   translate_to=temp_pole_loc,
                                   scale=rig_scale,
                                   parent=ik_anim_grp,
                                   lock_channels=['v'])
    cmds.delete(temp_pole_loc)
    ik_ctrl_list = [ik_foot_ctrl, ik_knee_ctrl]

    #create FK controls
    fk_anim_grp = side + '_' + prefix + '_fk_anim_grp'
    cmds.group(n=fk_anim_grp, em=True, p=rig_module.ctrl_grp)
    #    transform.snap('pelvis', fk_anim_grp)
    transform.snap(hip_ctrl.ctrl, fk_anim_grp)

    fk_thigh_ctrl = control.Control(shape='cube_ctrl_template',
                                    prefix=side + '_thigh_FK',
                                    translate_to=[bnd_jnts[0], bnd_jnts[1]],
                                    rotate_to=bnd_jnts[0],
                                    scale=rig_scale,
                                    parent=fk_anim_grp,
                                    lock_channels=['s', 'v'])
    transform.snap_pivot(bnd_jnts[0], fk_thigh_ctrl.ctrl)
    transform.snap_pivot(bnd_jnts[0], fk_thigh_ctrl.ofst)

    fk_calf_ctrl = control.Control(shape='cube_ctrl_template',
                                   prefix=side + '_calf_FK',
                                   translate_to=[bnd_jnts[1], bnd_jnts[2]],
                                   rotate_to=bnd_jnts[1],
                                   scale=rig_scale * 0.7,
                                   parent=fk_thigh_ctrl.ctrl,
                                   lock_channels=['s', 'v'])
    transform.snap_pivot(bnd_jnts[1], fk_calf_ctrl.ctrl)
    transform.snap_pivot(bnd_jnts[1], fk_calf_ctrl.ofst)

    fk_foot_ctrl = control.Control(shape='cube_ctrl_template',
                                   prefix=side + '_foot_FK',
                                   translate_to=[bnd_jnts[2], bnd_jnts[3]],
                                   rotate_to=bnd_jnts[3],
                                   scale=rig_scale * 0.6,
                                   parent=fk_calf_ctrl.ctrl,
                                   lock_channels=['s', 'v'])
    transform.snap_pivot(bnd_jnts[2], fk_foot_ctrl.ctrl)
    transform.snap_pivot(bnd_jnts[2], fk_foot_ctrl.ofst)

    #hook up FK ctrls
    fk_ctrl_list = [fk_thigh_ctrl, fk_calf_ctrl, fk_foot_ctrl]
    for i in range(len(fk_ctrl_list)):
        cmds.orientConstraint(fk_ctrl_list[i].ctrl, fk_leg_jnts[i], mo=False)

    #set up ik
    leg_ik_handle = cmds.ikHandle(n=side + '_leg_ikHandle',
                                  sj=ik_leg_jnts[0],
                                  ee=ik_leg_jnts[2],
                                  sol='ikRPsolver')[0]
    ball_ik_handle = cmds.ikHandle(n=side + 'ball_ikHandle',
                                   sj=ik_leg_jnts[2],
                                   ee=ik_leg_jnts[3],
                                   sol='ikSCsolver')[0]
    toe_ik_handle = cmds.ikHandle(n=side + 'toe_ikHandle_',
                                  sj=ik_leg_jnts[3],
                                  ee=ik_leg_jnts[4],
                                  sol='ikSCsolver')[0]

    ik_list = [leg_ik_handle, ball_ik_handle, toe_ik_handle]
    cmds.hide(ik_list)
    cmds.parent(ik_list, ik_foot_ctrl.ctrl)
    cmds.poleVectorConstraint(ik_knee_ctrl.ctrl, leg_ik_handle)

    #set up ik/fk switch
    limbs.setup_ikfk_switch(base_rig.ikfk_ctrl, side, prefix, ik_leg_jnts[0:3],
                            fk_leg_jnts[0:3], bnd_jnts[0:3], ik_anim_grp,
                            fk_anim_grp)

    #set up twist joints
    limbs.create_twist_jnts(side + '_' + prefix, bnd_jnts)

    #set up fk space switching
    limbs.setup_fk_space_switching(side + '_' + prefix, fk_anim_grp,
                                   fk_leg_jnts, base_rig.master_ctrl.ctrl,
                                   fk_thigh_ctrl.ofst)
    cmds.parentConstraint(hip_ctrl.ctrl, fk_anim_grp, mo=True)

    #set up limb stretching
    #    limbs.setup_limb_stretch(prefix, rig_module, ik_leg_jnts, ik_ctrl_list)
    limbs.add_ikpop_counter(side + '_' + prefix, ik_leg_jnts, bnd_jnts,
                            ik_foot_ctrl.ctrl)

    #set up ribbon
    ribbon.create_ep_curve('temp_' + prefix + '_ribbon_crv_01',
                           [bnd_jnts[0], bnd_jnts[1], bnd_jnts[2]],
                           degree=1)
    ribbon_sfc = ribbon.loft_using_curve('temp_' + prefix + '_ribbon_crv_01',
                                         10, 'z', side + '_' + prefix)

    cmds.rebuildSurface(ribbon_sfc, su=0, sv=11, du=1, dv=3, ch=True)
    limb_foll_list = ribbon.add_follicles(ribbon_sfc,
                                          11,
                                          on_edges=False,
                                          create_joints=True)
    limb_foll_jnts_list = limb_foll_list[1]
    limb_foll_list = limb_foll_list[0]

    for jnt in limb_foll_jnts_list:
        cmds.xform(jnt, os=True, ro=[-90, 0, 90])
        cmds.makeIdentity(jnt, t=0, r=1, s=0, apply=True)

    limb_follicles_grp = '_'.join([side, prefix, 'follicles', 'grp'])
    cmds.group(limb_foll_list, n=limb_follicles_grp)

    #set up blendshapes
    leg_drv_jnts = [
        u'thigh_l', u'calf_l', u'ankle_l', u'calf_l_twist', u'thigh_l_twist'
    ]
    cmds.select(leg_drv_jnts, ribbon_sfc)
    limb_ribbon_clstr = cmds.skinCluster(tsb=True, dr=4.5)

    shape = cmds.listRelatives(ribbon_sfc, shapes=True)[0]
    #'body_geo' must have a skinCluster associated with it.
    geo_skin_clstr = cmds.listConnections(shape, type='skinCluster')[0]

    limbs.create_deformer_blend(side + '_' + prefix,
                                ribbon_sfc,
                                geo_skin_clstr,
                                ik_foot_ctrl.ctrl,
                                limb_foll_jnts_list,
                                num_jnts=3)
예제 #33
0
def SK_FollicleControl(cons,multiple = 3,SV = 1,conPrefix = 'Lf_eyeBrow',nurbsMesh = 'Lf_eyeBrow_Loft',FaceFolScale = 'Face_Sclale_Grp'):
#    nurbsMesh  nurbs名字
#    conPrefix   控制器名字
#    FaceFolScale  毛囊缩放组
#    multiple    次级毛囊缩放组
#     SV          缩放值
    TR = 0.1*SV
    conSize = 1*SV
    tempCurves = []
    FOLs = []
    NewCons = [] #生成的新的控制器
    MainJnts = [] #主控蒙皮骨骼
    SeJnts = []   #次控蒙皮骨骼
    MainController = CreateControler(13,(conSize*0.1,conSize*0.1,conSize*0.1))
    
    #创建曲线上传Nurbs片
    for con in cons:
        emptyGrp = rig.group(n = con+'_EM_GRP',empty = True)
        rig.parent(emptyGrp,con)
        rig.xform(emptyGrp,ro = (0,0,0.0),wd = True)
        rig.xform(emptyGrp,t = (0,0,0.0),wd = True)
        Mpos = rig.xform(emptyGrp,q = True,t = True,ws = True) 
        rig.xform(emptyGrp,t = (0,0,TR),wd = True)
        Fpos = rig.xform(emptyGrp,q = True,t = True,ws = True)  
        rig.xform(emptyGrp,t = (0,0,-TR),wd = True)
        Bpos = rig.xform(emptyGrp,q = True,t = True,ws = True)       
        
        curs = rig.curve(d = 2,p = [Fpos,Mpos,Bpos])
        tempCurves.append(curs)
        rig.delete(emptyGrp)
    
    loftNurbs = rig.loft(tempCurves)[0]
    rig.rebuildSurface(loftNurbs,rpo  = 1,rt = 0,end = 1,kr = 0,su = len(cons)*2,du = 3,sv = 0,dv = 3,tol = 0.001,fr = 0,dir = 2,ch = True)
#    rig.rebuildSurface(loftNurbs,rt = 1,kr = 0,ch = True)
    mainMesh = rig.duplicate(loftNurbs,n = nurbsMesh)[0]
    SCMesh = rig.duplicate(mainMesh,n = mainMesh+'_SC')[0]
    rig.hide(mainMesh,SCMesh)
    rig.delete(loftNurbs,tempCurves)
    
    
    #在主nurbs片上生成毛囊
    MainMeshShape = rig.listRelatives(mainMesh,s = True)[0]
    CPO = rig.createNode('closestPointOnSurface',n = mainMesh+'_CPO',ss = True)
    rig.connectAttr(MainMeshShape+'.worldSpace[0]',CPO+'.inputSurface')
    for i,con in enumerate(cons):
        pos = rig.xform(con,q = True,t = True,ws = True)
        rig.setAttr(CPO+'.inPositionX',pos[0])
        rig.setAttr(CPO+'.inPositionY',pos[1])
        rig.setAttr(CPO+'.inPositionZ',pos[2])
        U = rig.getAttr(CPO+'.parameterU')
        V = rig.getAttr(CPO+'.parameterV')
    
        FOLShape = rig.createNode('follicle',n = con+'_EB_FOLShape',ss = True)
        rig.connectAttr(MainMeshShape+'.worldSpace[0]',FOLShape+'.inputSurface')
        FOL = rig.listRelatives(FOLShape,p = True)[0]
        rig.connectAttr(FaceFolScale+'.scale',FOL+'.scale')
        newFol = rig.rename(FOL,con+'_EB_FOL')
        rig.connectAttr(FOLShape+'.outTranslate',newFol+'.translate')
        rig.connectAttr(FOLShape+'.outRotate',newFol+'.rotate')
        rig.setAttr(FOLShape+'.parameterU',U)
        rig.setAttr(FOLShape+'.parameterV',V)
        rig.setAttr(FOLShape+'.simulationMethod',0)
        
    #    生成控制器,完成主要控设置。
        Mcon = MainController.SK_b05(conPrefix+'_'+str(i+1)+'_M') 
        rig.parent(Mcon,con)
        rig.xform(Mcon,ro = (-90,0,0),wd = True)   
        rig.xform(Mcon,t = (0,0,0),wd = True)
        rig.setAttr(Mcon+'.sy',-0.5)
        rig.makeIdentity(Mcon,apply = True,s = True,r = True)
        MconGrp = rig.group(Mcon,n = Mcon+'Grp',r = True)
        rig.parent(MconGrp,FOL)
        JNT = rig.joint(n = Mcon+'_JNT')
        rig.xform(JNT,t = pos,ws = True)
        rig.parent(JNT,Mcon)
        
        rig.hide(FOLShape,JNT)
        NewCons.append(Mcon)
        FOLs.append(FOL)
        MainJnts.append(JNT)
    rig.skinCluster(MainJnts,SCMesh)    
        
    #在次nurbs片上生成毛囊
    
    SCMeshShape = rig.listRelatives(SCMesh,s = True)[0]
    CPO = rig.createNode('closestPointOnSurface',n = SCMesh+'_CPO',ss = True)
    rig.connectAttr(SCMeshShape+'.worldSpace[0]',CPO+'.inputSurface')
    
    IterFol = len(cons)*multiple
    addPos = 1.0/IterFol
    dvUV = 0.0
    for con in range(IterFol+1):
        V = 0.5
        FOLShape = rig.createNode('follicle',n = SCMesh+'_'+str(con)+'_SC_FOLShape',ss = True)
        rig.connectAttr(SCMeshShape+'.worldSpace[0]',FOLShape+'.inputSurface')
        FOL = rig.listRelatives(FOLShape,p = True)[0]
        rig.connectAttr(FaceFolScale+'.scale',FOL+'.scale')
        newFol = rig.rename(FOL,SCMesh+'_'+str(con)+'_SC_FOL')
        rig.connectAttr(FOLShape+'.outTranslate',newFol+'.translate')
        rig.connectAttr(FOLShape+'.outRotate',newFol+'.rotate')
        rig.setAttr(FOLShape+'.parameterU',dvUV)
        rig.setAttr(FOLShape+'.parameterV',V)
        rig.setAttr(FOLShape+'.simulationMethod',0)  
        
        dvUV += addPos
        
        JNT = rig.joint(n = conPrefix+'_'+str(con+1)+'_SC_JNT')
        pos = rig.xform(FOL,q = True,t = True,ws = True)
        rig.xform(JNT,t = pos,ws = True)
        rig.parent(JNT,FOL)
        
        rig.hide(FOLShape,JNT)
        FOLs.append(FOL)
        SeJnts.append(JNT)
    AllGrp = rig.group(mainMesh,SCMesh,FOLs,n = nurbsMesh+'_DEF_GRP') 
    
    
    return mainMesh,SeJnts,AllGrp,NewCons
예제 #34
0
    def rigFromCurve(self,crv,numSpans=8,numJoints=10,numCtrls=5,stripWidth = 1.0,ctrlWidth=2.0,geo=None,uMin=0.0,uMax=1.0):
        '''make a cable rig from the given curve
            numSpans = number of spans in Nurbs strip
            numJoints = number of joints riding on nurbs strip
            numCtrls = number of controls to make  
            stripWidth = width of nurbs strip (can make it easier to paint weights if wider) 
            ctrlWidth = size of ctrls 
        '''
    
        shapes = cmds.listRelatives(crv,s=1)
        crvShape = shapes[0]
        #Make rig top nulls to parent stuff under
        topNull = cmds.createNode('transform',n=crv + "_Rig")
        hiddenStuff = cmds.createNode('transform',n=crv + "_NOTOUCH",p=topNull)
        cmds.setAttr(hiddenStuff + ".inheritsTransform", 0)
        cmds.setAttr(hiddenStuff + ".visibility", 0)
        cmds.addAttr(topNull, ln="stretchAmount",dv=1.0,min=0,max=1)
        cmds.addAttr(topNull, ln='slideAmount',dv=0.0)

        #make nurbs strip using extrude
        crossCurve = cmds.curve(d=1,p=[(0,0,-0.5 * stripWidth),(0,0,0.5 * stripWidth)],k=(0,1))
        cmds.select([crossCurve,crv],r=1)
        surf = cmds.extrude(ch=False,po=0,et=2,ucp=1,fpt=1,upn=1,rotation=0,scale=1,rsp=1)[0]
        cmds.delete(crossCurve)
        surf = cmds.rename(surf, crv + "_driverSurf")
        cmds.parent(surf,hiddenStuff)

        #Rebuild strip to proper number of spans
        cmds.rebuildSurface(surf,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=0,kc=1,sv=numSpans,su=0,du=1,tol=0.01,fr=0,dir=2)

        #make live curve on surface down the middle 
        #this is used later for noStretch
        curvMaker = cmds.createNode('curveFromSurfaceIso', n = surf+"CurveIso")
        cmds.setAttr(curvMaker + ".isoparmValue", 0.5)
        cmds.setAttr(curvMaker + ".isoparmDirection", 1)
        cmds.connectAttr(surf + ".worldSpace[0]", curvMaker + ".inputSurface")

        offsetCrvShp = cmds.createNode("nurbsCurve", n=crv + "_driverSurfCrvShape")
        offsetCrv = cmds.listRelatives(p=1)[0]
        offsetCrv = cmds.rename(offsetCrv,crv + "_driverSurfCrv")
        cmds.connectAttr(curvMaker + ".outputCurve", offsetCrvShp + ".create")
        cmds.parent(offsetCrv, hiddenStuff)
    
        #Measure curve length and divide by start length. 
        #This turns curve length into a normalized value that is
        #useful for multiplying by UV values later to control stretch
        crvInfo = cmds.createNode('curveInfo', n=offsetCrv + "Info")
        cmds.connectAttr(offsetCrv + ".worldSpace[0]", crvInfo + ".ic")
        arcLength = cmds.getAttr(crvInfo + ".al")
        stretchAmountNode = cmds.createNode('multiplyDivide', n=offsetCrv + "Stretch")
        cmds.setAttr(stretchAmountNode + ".op" , 2) #divide
        cmds.setAttr(stretchAmountNode + ".input1X", arcLength)
        cmds.connectAttr( crvInfo + ".al",stretchAmountNode + ".input2X")
    
        #Stretch Blender blends start length with current length
        #and pipes it back into stretchAmoundNode's startLength, to "trick" it into
        #thinking there is no stretch..
        #That way, when user turns on this "noStretch" attr, the startLength will
        #be made to equal current length, and stretchAmountNode will always be 1.
        #so the chain will not stretch. 
        stretchBlender = cmds.createNode('blendColors', n =offsetCrv + "StretchBlender")
        cmds.setAttr(stretchBlender + ".c1r", arcLength)
        cmds.connectAttr(crvInfo + ".al", stretchBlender + ".c2r")
        cmds.connectAttr(stretchBlender + ".opr", stretchAmountNode + ".input1X")
        cmds.connectAttr(topNull + ".stretchAmount",stretchBlender + ".blender")
    
        #make skin joints and attach to surface
        skinJoints = []
        skinJointParent = cmds.createNode('transform',n=crv + "_skinJoints",p=topNull)
        for i in range(numJoints):
            cmds.select(clear=True)
            jnt = cmds.joint(p=(0,0,0),n=crv + "_driverJoint%02d"%i) 
            locator = cmds.spaceLocator(n=crv + "driverLoc%02d"%i)[0]
            cmds.setAttr(locator + ".localScale",stripWidth,stripWidth,stripWidth)
            cmds.parent(locator,hiddenStuff)
            percentage = float(i)/(numJoints-1.0)
            print "percentage:", percentage
            print i
            if i > 1 and i < numJoints-2:
                percentage = uMin + (percentage * (uMax-uMin))
                print "\tinterp percent", percentage
            posNode,aimCnss,moPath,slider = self.attachObjToSurf(locator,surf,offsetCrv,stretchAmountNode,percentage)
            cmds.connectAttr(topNull + ".slideAmount", slider + ".i2")
            cmds.parentConstraint(locator,jnt,mo=False)
            if len(skinJoints):
                cmds.parent(jnt,skinJoints[-1])
            else:
                cmds.parent(jnt,skinJointParent)
            skinJoints.append(jnt)
            cmds.setAttr(jnt + ".radius",stripWidth) #just cosmetic
        
        #add controls
        ctrls = []
        stripJoints = []
        stripJointParent = cmds.createNode('transform',n=crv + "_stripJoints",p=hiddenStuff)
        ctrlParent = cmds.createNode('transform',n=crv+"_Ctrls",p=topNull)
    
        for i in range(numCtrls):
            #The first control is larger, and has the stretch attr
            if i == 0:
                zero,ctrl = self.makeCubeCtrl(crv + "_Ctrl%02d"%i,size=ctrlWidth*1.8)
                cmds.addAttr(ctrl,ln="noStretch",dv=0.0,min=0,max=1,k=1,s=1)
                cmds.addAttr(ctrl,ln='slideAmount',dv=0.0,min=-1.0,max=1.0,k=1,s=1)
                cmds.connectAttr(ctrl + ".noStretch",topNull + ".stretchAmount")
                cmds.connectAttr(ctrl + ".slideAmount",topNull + ".slideAmount")
            else:
                zero,ctrl = self.makeCubeCtrl(crv + "_Ctrl%02d"%i,size=ctrlWidth)
            
            #Make the joint the control. These drive the nurbs strip.
            cmds.select(clear=True)
            jnt = cmds.joint(p=(0,0,0),n=ctrl + "StripJnt")
            cmds.parentConstraint(ctrl,jnt,mo=False)
            cmds.setAttr(jnt + ".radius", stripWidth * 1.3) #just cosmetic
        
            #briefly attach ctrls to strip to align them
            percentage = float(i)/(numCtrls-1.0)
            print "ctrl percentage:",percentage
            if i > 0 and i < numCtrls-1:
                percentage = uMin + (percentage * (uMax-uMin))
                print '\tinterp percentage:', percentage
            cmds.delete(self.attachObjToSurf(zero,surf,offsetCrv,stretchAmountNode,percentage))
            ctrls.append(ctrl)
            cmds.parent(jnt,stripJointParent)
            stripJoints.append(jnt)
            cmds.parent(zero,ctrlParent)
        
        #skin strip to controls
        #Can get some different behavior by chaning the strip's weights
        #or perhaps using dual quat. mode on the skinCluster
        skinObjs = stripJoints + [surf]
        cmds.skinCluster(skinObjs,
            bindMethod=0, #closest Point
            sm=0, #standard bind method
            ih=True, #ignore hierarchy
        )    
        
        #rebuild curve and skin to joints
        newCurve = cmds.duplicate(crv)[0]
        newCurve = cmds.rename(newCurve, crv + "_skinned")
        cmds.parent(newCurve, topNull)
        cmds.rebuildCurve(newCurve,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=numJoints-2,d=3,tol=0.01)
        skinObjs = skinJoints + [newCurve]
        cmds.skinCluster(skinObjs,
            bindMethod = 0,
            sm = 0,
            ih=True,
            mi=1
            )
        if geo:
            wireDef,wireCrv = cmds.wire(geo,w=newCurve,n=crv + "_wire",dds=(0,10),en=1.0,ce=0,li=0)
            print wireDef
            cmds.parent(wireCrv,hiddenStuff)
            if cmds.objExists(wireCrv+"BaseWire"):
                cmds.parent(wireCrv+"BaseWire",hiddenStuff)
예제 #35
0
def build_spine(*args):
    nurbsProperties = []
    #build your curve based on the joints pos
    if cmds.objExists("curve1"):
        originalCrv = cmds.rename("curve1", "originalCrv")
        duplicatedCrv = cmds.duplicate(originalCrv, n="duplicatedCrv")
        cmds.xform(originalCrv, r=True, t=(-1, 0, 0))
        cmds.xform(duplicatedCrv, r=True, t=(0, 0, 0))  #the joints lie here
        loftName = cmds.loft(duplicatedCrv,
                             originalCrv,
                             ch=1,
                             u=1,
                             c=0,
                             ar=1,
                             d=3,
                             ss=1,
                             rn=0,
                             po=0,
                             rsn=True,
                             n="originalSurface")

        originalCrvNumber = countCVS(originalCrv)
        select_cvs = originalCrvNumber[0] - 1

        cmds.select(loftName[0] + ".cv[0:" + str(select_cvs) + "][0]")
        mel.eval('createHair 8 8 2 0 0 0 0 5 0 1 2 2;')
        cmds.delete('hairSystem1', 'pfxHair1', 'nucleus1')
        follicle_grp = cmds.rename('hairSystem1Follicles',
                                   'spine_follicles_grp')

        folName = 'spine_follicle'
        folList = cmds.ls(loftName[0] + 'Follicle*', transforms=True)
        for i in folList:
            cmds.rename(i, folName)

        folList = cmds.listRelatives(follicle_grp)
        crvList = cmds.ls('curve*', transforms=True)
        cmds.select(crvList, replace=True)
        cmds.delete(crvList)

        jntList = []
        jntGroup = []
        for i in range(0, originalCrvNumber[0] - 2):
            cmds.joint(n="ribbon_jnt" + str(i), p=(0, 0, 0), rad=1)
            cmds.group("ribbon_jnt" + str(i), n="ribbon_jnt_grp" + str(i))
            jntList.append("ribbon_jnt" + str(i))
            cmds.select(clear=True)
            jntGroup.append("ribbon_jnt_grp" + str(i))

        for i, j in zip(jntGroup, folList):
            cmds.parent(i, j)

        for i in jntGroup:
            cmds.setAttr(i + ".translateX", 0)
            cmds.setAttr(i + ".translateY", 0)
            cmds.setAttr(i + ".translateZ", 0)

        #redo the nurbsSurface
        loftName2 = cmds.duplicate(loftName, n="duplicatedSurface")
        set_su = 8  #user input 15
        set_sv = 1  #preferrably one no user input
        cmds.rebuildSurface(loftName2,
                            rpo=1,
                            rt=0,
                            end=1,
                            kr=0,
                            kcp=0,
                            kc=0,
                            su=set_su,
                            du=3,
                            sv=set_sv,
                            dv=1,
                            tol=12,
                            fr=0,
                            dir=2)

        # connect the created joints to the loftName2
        cmds.connectAttr(loftName2[0] + "Shape.local",
                         folName + "Shape.inputSurface",
                         force=True)
        cmds.connectAttr(loftName2[0] + "Shape.parentInverseMatrix[0]",
                         folName + "Shape.inputWorldMatrix",
                         force=True)
        for i in range(1, originalCrvNumber[0]):
            cmds.connectAttr(loftName2[0] + "Shape.local",
                             folName + "Shape" + str(i) + ".inputSurface",
                             force=True)
            cmds.connectAttr(loftName2[0] + "Shape.parentInverseMatrix[0]",
                             folName + "Shape" + str(i) + ".inputWorldMatrix",
                             force=True)

        #create clusters
        duplicatedCrvNumber = countCVS(loftName2[0])
        rib_clusterList = []
        for i in range(0, duplicatedCrvNumber[0] - 2):
            clusterName = cmds.cluster(loftName2[0] + ".cv[" + str(i) +
                                       "][0:1]",
                                       n="rib_clu_" + str(i))
            rib_clusterList.append(clusterName)

        rib_clusterList = cmds.ls('rib_clu_*', transforms=True)
        cmds.group(rib_clusterList, n="ribbon_clusterGrp")

        rib_clu_ctrlList = []
        for i in rib_clusterList:
            rib_clu_ctrlList.append(create_ctrl(str(i) + "_ctrl", i, 2, 5))

        cmds.group(rib_clu_ctrlList, n="rib_cluCtrlGrp")
        hide_obj("originalSurface", "duplicatedCrv", "originalCrv")

        ik_jnts = []
        fk_jnts = []
        res_jnts = []
        all_jnts = [jntList, ik_jnts, fk_jnts, res_jnts]

        for j in range(0, len(all_jnts[0])):
            cmds.duplicate(all_jnts[0][j], n="IK_jnt" + str(j), rr=True)
            ik_jnts.append("IK_jnt" + str(j))

            cmds.duplicate(all_jnts[0][j], n="FK_jnt" + str(j), rr=True)
            fk_jnts.append("FK_jnt" + str(j))

            cmds.duplicate(all_jnts[0][j], n="RES_jnt" + str(j), rr=True)
            res_jnts.append("RES_jnt" + str(j))

        for x, y, z in zip(all_jnts[1], all_jnts[2], all_jnts[3]):
            cmds.parent(x, y, z, world=True)

        a = len(jntList) - 1
        while (a > 0):
            for b in [all_jnts[1], all_jnts[2], all_jnts[3]]:
                cmds.parent(b[a], b[a - 1])
            a = a - 1

        return all_jnts, rib_clusterList, rib_clu_ctrlList, jntGroup, duplicatedCrv
    else:
        print("create a curve1 first")
        return None
예제 #36
0
def createRibbon(axis=(0, 0, 1),
                 name='xxxx',
                 horizontal=False,
                 numJoints=3,
                 guias=None,
                 v=True,
                 s=0,
                 firstLimb=True,
                 upCtrl=None,
                 ctrlRadius=1,
                 worldRef="worldRef"):
    retDict = {}

    #define variables
    top_Loc = []
    mid_Loc = []
    bttm_Loc = []
    rb_Jnt = []
    drv_Jnt = []
    fols = []
    aux_Jnt = []
    ribbon = ''
    extraCtrlList = []

    #define attributes
    limbManualVVAttr = "limbManualVolume"
    limbVVAttr = "limbVolumeVariation"
    limbMinVVAttr = "limbMinVolume"

    #create a nurbsPlane based in the choose orientation option
    if horizontal:
        ribbon = cmds.nurbsPlane(ax=axis,
                                 w=numJoints,
                                 lr=(1 / float(numJoints)),
                                 d=3,
                                 u=numJoints,
                                 v=1,
                                 ch=0,
                                 name=name + '_Plane')[0]
        cmds.rebuildSurface(ribbon,
                            ch=0,
                            rpo=1,
                            rt=0,
                            end=1,
                            kr=0,
                            kcp=0,
                            kc=0,
                            sv=1,
                            du=3,
                            dv=1,
                            tol=0.01,
                            fr=0,
                            dir=1)
    else:
        ribbon = cmds.nurbsPlane(ax=axis,
                                 w=1,
                                 lr=numJoints,
                                 d=3,
                                 u=1,
                                 v=numJoints,
                                 ch=0,
                                 name=name + '_Plane')[0]
        cmds.rebuildSurface(ribbon,
                            ch=0,
                            rpo=1,
                            rt=0,
                            end=1,
                            kr=0,
                            kcp=0,
                            kc=0,
                            su=1,
                            du=1,
                            dv=3,
                            tol=0.01,
                            fr=0,
                            dir=0)
    # make this ribbonNurbsPlane as not skinable from dpAR_UI:
    cmds.addAttr(ribbon,
                 longName="doNotSkinIt",
                 attributeType="bool",
                 keyable=True)
    cmds.setAttr(ribbon + ".doNotSkinIt", 1)
    #call the function to create follicles and joint in the nurbsPlane
    results = createFollicles(rib=ribbon,
                              num=numJoints,
                              name=name,
                              horizontal=horizontal)
    rb_Jnt = results[0]
    fols = results[1]
    #create locator controls for the middle of the ribbon
    mid_Loc.append(cmds.spaceLocator(name=name + '_Mid_Pos_Loc')[0])
    mid_Loc.append(cmds.spaceLocator(name=name + '_Mid_Aim_Loc')[0])
    mid_Loc.append(cmds.spaceLocator(name=name + '_Mid_Off_Loc')[0])
    mid_Loc.append(cmds.spaceLocator(name=name + '_Mid_Up_Loc')[0])
    #parent correctly the middle locators
    cmds.parent(mid_Loc[2], mid_Loc[1], relative=True)
    cmds.parent(mid_Loc[1], mid_Loc[0], relative=True)
    cmds.parent(mid_Loc[3], mid_Loc[0], relative=True)
    #create the locators controls for the top of the ribbon
    top_Loc.append(cmds.spaceLocator(name=name + '_Top_Pos_Loc')[0])
    top_Loc.append(cmds.spaceLocator(name=name + '_Top_Aim_Loc')[0])
    top_Loc.append(cmds.spaceLocator(name=name + '_Top_Up_Loc')[0])
    #parent correctly the top locators
    cmds.parent(top_Loc[1], top_Loc[0], relative=True)
    cmds.parent(top_Loc[2], top_Loc[0], relative=True)
    #create the locators for the end of the ribbon
    bttm_Loc.append(cmds.spaceLocator(name=name + '_Bttm_Pos_Loc')[0])
    bttm_Loc.append(cmds.spaceLocator(name=name + '_Bttm_Aim_Loc')[0])
    bttm_Loc.append(cmds.spaceLocator(name=name + '_Bttm_Up_Loc')[0])
    #parent correctly the bottom locators
    cmds.parent(bttm_Loc[1], bttm_Loc[0], relative=True)
    cmds.parent(bttm_Loc[2], bttm_Loc[0], relative=True)

    #put the top locators in the same place of the top joint
    cmds.parent(top_Loc[0], fols[len(fols) - 1], relative=True)
    cmds.parent(top_Loc[0], w=True)

    #put the bottom locators in the same place of the bottom joint
    cmds.parent(bttm_Loc[0], fols[0], relative=True)
    cmds.parent(bttm_Loc[0], w=True)
    cmds.select(clear=True)

    #create the joints that will be used to control the ribbon
    drv_Jnt = cmds.duplicate(
        [rb_Jnt[0], rb_Jnt[(len(rb_Jnt) - 1) / 2], rb_Jnt[len(rb_Jnt) - 1]])
    dup = cmds.duplicate([drv_Jnt[0], drv_Jnt[2]])
    drv_Jnt.append(dup[0])
    drv_Jnt.append(dup[1])
    #cmds.parent(drv_Jnt, w=True)
    for jnt in drv_Jnt:
        cmds.joint(jnt, e=True, oj='none', ch=True, zso=True)
        cmds.setAttr(jnt + '.radius', cmds.getAttr(jnt + '.radius') + 0.5)
    #rename created joints
    drv_Jnt[0] = cmds.rename(drv_Jnt[0], name + '_Drv_Bttm_Jxt')
    drv_Jnt[1] = cmds.rename(drv_Jnt[1], name + '_Drv_Mid_Jxt')
    drv_Jnt[2] = cmds.rename(drv_Jnt[2], name + '_Drv_Top_Jxt')
    drv_Jnt[3] = cmds.rename(drv_Jnt[3], name + '_Drv_Bttm_End')
    drv_Jnt[4] = cmds.rename(drv_Jnt[4], name + '_Drv_Top_End')

    #place joints correctly accordaly with the user options choose
    if (horizontal and axis == (1, 0, 0)) or (horizontal
                                              and axis == (0, 0, 1)):
        cmds.setAttr(bttm_Loc[2] + '.translateY', 2)
        cmds.setAttr(top_Loc[2] + '.translateY', 2)
        cmds.setAttr(mid_Loc[3] + '.translateY', 2)
    elif (horizontal and axis == (0, 1, 0)) or (not horizontal
                                                and axis == (1, 0, 0)):
        cmds.setAttr(bttm_Loc[2] + '.translateZ', 2)
        cmds.setAttr(top_Loc[2] + '.translateZ', 2)
        cmds.setAttr(mid_Loc[3] + '.translateZ', 2)
    elif not horizontal and axis == (0, 1, 0) or (not horizontal
                                                  and axis == (0, 0, 1)):
        cmds.setAttr(bttm_Loc[2] + '.translateX', 2)
        cmds.setAttr(top_Loc[2] + '.translateX', 2)
        cmds.setAttr(mid_Loc[3] + '.translateX', 2)
    elif horizontal and axis == (0, 0, -1):
        if firstLimb:
            cmds.setAttr(bttm_Loc[2] + '.translateY', 2)
            cmds.setAttr(top_Loc[2] + '.translateX', -2)
            cmds.setAttr(mid_Loc[3] + '.translateX', -2)
            cmds.setAttr(mid_Loc[3] + '.translateY', 2)
        else:
            if s == 0:
                cmds.setAttr(bttm_Loc[2] + '.translateX', -2)
                cmds.setAttr(top_Loc[2] + '.translateY', -2)
                cmds.setAttr(mid_Loc[3] + '.translateX', -2)
                cmds.setAttr(mid_Loc[3] + '.translateY', 2)
            else:
                cmds.setAttr(bttm_Loc[2] + '.translateX', -2)
                cmds.setAttr(top_Loc[2] + '.translateY', -2)
                cmds.setAttr(mid_Loc[3] + '.translateX', -2)
                cmds.setAttr(mid_Loc[3] + '.translateY', 2)

    #create auxiliary joints that will be used to control the ribbon
    aux_Jnt.append(cmds.duplicate(drv_Jnt[1], name=name + '_Jxt_Rot')[0])
    cmds.setAttr(aux_Jnt[0] + '.jointOrient', 0, 0, 0)
    aux_Jnt.append(cmds.duplicate(aux_Jnt[0], name=name + '_Jxt_Rot_End')[0])

    cmds.parent(aux_Jnt[1], mid_Loc[3])
    cmds.setAttr(aux_Jnt[1] + '.translate', 0, 0, 0)
    cmds.parent(aux_Jnt[1], aux_Jnt[0])
    cmds.parent(mid_Loc[3], aux_Jnt[1])
    #calculate the adjust for the new chain position
    dist = float(numJoints) / 2.0
    end_dist = (1 / float(numJoints))
    cmds.parent(drv_Jnt[3], drv_Jnt[0])
    cmds.parent(drv_Jnt[4], drv_Jnt[2])

    #adjust the joints orientation and position based in the options choose from user
    if horizontal and axis == (1, 0, 0):
        cmds.setAttr(drv_Jnt[0] + '.jointOrient', 0, 90, 0)
        cmds.setAttr(drv_Jnt[2] + '.jointOrient', 0, 90, 0)

        cmds.setAttr(drv_Jnt[0] + '.tz', -dist)
        cmds.setAttr(drv_Jnt[3] + '.tz', end_dist * dist)
        cmds.setAttr(drv_Jnt[2] + '.tz', dist)
        cmds.setAttr(drv_Jnt[4] + '.tz', -end_dist * dist)

    elif horizontal and axis == (0, 1, 0):
        cmds.setAttr(drv_Jnt[0] + '.jointOrient', 0, 0, 0)
        cmds.setAttr(drv_Jnt[2] + '.jointOrient', 0, 0, 0)

        cmds.setAttr(drv_Jnt[0] + '.tx', -dist)
        cmds.setAttr(drv_Jnt[3] + '.tx', end_dist * dist)
        cmds.setAttr(drv_Jnt[2] + '.tx', dist)
        cmds.setAttr(drv_Jnt[4] + '.tx', -end_dist * dist)

    elif horizontal and axis == (0, 0, 1):
        cmds.setAttr(drv_Jnt[0] + '.jointOrient', 0, 0, 0)
        cmds.setAttr(drv_Jnt[2] + '.jointOrient', 0, 0, 0)

        cmds.setAttr(drv_Jnt[0] + '.tx', -dist)
        cmds.setAttr(drv_Jnt[3] + '.tx', end_dist * dist)
        cmds.setAttr(drv_Jnt[2] + '.tx', dist)
        cmds.setAttr(drv_Jnt[4] + '.tx', -end_dist * dist)

    elif horizontal and axis == (0, 0, -1):
        cmds.setAttr(drv_Jnt[0] + '.jointOrient', 0, 0, 0)
        cmds.setAttr(drv_Jnt[2] + '.jointOrient', 0, 0, 0)

        cmds.setAttr(drv_Jnt[0] + '.tx', -dist)
        cmds.setAttr(drv_Jnt[3] + '.tx', end_dist * dist)
        cmds.setAttr(drv_Jnt[2] + '.tx', dist)
        cmds.setAttr(drv_Jnt[4] + '.tx', -end_dist * dist)

    elif not horizontal and axis == (1, 0, 0):
        cmds.setAttr(drv_Jnt[0] + '.jointOrient', 0, 0, -90)
        cmds.setAttr(drv_Jnt[2] + '.jointOrient', 0, 0, -90)

        cmds.setAttr(drv_Jnt[0] + '.ty', -dist)
        cmds.setAttr(drv_Jnt[3] + '.ty', end_dist * dist)
        cmds.setAttr(drv_Jnt[2] + '.ty', dist)
        cmds.setAttr(drv_Jnt[4] + '.ty', -end_dist * dist)

    elif not horizontal and axis == (0, 1, 0):
        cmds.setAttr(drv_Jnt[0] + '.jointOrient', 0, 90, 0)
        cmds.setAttr(drv_Jnt[2] + '.jointOrient', 0, 90, 0)

        cmds.setAttr(drv_Jnt[0] + '.tz', -dist)
        cmds.setAttr(drv_Jnt[3] + '.tz', end_dist * dist)
        cmds.setAttr(drv_Jnt[2] + '.tz', dist)
        cmds.setAttr(drv_Jnt[4] + '.tz', -end_dist * dist)

    elif not horizontal and axis == (0, 0, 1):
        cmds.setAttr(drv_Jnt[0] + '.jointOrient', 0, 0, -90)
        cmds.setAttr(drv_Jnt[2] + '.jointOrient', 0, 0, -90)

        cmds.setAttr(drv_Jnt[0] + '.ty', -dist)
        cmds.setAttr(drv_Jnt[3] + '.ty', end_dist * dist)
        cmds.setAttr(drv_Jnt[2] + '.ty', dist)
        cmds.setAttr(drv_Jnt[4] + '.ty', -end_dist * dist)

    #fix the control locators position and orientation
    cmds.parent(top_Loc[0], drv_Jnt[2])
    cmds.setAttr(top_Loc[0] + '.translate', 0, 0, 0)
    cmds.parent(top_Loc[0], w=True)
    cmds.setAttr(top_Loc[0] + '.rotate', 0, 0, 0)

    cmds.parent(bttm_Loc[0], drv_Jnt[0])
    cmds.setAttr(bttm_Loc[0] + '.translate', 0, 0, 0)
    cmds.parent(bttm_Loc[0], w=True)
    cmds.setAttr(bttm_Loc[0] + '.rotate', 0, 0, 0)

    cmds.parent(drv_Jnt[2], top_Loc[1])
    cmds.parent(drv_Jnt[1], mid_Loc[2])
    cmds.parent(drv_Jnt[0], bttm_Loc[1])

    cmds.parent(aux_Jnt[0], mid_Loc[0])
    #create a nurbs control in order to be used in the ribbon offset
    mid_Ctrl = cmds.circle(c=(0, 0, 0),
                           nr=(1, 0, 0),
                           ch=0,
                           name=name + '_MidCtrl')[0]
    ctrls.renameShape([mid_Ctrl])
    midCtrl = mid_Ctrl
    mid_Ctrl = cmds.group(n=mid_Ctrl + '_Grp', em=True)
    cmds.delete(cmds.parentConstraint(midCtrl, mid_Ctrl, mo=0))
    cmds.parent(midCtrl, mid_Ctrl)

    #adjust the realtionship between the locators
    cmds.parent(mid_Ctrl, mid_Loc[2], r=True)
    cmds.parent(drv_Jnt[1], midCtrl)
    cmds.parent([top_Loc[2], mid_Loc[3], bttm_Loc[2]], w=True)
    cmds.makeIdentity(top_Loc[0], apply=True)
    cmds.makeIdentity(mid_Loc[0], apply=True)
    cmds.makeIdentity(bttm_Loc[0], apply=True)
    cmds.parent(top_Loc[2], top_Loc[0])
    cmds.parent(bttm_Loc[2], bttm_Loc[0])
    cmds.parent(mid_Loc[3], aux_Jnt[1])
    #create needed constraints in the locators in order to set the top always follow, to the base always aim the middle, to the middle always aim the top
    if firstLimb:
        cmds.aimConstraint(drv_Jnt[1],
                           bttm_Loc[1],
                           offset=(0, 0, 0),
                           weight=1,
                           aimVector=(1, 0, 0),
                           upVector=(0, 0, 1),
                           worldUpType='object',
                           worldUpObject=bttm_Loc[2],
                           name=bttm_Loc[1] + "_AimConstraint")
        cmds.aimConstraint(top_Loc[0],
                           mid_Loc[1],
                           offset=(0, 0, 0),
                           weight=1,
                           aimVector=(1, 0, 0),
                           upVector=(0, 0, 1),
                           worldUpType='object',
                           worldUpObject=mid_Loc[3],
                           name=mid_Loc[1] + "_AimConstraint")
        cmds.aimConstraint(drv_Jnt[1],
                           top_Loc[1],
                           offset=(0, 0, 0),
                           weight=1,
                           aimVector=(-1, 0, 0),
                           upVector=(0, 1, 0),
                           worldUpType='object',
                           worldUpObject=top_Loc[2],
                           name=top_Loc[1] + "_AimConstraint")
    else:
        # bug fix to plane twist
        cmds.aimConstraint(drv_Jnt[1],
                           bttm_Loc[1],
                           offset=(0, 0, 0),
                           weight=1,
                           aimVector=(1, 0, 0),
                           upVector=(0, 1, 0),
                           worldUpType='object',
                           worldUpObject=bttm_Loc[2],
                           name=bttm_Loc[1] + "_AimConstraint")
        cmds.aimConstraint(top_Loc[0],
                           mid_Loc[1],
                           offset=(0, 0, 0),
                           weight=1,
                           aimVector=(-1, 0, 0),
                           upVector=(0, 0, 1),
                           worldUpType='object',
                           worldUpObject=mid_Loc[3],
                           name=mid_Loc[1] + "_AimConstraint")
        cmds.aimConstraint(drv_Jnt[1],
                           top_Loc[1],
                           offset=(0, 0, 0),
                           weight=1,
                           aimVector=(-1, 0, 0),
                           upVector=(0, 0, 1),
                           worldUpType='object',
                           worldUpObject=top_Loc[2],
                           name=top_Loc[1] + "_AimConstraint")

    #create a point and orient constraint for the middel control
    cmds.pointConstraint(top_Loc[0],
                         bttm_Loc[0],
                         mid_Loc[0],
                         offset=(0, 0, 0),
                         weight=1,
                         name=mid_Loc[0] + "_PointConstraint")
    ori = cmds.orientConstraint(top_Loc[0],
                                bttm_Loc[0],
                                aux_Jnt[0],
                                offset=(0, 0, 0),
                                weight=1,
                                name=aux_Jnt[0] + "_OrientConstraint")

    #ribbon scale (volume variation)
    if numJoints == 3:
        proportionList = [0.5, 1, 0.5]
    elif numJoints == 5:
        proportionList = [0.4, 0.8, 1, 0.8, 0.4]
    elif numJoints == 7:
        proportionList = [0.25, 0.5, 0.75, 1, 0.75, 0.5, 0.25]

    curveInfoNode = cmds.arclen(ribbon + ".v[0.5]", constructionHistory=True)
    curveInfoNode = cmds.rename(curveInfoNode, ribbon + "_CurveInfo")
    rbScaleMD = cmds.createNode("multiplyDivide",
                                name=ribbon + "_ScaleCompensate_MD")
    rbNormalizeMD = cmds.createNode("multiplyDivide",
                                    name=ribbon + "_Normalize_MD")
    cmds.setAttr(rbNormalizeMD + ".operation", 2)
    cmds.connectAttr(curveInfoNode + ".arcLength",
                     rbNormalizeMD + ".input2X",
                     force=True)
    cmds.connectAttr(rbScaleMD + ".outputX",
                     rbNormalizeMD + ".input1X",
                     force=True)

    if cmds.objExists(worldRef):
        if not cmds.objExists(worldRef + "." + limbManualVVAttr):
            cmds.addAttr(worldRef,
                         longName=limbVVAttr,
                         attributeType="float",
                         minValue=0,
                         maxValue=1,
                         defaultValue=1,
                         keyable=True)
            cmds.addAttr(worldRef,
                         longName=limbManualVVAttr,
                         attributeType="float",
                         defaultValue=1,
                         keyable=True)
            cmds.addAttr(worldRef,
                         longName=limbMinVVAttr,
                         attributeType="float",
                         defaultValue=0.01,
                         keyable=True)
        cmds.connectAttr(worldRef + ".scaleX",
                         rbScaleMD + ".input1X",
                         force=True)

    #fix group hierarchy
    extraCtrlGrp = cmds.group(empty=True, name=name + "_ExtraBendyCtrl_Grp")
    i = 0
    for jnt in rb_Jnt:
        cmds.makeIdentity(jnt, a=True)
        # create extra control
        extraCtrlName = jnt.replace("_Jnt", "_Ctrl")
        extraCtrl = ctrls.cvSquare(ctrlName=extraCtrlName, r=ctrlRadius)
        extraCtrlList.append(extraCtrl)
        cmds.rotate(0, 0, 90, extraCtrl)
        cmds.makeIdentity(extraCtrl, a=True)
        extraCtrlZero = utils.zeroOut([extraCtrl])[0]
        cmds.parent(extraCtrlZero, extraCtrlGrp)
        cmds.parentConstraint(fols[i],
                              extraCtrlZero,
                              w=1,
                              name=extraCtrlZero + "_ParentConstraint")
        cmds.parentConstraint(extraCtrl,
                              jnt,
                              w=1,
                              name=jnt + "_ParentConstraint")
        cmds.scaleConstraint(extraCtrl,
                             jnt,
                             w=1,
                             name=jnt + "_ScaleConstraint")

        # work with volume variation
        rbProportionMD = cmds.createNode("multiplyDivide",
                                         name=extraCtrlName.replace(
                                             "_Ctrl", "_Proportion_MD"))
        rbIntensityMD = cmds.createNode("multiplyDivide",
                                        name=extraCtrlName.replace(
                                            "_Ctrl", "_Intensity_MD"))
        rbAddScalePMA = cmds.createNode("plusMinusAverage",
                                        name=extraCtrlName.replace(
                                            "_Ctrl", "_AddScale_PMA"))
        rbScaleClp = cmds.createNode("clamp",
                                     name=extraCtrlName.replace(
                                         "_Ctrl", "_Scale_Clp"))
        rbBlendCB = cmds.createNode("blendColors",
                                    name=extraCtrlName.replace(
                                        "_Ctrl", "_Blend_BC"))
        cmds.connectAttr(worldRef + "." + limbVVAttr,
                         rbBlendCB + ".blender",
                         force=True)
        cmds.setAttr(rbBlendCB + ".color2", 1, 1, 1, type="double3")
        cmds.connectAttr(rbNormalizeMD + ".outputX",
                         rbProportionMD + ".input1X",
                         force=True)
        cmds.setAttr(rbProportionMD + ".input2X", proportionList[i])
        cmds.connectAttr(rbProportionMD + ".outputX",
                         rbIntensityMD + ".input1X",
                         force=True)
        cmds.connectAttr(worldRef + "." + limbManualVVAttr,
                         rbIntensityMD + ".input2X",
                         force=True)
        cmds.connectAttr(rbIntensityMD + ".outputX",
                         rbAddScalePMA + ".input1D[1]",
                         force=True)
        cmds.connectAttr(rbAddScalePMA + ".output1D",
                         rbScaleClp + ".inputR",
                         force=True)
        cmds.connectAttr(worldRef + "." + limbMinVVAttr, rbScaleClp + ".minR")
        cmds.setAttr(rbScaleClp + ".maxR", 1000000)
        cmds.connectAttr(rbScaleClp + ".outputR",
                         rbBlendCB + ".color1.color1R",
                         force=True)
        cmds.connectAttr(rbBlendCB + ".output.outputR",
                         extraCtrlZero + ".scaleY",
                         force=True)
        cmds.connectAttr(rbBlendCB + ".output.outputR",
                         extraCtrlZero + ".scaleZ",
                         force=True)

        # update i
        i = i + 1

    locatorsGrp = cmds.group(bttm_Loc[0],
                             top_Loc[0],
                             mid_Loc[0],
                             n=name + '_Loc_Grp')
    skinJntGrp = cmds.group(rb_Jnt, n=name + '_Jnt_Grp')
    finalSystemGrp = cmds.group(ribbon,
                                locatorsGrp,
                                skinJntGrp,
                                n=name + '_RibbonSystem_Grp')

    #do the controller joints skin and the ribbon
    ribbonShape = cmds.listRelatives(ribbon, shapes=True)
    skin = cmds.skinCluster(drv_Jnt[0:3], ribbonShape, tsb=True, mi=2, dr=1)

    #skin presets for the ribbon (that's amazing!)
    if not horizontal:
        if numJoints == 3:
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][5]',
                             tv=(drv_Jnt[2], 1))
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][4]',
                             tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][3]',
                             tv=[(drv_Jnt[2], 0.2), (drv_Jnt[1], 0.8)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][2]',
                             tv=[(drv_Jnt[0], 0.2), (drv_Jnt[1], 0.8)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][1]',
                             tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][0]',
                             tv=(drv_Jnt[0], 1))

        elif numJoints == 5:
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][7]',
                             tv=(drv_Jnt[2], 1))
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][6]',
                             tv=[(drv_Jnt[2], 0.80), (drv_Jnt[1], 0.2)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][5]',
                             tv=[(drv_Jnt[2], 0.5), (drv_Jnt[1], 0.5)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][4]',
                             tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][3]',
                             tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][2]',
                             tv=[(drv_Jnt[0], 0.5), (drv_Jnt[1], 0.5)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][1]',
                             tv=[(drv_Jnt[0], 0.8), (drv_Jnt[1], 0.2)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][0]',
                             tv=(drv_Jnt[0], 1))
        elif numJoints == 7:
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][9]',
                             tv=(drv_Jnt[2], 1))
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][8]',
                             tv=[(drv_Jnt[2], 0.85), (drv_Jnt[1], 0.15)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][7]',
                             tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][6]',
                             tv=[(drv_Jnt[2], 0.35), (drv_Jnt[1], 0.65)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][5]',
                             tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][4]',
                             tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][3]',
                             tv=[(drv_Jnt[0], 0.35), (drv_Jnt[1], 0.65)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][2]',
                             tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][1]',
                             tv=[(drv_Jnt[0], 0.85), (drv_Jnt[1], 0.15)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0:1][0]',
                             tv=(drv_Jnt[0], 1))
    else:
        if numJoints == 3:
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[5][0:1]',
                             tv=(drv_Jnt[2], 1))
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[4][0:1]',
                             tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[3][0:1]',
                             tv=[(drv_Jnt[2], 0.2), (drv_Jnt[1], 0.8)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[2][0:1]',
                             tv=[(drv_Jnt[0], 0.2), (drv_Jnt[1], 0.8)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[1][0:1]',
                             tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0][0:1]',
                             tv=(drv_Jnt[0], 1))
        elif numJoints == 5:
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[7][0:1]',
                             tv=(drv_Jnt[2], 1))
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[6][0:1]',
                             tv=[(drv_Jnt[2], 0.80), (drv_Jnt[1], 0.2)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[5][0:1]',
                             tv=[(drv_Jnt[2], 0.5), (drv_Jnt[1], 0.5)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[4][0:1]',
                             tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[3][0:1]',
                             tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[2][0:1]',
                             tv=[(drv_Jnt[0], 0.5), (drv_Jnt[1], 0.5)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[1][0:1]',
                             tv=[(drv_Jnt[0], 0.8), (drv_Jnt[1], 0.2)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0][0:1]',
                             tv=(drv_Jnt[0], 1))
        elif numJoints == 7:
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[9][0:1]',
                             tv=(drv_Jnt[2], 1))
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[8][0:1]',
                             tv=[(drv_Jnt[2], 0.85), (drv_Jnt[1], 0.15)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[7][0:1]',
                             tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[6][0:1]',
                             tv=[(drv_Jnt[2], 0.35), (drv_Jnt[1], 0.65)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[5][0:1]',
                             tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[4][0:1]',
                             tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[3][0:1]',
                             tv=[(drv_Jnt[0], 0.35), (drv_Jnt[1], 0.65)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[2][0:1]',
                             tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[1][0:1]',
                             tv=[(drv_Jnt[0], 0.85), (drv_Jnt[1], 0.15)])
            cmds.skinPercent(skin[0],
                             ribbon + '.cv[0][0:1]',
                             tv=(drv_Jnt[0], 1))
    constr = []
    if guias:
        top = guias[0]
        bottom = guias[1]
        constr.append(
            cmds.parentConstraint(top,
                                  bttm_Loc[0],
                                  mo=False,
                                  name=bttm_Loc[0] + "_ParentConstraint"))
        constr.append(
            cmds.parentConstraint(bottom,
                                  top_Loc[0],
                                  mo=False,
                                  name=top_Loc[0] + "_ParentConstraint"))

    #fix orientation issues
    cmds.delete(ori)
    cmds.orientConstraint(bttm_Loc[0],
                          aux_Jnt[0],
                          weight=0.5,
                          mo=True,
                          name=aux_Jnt[0] + "_OrientConstraint")

    #fix loc_Grp scale
    if guias:
        from math import sqrt, pow
        auxLoc1 = cmds.spaceLocator(name='auxLoc1')[0]
        auxLoc2 = cmds.spaceLocator(name='auxLoc2')[0]
        cmds.delete(cmds.parentConstraint(top, auxLoc1, mo=False, w=1))
        cmds.delete(cmds.parentConstraint(bottom, auxLoc2, mo=False, w=1))
        a = cmds.xform(auxLoc1, ws=True, translation=True, q=True)
        b = cmds.xform(auxLoc2, ws=True, translation=True, q=True)

        dist = sqrt(
            pow(a[0] - b[0], 2.0) + pow(a[1] - b[1], 2.0) +
            pow(a[2] - b[2], 2.0))
        scale = dist / float(numJoints)

        cmds.setAttr(locatorsGrp + '.s', scale, scale, scale)

        cmds.delete(auxLoc1, auxLoc2)

    # baseTwist:
    if not upCtrl == None:
        bttm_LocGrp = cmds.group(bttm_Loc[2], name=bttm_Loc[2] + "_Grp")
        bttm_LocPos = cmds.xform(bttm_Loc[0],
                                 query=True,
                                 worldSpace=True,
                                 translation=True)
        cmds.move(bttm_LocPos[0],
                  bttm_LocPos[1],
                  bttm_LocPos[2],
                  bttm_LocGrp + ".scalePivot",
                  bttm_LocGrp + ".rotatePivot",
                  absolute=True)
        cmds.connectAttr(upCtrl + ".baseTwist",
                         bttm_LocGrp + ".rotateZ",
                         force=True)

    #updating values
    cmds.setAttr(rbScaleMD + ".input2X",
                 cmds.getAttr(curveInfoNode + ".arcLength"))
    for jnt in rb_Jnt:
        rbAddScalePMA = jnt.replace("_Jnt", "_AddScale_PMA")
        cmds.setAttr(rbAddScalePMA + ".input1D[0]",
                     1 - cmds.getAttr(rbAddScalePMA + ".input1D[1]"))

    #change renderStats
    ribbonShape = cmds.listRelatives(ribbon, s=True, f=True)[0]

    cmds.setAttr(ribbonShape + '.castsShadows', 0)
    cmds.setAttr(ribbonShape + '.receiveShadows', 0)
    cmds.setAttr(ribbonShape + '.motionBlur', 0)
    cmds.setAttr(ribbonShape + '.primaryVisibility', 0)
    cmds.setAttr(ribbonShape + '.smoothShading', 0)
    cmds.setAttr(ribbonShape + '.visibleInReflections', 0)
    cmds.setAttr(ribbonShape + '.visibleInRefractions', 0)
    cmds.setAttr(ribbonShape + '.doubleSided', 1)

    retDict['name'] = name
    retDict['locsList'] = [top_Loc[0], mid_Loc[0], bttm_Loc[0]]
    retDict['skinJointsList'] = rb_Jnt
    retDict['scaleGrp'] = locatorsGrp
    retDict['finalGrp'] = finalSystemGrp
    retDict['middleCtrl'] = mid_Ctrl
    retDict['constraints'] = constr
    retDict['bendGrpList'] = [top_Loc[0], bttm_Loc[0]]
    retDict['extraCtrlGrp'] = extraCtrlGrp
    retDict['extraCtrlList'] = extraCtrlList
    retDict['rbScaleMD'] = rbScaleMD
    retDict['rbNormalizeMD'] = rbNormalizeMD
    cmds.setAttr(finalSystemGrp + '.v', v)
    return retDict
예제 #37
0
def rebuild_splitter_surface(surface='', number_of_span=5):
    result = cmds.rebuildSurface(surface, ch=False, kr=2, su=number_of_span, sv=1)[0]
    return result
예제 #38
0
def create(surface,spansU=0,spansV=0,prefix=None):
	'''
	'''
	# Load Plugins
	loadPlugin()

	# ==========
	# - Checks -
	# ==========

	# Check Surface
	if not glTools.utils.surface.isSurface(surface):
		raise Exception('Object "'+surface+'" is not a valid nurbs surface!')

	# Check Prefix
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(surface)

	# Get Surface Details
	if not spansU: spansU = mc.getAttr(surface+'.spansU')
	if not spansV: spansV = mc.getAttr(surface+'.spansV')
	minU = mc.getAttr(surface+'.minValueU')
	maxU = mc.getAttr(surface+'.maxValueU')
	minV = mc.getAttr(surface+'.minValueV')
	maxV = mc.getAttr(surface+'.maxValueV')
	incU = (maxU-minU)/spansU
	incV = (maxV-minV)/spansV

	# =============
	# - Rebuild U -
	# =============

	crvU = []
	for i in range(spansU+1):

		# Duplicate Surface Curve
		dupCurve = mc.duplicateCurve(surface+'.u['+str(incU*i)+']',ch=True,rn=False,local=False)
		dupCurveNode = mc.rename(dupCurve[1],prefix+'_spanU'+str(i)+'_duplicateCurve')
		dupCurve = mc.rename(dupCurve[0],prefix+'_spanU'+str(i)+'_crv')
		crvU.append(dupCurve)

		# Set Curve Length
		arcLen = mc.arclen(dupCurve)
		setLen = mc.createNode('setCurveLength',n=prefix+'_spanU'+str(i)+'_setCurveLength')
		crvInfo = mc.createNode('curveInfo',n=prefix+'_spanU'+str(i)+'_curveInfo')
		blendLen = mc.createNode('blendTwoAttr',n=prefix+'_spanU'+str(i)+'length_blendTwoAttr')
		mc.addAttr(dupCurve,ln='targetLength',dv=arcLen,k=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',crvInfo+'.inputCurve',f=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',setLen+'.inputCurve',f=True)
		mc.connectAttr(crvInfo+'.arcLength',blendLen+'.input[0]',f=True)
		mc.connectAttr(dupCurve+'.targetLength',blendLen+'.input[1]',f=True)
		mc.connectAttr(blendLen+'.output',setLen+'.length',f=True)
		mc.connectAttr(setLen+'.outputCurve',dupCurve+'.create',f=True)

		# Add Control Attributes
		mc.addAttr(dupCurve,ln='lockLength',min=0,max=1,dv=1,k=True)
		mc.addAttr(dupCurve,ln='lengthBias',min=0,max=1,dv=0,k=True)
		mc.connectAttr(dupCurve+'.lockLength',blendLen+'.attributesBlender',f=True)
		mc.connectAttr(dupCurve+'.lengthBias',setLen+'.bias',f=True)

	# Loft New Surface
	srfU = mc.loft(crvU,ch=True,uniform=True,close=False,autoReverse=False,degree=3)
	srfUloft = mc.rename(srfU[1],prefix+'_rebuildU_loft')
	srfU = mc.rename(srfU[0],prefix+'_rebuildU_srf')

	# Rebuild 0-1
	rebuildSrf = mc.rebuildSurface(srfU,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=1,su=0,du=3,sv=0,dv=3,tol=0)
	rebuildSrfNode = mc.rename(rebuildSrf[1],prefix+'_rebuildU_rebuildSurface')

	# Add Control Attributes
	mc.addAttr(srfU,ln='lockLength',min=0,max=1,dv=1,k=True)
	mc.addAttr(srfU,ln='lengthBias',min=0,max=1,dv=0,k=True)
	for crv in crvU:
		mc.connectAttr(srfU+'.lockLength',crv+'.lockLength',f=True)
		mc.connectAttr(srfU+'.lengthBias',crv+'.lengthBias',f=True)

	# =============
	# - Rebuild V -
	# =============

	crvV = []
	for i in range(spansV+1):

		# Duplicate Surface Curve
		dupCurve = mc.duplicateCurve(srfU+'.v['+str(incV*i)+']',ch=True,rn=False,local=False)
		dupCurveNode = mc.rename(dupCurve[1],prefix+'_spanV'+str(i)+'_duplicateCurve')
		dupCurve = mc.rename(dupCurve[0],prefix+'_spanV'+str(i)+'_crv')
		crvV.append(dupCurve)

		# Set Curve Length
		arcLen = mc.arclen(dupCurve)
		setLen = mc.createNode('setCurveLength',n=prefix+'_spanV'+str(i)+'_setCurveLength')
		crvInfo = mc.createNode('curveInfo',n=prefix+'_spanV'+str(i)+'_curveInfo')
		blendLen = mc.createNode('blendTwoAttr',n=prefix+'_spanV'+str(i)+'length_blendTwoAttr')
		mc.addAttr(dupCurve,ln='targetLength',dv=arcLen,k=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',crvInfo+'.inputCurve',f=True)
		mc.connectAttr(dupCurveNode+'.outputCurve',setLen+'.inputCurve',f=True)
		mc.connectAttr(crvInfo+'.arcLength',blendLen+'.input[0]',f=True)
		mc.connectAttr(dupCurve+'.targetLength',blendLen+'.input[1]',f=True)
		mc.connectAttr(blendLen+'.output',setLen+'.length',f=True)
		mc.connectAttr(setLen+'.outputCurve',dupCurve+'.create',f=True)

		# Add Control Attribute
		mc.addAttr(dupCurve,ln='lockLength',min=0,max=1,dv=1,k=True)
		mc.addAttr(dupCurve,ln='lengthBias',min=0,max=1,dv=0,k=True)
		mc.connectAttr(dupCurve+'.lockLength',blendLen+'.attributesBlender',f=True)
		mc.connectAttr(dupCurve+'.lengthBias',setLen+'.bias',f=True)

	# Loft New Surface
	srfV = mc.loft(crvV,ch=True,uniform=True,close=False,autoReverse=False,degree=3)
	srfVloft = mc.rename(srfV[1],prefix+'_rebuildV_loft')
	srfV = mc.rename(srfV[0],prefix+'_rebuildV_srf')

	# Rebuild 0-1
	rebuildSrf = mc.rebuildSurface(srfV,ch=True,rpo=True,rt=0,end=1,kr=0,kcp=1,su=0,du=3,sv=0,dv=3,tol=0)
	rebuildSrfNode = mc.rename(rebuildSrf[1],prefix+'_rebuildV_rebuildSurface')

	# Add Control Attribute
	mc.addAttr(srfV,ln='lockLength',min=0,max=1,dv=1,k=True)
	mc.addAttr(srfV,ln='lengthBias',min=0,max=1,dv=0,k=True)
	for crv in crvV:
		mc.connectAttr(srfV+'.lockLength',crv+'.lockLength',f=True)
		mc.connectAttr(srfV+'.lengthBias',crv+'.lengthBias',f=True)

	# ===================
	# - Build Hierarchy -
	# ===================

	rebuildUGrp = mc.group(em=True,n=prefix+'_rebuildU_grp')
	mc.parent(crvU,rebuildUGrp)
	mc.parent(srfU,rebuildUGrp)

	rebuildVGrp = mc.group(em=True,n=prefix+'_rebuildV_grp')
	mc.parent(crvV,rebuildVGrp)
	mc.parent(srfV,rebuildVGrp)

	rebuildGrp = mc.group(em=True,n=prefix+'_lockLength_grp')
	mc.parent(rebuildUGrp,rebuildGrp)
	mc.parent(rebuildVGrp,rebuildGrp)

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

	return rebuildGrp
예제 #39
0
파일: jcRibbon.py 프로젝트: utsdab/usr
def createRibbon(axis=(0, 0, 1), name='xxxx', horizontal=False, numJoints=3, guias=None, v=True, s=0, firstLimb=True, upCtrl=None, ctrlRadius=1, worldRef="worldRef"):
        retDict = {}
        
        #define variables
        top_Loc = []
        mid_Loc = []
        bttm_Loc = []
        rb_Jnt = []
        drv_Jnt =[]
        fols = []
        aux_Jnt = []
        ribbon = ''
        extraCtrlList = []

        #define attributes
        limbManualVVAttr = "limbManualVolume"
        limbVVAttr       = "limbVolumeVariation"
        limbMinVVAttr    = "limbMinVolume"

        #create a nurbsPlane based in the choose orientation option
        if horizontal:
            ribbon =cmds.nurbsPlane(ax=axis, w=numJoints, lr=(1/float(numJoints)), d=3, u=numJoints, v=1, ch=0, name=name+'_Plane')[0]
            cmds.rebuildSurface(ribbon, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kc=0, sv=1, du=3, dv=1, tol=0.01, fr=0, dir=1) 
        else:
            ribbon =cmds.nurbsPlane(ax=axis, w=1, lr=numJoints, d=3, u=1, v=numJoints, ch=0, name=name+'_Plane')[0]
            cmds.rebuildSurface(ribbon, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kc=0, su=1, du=1, dv=3, tol=0.01, fr=0, dir=0) 
        # make this ribbonNurbsPlane as not skinable from dpAR_UI:
        cmds.addAttr(ribbon, longName="doNotSkinIt", attributeType="bool", keyable=True)
        cmds.setAttr(ribbon+".doNotSkinIt", 1)
        #call the function to create follicles and joint in the nurbsPlane
        results = createFollicles(rib=ribbon, num=numJoints, name=name, horizontal=horizontal)
        rb_Jnt = results[0]
        fols = results[1]
        #create locator controls for the middle of the ribbon
        mid_Loc.append(cmds.spaceLocator(name=name+'_Mid_Pos_Loc')[0])
        mid_Loc.append(cmds.spaceLocator(name=name+'_Mid_Aim_Loc')[0])
        mid_Loc.append(cmds.spaceLocator(name=name+'_Mid_Off_Loc')[0])
        mid_Loc.append(cmds.spaceLocator(name=name+'_Mid_Up_Loc')[0])
        #parent correctly the middle locators
        cmds.parent(mid_Loc[2], mid_Loc[1], relative=True)
        cmds.parent(mid_Loc[1], mid_Loc[0], relative=True)
        cmds.parent(mid_Loc[3], mid_Loc[0], relative=True)
        #create the locators controls for the top of the ribbon
        top_Loc.append(cmds.spaceLocator(name=name+'_Top_Pos_Loc')[0])
        top_Loc.append(cmds.spaceLocator(name=name+'_Top_Aim_Loc')[0])
        top_Loc.append(cmds.spaceLocator(name=name+'_Top_Up_Loc')[0])
        #parent correctly the top locators
        cmds.parent(top_Loc[1], top_Loc[0], relative=True)
        cmds.parent(top_Loc[2], top_Loc[0], relative=True)
        #create the locators for the end of the ribbon
        bttm_Loc.append(cmds.spaceLocator(name=name+'_Bttm_Pos_Loc')[0])
        bttm_Loc.append(cmds.spaceLocator(name=name+'_Bttm_Aim_Loc')[0])
        bttm_Loc.append(cmds.spaceLocator(name=name+'_Bttm_Up_Loc')[0])
        #parent correctly the bottom locators
        cmds.parent(bttm_Loc[1], bttm_Loc[0], relative=True)
        cmds.parent(bttm_Loc[2], bttm_Loc[0], relative=True)
        
        #put the top locators in the same place of the top joint
        cmds.parent(top_Loc[0], fols[len(fols)-1], relative=True)
        cmds.parent(top_Loc[0], w=True)
        
        #put the bottom locators in the same place of the bottom joint
        cmds.parent(bttm_Loc[0], fols[0], relative=True)
        cmds.parent(bttm_Loc[0], w=True)
        cmds.select(clear=True)
        
        #create the joints that will be used to control the ribbon
        drv_Jnt = cmds.duplicate([rb_Jnt[0], rb_Jnt[(len(rb_Jnt)-1)/2], rb_Jnt[len(rb_Jnt)-1]])
        dup = cmds.duplicate([drv_Jnt[0], drv_Jnt[2]])
        drv_Jnt.append(dup[0])
        drv_Jnt.append(dup[1])
        #cmds.parent(drv_Jnt, w=True)
        for jnt in drv_Jnt:
            cmds.joint(jnt, e=True, oj='none', ch=True, zso=True);
            cmds.setAttr(jnt+'.radius', cmds.getAttr(jnt+'.radius')+0.5)
        #rename created joints
        drv_Jnt[0] = cmds.rename(drv_Jnt[0], name+'_Drv_Bttm_Jxt')
        drv_Jnt[1] = cmds.rename(drv_Jnt[1], name+'_Drv_Mid_Jxt')
        drv_Jnt[2] = cmds.rename(drv_Jnt[2], name+'_Drv_Top_Jxt')
        drv_Jnt[3] = cmds.rename(drv_Jnt[3], name+'_Drv_Bttm_End')
        drv_Jnt[4] = cmds.rename(drv_Jnt[4], name+'_Drv_Top_End')
        
        #place joints correctly accordaly with the user options choose
        if (horizontal and axis==(1, 0, 0)) or (horizontal and axis==(0, 0, 1)):
            cmds.setAttr(bttm_Loc[2]+'.translateY', 2)
            cmds.setAttr(top_Loc[2]+'.translateY', 2)
            cmds.setAttr(mid_Loc[3]+'.translateY', 2)
        elif (horizontal and axis==(0, 1, 0)) or (not horizontal and axis==(1, 0, 0)):
            cmds.setAttr(bttm_Loc[2]+'.translateZ', 2)
            cmds.setAttr(top_Loc[2]+'.translateZ', 2)
            cmds.setAttr(mid_Loc[3]+'.translateZ', 2)
        elif not horizontal and axis==(0, 1, 0) or (not horizontal and axis==(0, 0, 1)):
            cmds.setAttr(bttm_Loc[2]+'.translateX', 2)
            cmds.setAttr(top_Loc[2]+'.translateX', 2)
            cmds.setAttr(mid_Loc[3]+'.translateX', 2)
        elif horizontal and axis==(0, 0, -1):
            if firstLimb:
                cmds.setAttr(bttm_Loc[2]+'.translateY', 2)
                cmds.setAttr(top_Loc[2]+'.translateX', -2)
                cmds.setAttr(mid_Loc[3]+'.translateX', -2)
                cmds.setAttr(mid_Loc[3]+'.translateY', 2)
            else:
                if s == 0:
                    cmds.setAttr(bttm_Loc[2]+'.translateX', -2)
                    cmds.setAttr(top_Loc[2]+'.translateY', -2)
                    cmds.setAttr(mid_Loc[3]+'.translateX', -2)
                    cmds.setAttr(mid_Loc[3]+'.translateY', 2)
                else:
                    cmds.setAttr(bttm_Loc[2]+'.translateX', -2)
                    cmds.setAttr(top_Loc[2]+'.translateY', -2)
                    cmds.setAttr(mid_Loc[3]+'.translateX', -2)
                    cmds.setAttr(mid_Loc[3]+'.translateY', 2)
                
        
        #create auxiliary joints that will be used to control the ribbon
        aux_Jnt.append(cmds.duplicate(drv_Jnt[1], name=name+'_Jxt_Rot')[0])
        cmds.setAttr(aux_Jnt[0]+'.jointOrient', 0, 0, 0)
        aux_Jnt.append(cmds.duplicate(aux_Jnt[0], name=name+'_Jxt_Rot_End')[0])
        
        cmds.parent(aux_Jnt[1], mid_Loc[3])
        cmds.setAttr(aux_Jnt[1]+'.translate', 0, 0, 0)
        cmds.parent(aux_Jnt[1], aux_Jnt[0])
        cmds.parent(mid_Loc[3], aux_Jnt[1])
        #calculate the adjust for the new chain position
        dist = float(numJoints)/2.0
        end_dist = (1/float(numJoints))
        cmds.parent(drv_Jnt[3], drv_Jnt[0])
        cmds.parent(drv_Jnt[4], drv_Jnt[2])
        
        #adjust the joints orientation and position based in the options choose from user
        if horizontal and axis==(1, 0, 0):
            cmds.setAttr(drv_Jnt[0]+'.jointOrient', 0, 90, 0)
            cmds.setAttr(drv_Jnt[2]+'.jointOrient', 0, 90, 0)
            
            cmds.setAttr(drv_Jnt[0]+'.tz', -dist)
            cmds.setAttr(drv_Jnt[3]+'.tz', end_dist*dist)
            cmds.setAttr(drv_Jnt[2]+'.tz', dist)
            cmds.setAttr(drv_Jnt[4]+'.tz', -end_dist*dist)
        
        elif horizontal and axis==(0, 1, 0):
            cmds.setAttr(drv_Jnt[0]+'.jointOrient', 0, 0, 0)
            cmds.setAttr(drv_Jnt[2]+'.jointOrient', 0, 0, 0)
            
            cmds.setAttr(drv_Jnt[0]+'.tx', -dist)
            cmds.setAttr(drv_Jnt[3]+'.tx', end_dist*dist)
            cmds.setAttr(drv_Jnt[2]+'.tx', dist)
            cmds.setAttr(drv_Jnt[4]+'.tx', -end_dist*dist)
        
        elif horizontal and axis==(0, 0, 1):
            cmds.setAttr(drv_Jnt[0]+'.jointOrient', 0, 0, 0)
            cmds.setAttr(drv_Jnt[2]+'.jointOrient', 0, 0, 0)
            
            cmds.setAttr(drv_Jnt[0]+'.tx', -dist)
            cmds.setAttr(drv_Jnt[3]+'.tx', end_dist*dist)
            cmds.setAttr(drv_Jnt[2]+'.tx', dist)
            cmds.setAttr(drv_Jnt[4]+'.tx', -end_dist*dist)
        
        elif horizontal and axis==(0, 0, -1):
            cmds.setAttr(drv_Jnt[0]+'.jointOrient', 0, 0, 0)
            cmds.setAttr(drv_Jnt[2]+'.jointOrient', 0, 0, 0)
            
            cmds.setAttr(drv_Jnt[0]+'.tx', -dist)
            cmds.setAttr(drv_Jnt[3]+'.tx', end_dist*dist)
            cmds.setAttr(drv_Jnt[2]+'.tx', dist)
            cmds.setAttr(drv_Jnt[4]+'.tx', -end_dist*dist)
            
        elif not horizontal and axis==(1, 0, 0):
            cmds.setAttr(drv_Jnt[0]+'.jointOrient', 0, 0, -90)
            cmds.setAttr(drv_Jnt[2]+'.jointOrient', 0, 0, -90)
        
            cmds.setAttr(drv_Jnt[0]+'.ty', -dist)
            cmds.setAttr(drv_Jnt[3]+'.ty', end_dist*dist)
            cmds.setAttr(drv_Jnt[2]+'.ty', dist)
            cmds.setAttr(drv_Jnt[4]+'.ty', -end_dist*dist)
            
        elif not horizontal and axis==(0, 1, 0):
            cmds.setAttr(drv_Jnt[0]+'.jointOrient', 0, 90, 0)
            cmds.setAttr(drv_Jnt[2]+'.jointOrient', 0, 90, 0)
        
            cmds.setAttr(drv_Jnt[0]+'.tz', -dist)
            cmds.setAttr(drv_Jnt[3]+'.tz', end_dist*dist)
            cmds.setAttr(drv_Jnt[2]+'.tz', dist)
            cmds.setAttr(drv_Jnt[4]+'.tz', -end_dist*dist)
            
        elif not horizontal and axis==(0, 0, 1):
            cmds.setAttr(drv_Jnt[0]+'.jointOrient', 0, 0, -90)
            cmds.setAttr(drv_Jnt[2]+'.jointOrient', 0, 0, -90)
        
            cmds.setAttr(drv_Jnt[0]+'.ty', -dist)
            cmds.setAttr(drv_Jnt[3]+'.ty', end_dist*dist)
            cmds.setAttr(drv_Jnt[2]+'.ty', dist)
            cmds.setAttr(drv_Jnt[4]+'.ty', -end_dist*dist)
        
        #fix the control locators position and orientation
        cmds.parent(top_Loc[0], drv_Jnt[2])
        cmds.setAttr(top_Loc[0]+'.translate', 0, 0, 0)
        cmds.parent(top_Loc[0], w=True)
        cmds.setAttr(top_Loc[0]+'.rotate', 0, 0, 0)
        
        cmds.parent(bttm_Loc[0], drv_Jnt[0])
        cmds.setAttr(bttm_Loc[0]+'.translate', 0, 0, 0)
        cmds.parent(bttm_Loc[0], w=True)
        cmds.setAttr(bttm_Loc[0]+'.rotate', 0, 0, 0)    
        
        cmds.parent(drv_Jnt[2], top_Loc[1])
        cmds.parent(drv_Jnt[1], mid_Loc[2])
        cmds.parent(drv_Jnt[0], bttm_Loc[1])
        
        cmds.parent(aux_Jnt[0], mid_Loc[0])
        #create a nurbs control in order to be used in the ribbon offset
        mid_Ctrl = cmds.circle (c=(0, 0, 0), nr=(1, 0, 0), ch=0, name=name+'_MidCtrl')[0]
        ctrls.renameShape([mid_Ctrl])
        midCtrl = mid_Ctrl
        mid_Ctrl = cmds.group(n=mid_Ctrl+'_Grp', em=True)
        cmds.delete(cmds.parentConstraint(midCtrl, mid_Ctrl, mo=0))
        cmds.parent(midCtrl, mid_Ctrl)
        
        #adjust the realtionship between the locators
        cmds.parent(mid_Ctrl, mid_Loc[2], r=True)
        cmds.parent(drv_Jnt[1], midCtrl)
        cmds.parent([top_Loc[2], mid_Loc[3], bttm_Loc[2]], w=True)
        cmds.makeIdentity(top_Loc[0], apply=True)
        cmds.makeIdentity(mid_Loc[0], apply=True)
        cmds.makeIdentity(bttm_Loc[0], apply=True)
        cmds.parent(top_Loc[2], top_Loc[0])
        cmds.parent(bttm_Loc[2], bttm_Loc[0])
        cmds.parent(mid_Loc[3], aux_Jnt[1]) 
        #create needed constraints in the locators in order to set the top always follow, to the base always aim the middle, to the middle always aim the top
        if firstLimb:
            cmds.aimConstraint(drv_Jnt[1], bttm_Loc[1], offset=(0, 0, 0), weight=1, aimVector=(1, 0, 0), upVector=(0, 0, 1), worldUpType='object', worldUpObject=bttm_Loc[2], name=bttm_Loc[1]+"_AimConstraint")
            cmds.aimConstraint(top_Loc[0], mid_Loc[1], offset=(0, 0, 0), weight=1, aimVector=(1, 0, 0), upVector=(0, 0, 1), worldUpType='object', worldUpObject=mid_Loc[3], name=mid_Loc[1]+"_AimConstraint")
            cmds.aimConstraint(drv_Jnt[1], top_Loc[1], offset=(0, 0, 0), weight=1, aimVector=(-1, 0, 0), upVector=(0, 1, 0), worldUpType='object', worldUpObject=top_Loc[2], name=top_Loc[1]+"_AimConstraint")
        else:
            # bug fix to plane twist
            cmds.aimConstraint(drv_Jnt[1], bttm_Loc[1], offset=(0, 0, 0), weight=1, aimVector=(1, 0, 0), upVector=(0, 1, 0), worldUpType='object', worldUpObject=bttm_Loc[2], name=bttm_Loc[1]+"_AimConstraint")
            cmds.aimConstraint(top_Loc[0], mid_Loc[1], offset=(0, 0, 0), weight=1, aimVector=(-1, 0, 0), upVector=(0, 0, 1), worldUpType='object', worldUpObject=mid_Loc[3], name=mid_Loc[1]+"_AimConstraint")
            cmds.aimConstraint(drv_Jnt[1], top_Loc[1], offset=(0, 0, 0), weight=1, aimVector=(-1, 0, 0), upVector=(0, 0, 1), worldUpType='object', worldUpObject=top_Loc[2], name=top_Loc[1]+"_AimConstraint")
        
        #create a point and orient constraint for the middel control
        cmds.pointConstraint(top_Loc[0], bttm_Loc[0], mid_Loc[0], offset=(0, 0, 0), weight=1, name=mid_Loc[0]+"_PointConstraint")
        ori = cmds.orientConstraint(top_Loc[0], bttm_Loc[0], aux_Jnt[0], offset=(0, 0, 0), weight=1, name=aux_Jnt[0]+"_OrientConstraint")
        
        #ribbon scale (volume variation)
        if numJoints == 3:
            proportionList = [0.5, 1, 0.5]
        elif numJoints == 5:
            proportionList = [0.4, 0.8, 1, 0.8, 0.4]
        elif numJoints == 7:
            proportionList = [0.25, 0.5, 0.75, 1, 0.75, 0.5, 0.25]

        curveInfoNode = cmds.arclen(ribbon+".v[0.5]", constructionHistory=True)
        curveInfoNode = cmds.rename(curveInfoNode, ribbon+"_CurveInfo")
        rbScaleMD = cmds.createNode("multiplyDivide", name=ribbon+"_ScaleCompensate_MD")
        rbNormalizeMD = cmds.createNode("multiplyDivide", name=ribbon+"_Normalize_MD")
        cmds.setAttr(rbNormalizeMD+".operation", 2)
        cmds.connectAttr(curveInfoNode+".arcLength", rbNormalizeMD+".input2X", force=True)
        cmds.connectAttr(rbScaleMD+".outputX", rbNormalizeMD+".input1X", force=True)

        if cmds.objExists(worldRef):
            if not cmds.objExists(worldRef+"."+limbManualVVAttr):
                cmds.addAttr(worldRef, longName=limbVVAttr, attributeType="float", minValue=0, maxValue=1, defaultValue=1, keyable=True)
                cmds.addAttr(worldRef, longName=limbManualVVAttr, attributeType="float", defaultValue=1, keyable=True)
                cmds.addAttr(worldRef, longName=limbMinVVAttr, attributeType="float", defaultValue=0.01, keyable=True)
            cmds.connectAttr(worldRef+".scaleX", rbScaleMD+".input1X", force=True)
        
        #fix group hierarchy
        extraCtrlGrp = cmds.group(empty=True, name=name+"_ExtraBendyCtrl_Grp")
        i = 0
        for jnt in rb_Jnt:
            cmds.makeIdentity(jnt, a=True)
            # create extra control
            extraCtrlName = jnt.replace("_Jnt", "_Ctrl")
            extraCtrl = ctrls.cvSquare(ctrlName=extraCtrlName, r=ctrlRadius)
            extraCtrlList.append(extraCtrl)
            cmds.rotate(0, 0, 90, extraCtrl)
            cmds.makeIdentity(extraCtrl, a=True)
            extraCtrlZero = utils.zeroOut([extraCtrl])[0]
            cmds.parent(extraCtrlZero, extraCtrlGrp)
            cmds.parentConstraint(fols[i], extraCtrlZero, w=1, name=extraCtrlZero+"_ParentConstraint")
            cmds.parentConstraint(extraCtrl, jnt, w=1, name=jnt+"_ParentConstraint")
            cmds.scaleConstraint(extraCtrl, jnt, w=1, name=jnt+"_ScaleConstraint")
            
            # work with volume variation
            rbProportionMD = cmds.createNode("multiplyDivide", name=extraCtrlName.replace("_Ctrl", "_Proportion_MD"))
            rbIntensityMD = cmds.createNode("multiplyDivide", name=extraCtrlName.replace("_Ctrl", "_Intensity_MD"))
            rbAddScalePMA = cmds.createNode("plusMinusAverage", name=extraCtrlName.replace("_Ctrl", "_AddScale_PMA"))
            rbScaleClp = cmds.createNode("clamp", name=extraCtrlName.replace("_Ctrl", "_Scale_Clp"))
            rbBlendCB = cmds.createNode("blendColors", name=extraCtrlName.replace("_Ctrl", "_Blend_BC"))
            cmds.connectAttr(worldRef+"."+limbVVAttr, rbBlendCB+".blender", force=True)
            cmds.setAttr(rbBlendCB+".color2", 1, 1, 1, type="double3")
            cmds.connectAttr(rbNormalizeMD+".outputX", rbProportionMD+".input1X", force=True)
            cmds.setAttr(rbProportionMD+".input2X", proportionList[i])
            cmds.connectAttr(rbProportionMD+".outputX", rbIntensityMD+".input1X", force=True)
            cmds.connectAttr(worldRef+"."+limbManualVVAttr, rbIntensityMD+".input2X", force=True)
            cmds.connectAttr(rbIntensityMD+".outputX", rbAddScalePMA+".input1D[1]", force=True)
            cmds.connectAttr(rbAddScalePMA+".output1D", rbScaleClp+".inputR", force=True)
            cmds.connectAttr(worldRef+"."+limbMinVVAttr, rbScaleClp+".minR")
            cmds.setAttr(rbScaleClp+".maxR", 1000000)
            cmds.connectAttr(rbScaleClp+".outputR", rbBlendCB+".color1.color1R", force=True)
            cmds.connectAttr(rbBlendCB+".output.outputR", extraCtrlZero+".scaleY", force=True)
            cmds.connectAttr(rbBlendCB+".output.outputR", extraCtrlZero+".scaleZ", force=True)
            
            # update i
            i = i + 1
        
        locatorsGrp = cmds.group(bttm_Loc[0], top_Loc[0], mid_Loc[0], n=name+'_Loc_Grp')
        skinJntGrp = cmds.group(rb_Jnt, n=name+'_Jnt_Grp')
        finalSystemGrp = cmds.group(ribbon, locatorsGrp, skinJntGrp, n=name+'_RibbonSystem_Grp')
        
        #do the controller joints skin and the ribbon
        ribbonShape = cmds.listRelatives(ribbon, shapes=True)
        skin = cmds.skinCluster(drv_Jnt[0:3], ribbonShape, tsb=True, mi=2, dr=1)
        
        #skin presets for the ribbon (that's amazing!)
        if not horizontal:
            if numJoints == 3:
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][5]', tv=(drv_Jnt[2], 1))
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][4]', tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][3]', tv=[(drv_Jnt[2], 0.2), (drv_Jnt[1], 0.8)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][2]', tv=[(drv_Jnt[0], 0.2), (drv_Jnt[1], 0.8)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][1]', tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][0]', tv=(drv_Jnt[0], 1))

            elif numJoints == 5:
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][7]', tv=(drv_Jnt[2], 1))
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][6]', tv=[(drv_Jnt[2], 0.80), (drv_Jnt[1], 0.2)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][5]', tv=[(drv_Jnt[2], 0.5), (drv_Jnt[1], 0.5)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][4]', tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][3]', tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][2]', tv=[(drv_Jnt[0], 0.5), (drv_Jnt[1], 0.5)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][1]', tv=[(drv_Jnt[0], 0.8), (drv_Jnt[1], 0.2)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][0]', tv=(drv_Jnt[0], 1))
            elif numJoints == 7:
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][9]', tv=(drv_Jnt[2], 1))
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][8]', tv=[(drv_Jnt[2], 0.85), (drv_Jnt[1], 0.15)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][7]', tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][6]', tv=[(drv_Jnt[2], 0.35), (drv_Jnt[1], 0.65)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][5]', tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][4]', tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][3]', tv=[(drv_Jnt[0], 0.35), (drv_Jnt[1], 0.65)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][2]', tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][1]', tv=[(drv_Jnt[0], 0.85), (drv_Jnt[1], 0.15)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0:1][0]', tv=(drv_Jnt[0], 1))
        else:
            if numJoints == 3:
                cmds.skinPercent(skin[0], ribbon + '.cv[5][0:1]', tv=(drv_Jnt[2], 1))
                cmds.skinPercent(skin[0], ribbon + '.cv[4][0:1]', tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[3][0:1]', tv=[(drv_Jnt[2], 0.2), (drv_Jnt[1], 0.8)])
                cmds.skinPercent(skin[0], ribbon + '.cv[2][0:1]', tv=[(drv_Jnt[0], 0.2), (drv_Jnt[1], 0.8)])
                cmds.skinPercent(skin[0], ribbon + '.cv[1][0:1]', tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0][0:1]', tv=(drv_Jnt[0], 1))
            elif numJoints == 5:
                cmds.skinPercent(skin[0], ribbon + '.cv[7][0:1]', tv=(drv_Jnt[2], 1))
                cmds.skinPercent(skin[0], ribbon + '.cv[6][0:1]', tv=[(drv_Jnt[2], 0.80), (drv_Jnt[1], 0.2)])
                cmds.skinPercent(skin[0], ribbon + '.cv[5][0:1]', tv=[(drv_Jnt[2], 0.5), (drv_Jnt[1], 0.5)])
                cmds.skinPercent(skin[0], ribbon + '.cv[4][0:1]', tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[3][0:1]', tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[2][0:1]', tv=[(drv_Jnt[0], 0.5), (drv_Jnt[1], 0.5)])
                cmds.skinPercent(skin[0], ribbon + '.cv[1][0:1]', tv=[(drv_Jnt[0], 0.8), (drv_Jnt[1], 0.2)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0][0:1]', tv=(drv_Jnt[0], 1))
            elif numJoints == 7:
                cmds.skinPercent(skin[0], ribbon + '.cv[9][0:1]', tv=(drv_Jnt[2], 1))
                cmds.skinPercent(skin[0], ribbon + '.cv[8][0:1]', tv=[(drv_Jnt[2], 0.85), (drv_Jnt[1], 0.15)])
                cmds.skinPercent(skin[0], ribbon + '.cv[7][0:1]', tv=[(drv_Jnt[2], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[6][0:1]', tv=[(drv_Jnt[2], 0.35), (drv_Jnt[1], 0.65)])
                cmds.skinPercent(skin[0], ribbon + '.cv[5][0:1]', tv=[(drv_Jnt[2], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[4][0:1]', tv=[(drv_Jnt[0], 0.25), (drv_Jnt[1], 0.75)])
                cmds.skinPercent(skin[0], ribbon + '.cv[3][0:1]', tv=[(drv_Jnt[0], 0.35), (drv_Jnt[1], 0.65)])
                cmds.skinPercent(skin[0], ribbon + '.cv[2][0:1]', tv=[(drv_Jnt[0], 0.6), (drv_Jnt[1], 0.4)])
                cmds.skinPercent(skin[0], ribbon + '.cv[1][0:1]', tv=[(drv_Jnt[0], 0.85), (drv_Jnt[1], 0.15)])
                cmds.skinPercent(skin[0], ribbon + '.cv[0][0:1]', tv=(drv_Jnt[0], 1))
        constr = []
        if guias:
            top = guias[0]
            bottom = guias[1]
            constr.append(cmds.parentConstraint(top, bttm_Loc[0], mo=False, name=bttm_Loc[0]+"_ParentConstraint"))
            constr.append(cmds.parentConstraint(bottom, top_Loc[0], mo=False, name=top_Loc[0]+"_ParentConstraint"))
        
        #fix orientation issues
        cmds.delete(ori)
        cmds.orientConstraint(bttm_Loc[0], aux_Jnt[0], weight=0.5, mo=True, name=aux_Jnt[0]+"_OrientConstraint")
        
        #fix loc_Grp scale
        if guias:
            from math import sqrt, pow
            auxLoc1 = cmds.spaceLocator(name='auxLoc1')[0]
            auxLoc2 = cmds.spaceLocator(name='auxLoc2')[0]
            cmds.delete(cmds.parentConstraint(top, auxLoc1, mo=False, w=1))
            cmds.delete(cmds.parentConstraint(bottom, auxLoc2, mo=False, w=1))
            a = cmds.xform(auxLoc1, ws=True, translation=True, q=True)
            b = cmds.xform(auxLoc2, ws=True, translation=True, q=True)
            
            dist = sqrt(pow(a[0]-b[0], 2.0)+pow(a[1]-b[1], 2.0)+pow(a[2]-b[2], 2.0))
            scale = dist/float(numJoints)
            
            cmds.setAttr(locatorsGrp+'.s', scale, scale, scale)
        
            cmds.delete(auxLoc1, auxLoc2)
        
        # baseTwist:
        if not upCtrl == None:
            bttm_LocGrp = cmds.group(bttm_Loc[2], name=bttm_Loc[2]+"_Grp")
            bttm_LocPos = cmds.xform(bttm_Loc[0], query=True, worldSpace=True, translation=True)
            cmds.move(bttm_LocPos[0], bttm_LocPos[1], bttm_LocPos[2], bttm_LocGrp+".scalePivot", bttm_LocGrp+".rotatePivot", absolute=True)
            cmds.connectAttr(upCtrl+".baseTwist", bttm_LocGrp+".rotateZ", force=True)
        
        #updating values
        cmds.setAttr(rbScaleMD+".input2X", cmds.getAttr(curveInfoNode+".arcLength"))
        for jnt in rb_Jnt:
            rbAddScalePMA = jnt.replace("_Jnt", "_AddScale_PMA")
            cmds.setAttr(rbAddScalePMA+".input1D[0]", 1-cmds.getAttr(rbAddScalePMA+".input1D[1]"))

        #change renderStats
        ribbonShape = cmds.listRelatives(ribbon, s=True, f=True)[0]
        
        cmds.setAttr(ribbonShape+'.castsShadows', 0)
        cmds.setAttr(ribbonShape+'.receiveShadows', 0)
        cmds.setAttr(ribbonShape+'.motionBlur', 0)
        cmds.setAttr(ribbonShape+'.primaryVisibility', 0)
        cmds.setAttr(ribbonShape+'.smoothShading', 0)
        cmds.setAttr(ribbonShape+'.visibleInReflections', 0)
        cmds.setAttr(ribbonShape+'.visibleInRefractions', 0)
        cmds.setAttr(ribbonShape+'.doubleSided', 1)
        
        retDict['name'] = name
        retDict['locsList'] = [top_Loc[0], mid_Loc[0], bttm_Loc[0]]
        retDict['skinJointsList'] =  rb_Jnt
        retDict['scaleGrp'] = locatorsGrp
        retDict['finalGrp'] = finalSystemGrp
        retDict['middleCtrl'] = mid_Ctrl
        retDict['constraints'] = constr
        retDict['bendGrpList'] = [top_Loc[0], bttm_Loc[0]]
        retDict['extraCtrlGrp'] = extraCtrlGrp
        retDict['extraCtrlList'] = extraCtrlList
        retDict['rbScaleMD'] = rbScaleMD
        retDict['rbNormalizeMD'] = rbNormalizeMD
        cmds.setAttr(finalSystemGrp+'.v', v)
        return retDict
예제 #40
0
def nk_createRibbonSpine(prefix='CHAR_SIDE_LIMB', type='offset'):
 
    ##+++++++++++++++++++++++++++++++++##
    ##+++++++nk_createRibbonSpine++++++##
    ##+++++++++++++++++++++++++++++++++##
 
     
    #Check the type of ribbon
    if type == 'basic':
        suffix = 'rbnBasic'
 
    if type =='offset':
        suffix = 'rbnOffset'
     
     
    #create group for ribbon rig
    ribbonRigGrp = mc.group(em=True, n=(prefix + '_' + suffix + '_rig_grp'))
    # ribbonRigGrp = mc.group(em=True, n=(prefix))
 
    # Create nurbs plane
    ribbonPlane = mc.nurbsPlane (n=(prefix + '_' + suffix + 'Plane'), p=[0, 0, 0], ax= [0, 0 ,1], w=1 ,lr=5 ,d=3, u=1, v=5, ch=0)
    ribbonPlaneShape = mc.listRelatives(ribbonPlane, c=True, s=True) #get shape node
     
    # CLEANUP: Parent plane to rigGrp and turn off inheritsTransforms
    mc.parent(ribbonPlane[0], ribbonRigGrp)
    mc.setAttr('{ribbonPlane}.inheritsTransform'.format(ribbonPlane=ribbonPlane[0]),0, lock=True)
    #mc.setAttr('{ribbonPlane}.inheritsTransform'.format(ribbonPlane=ribbonPlane[0]), lock=True)
     
 
    ## rebuildSurface
    mc.rebuildSurface(ribbonPlane[0], rpo=1, rt=0, end=1, kr=0, kcp=0, kc=0, su=1, du=1, sv=0, dv=3, tol=0.01, dir=0)
     
    # Create follicles * 5
     
    ##Create an empty group for the follicles
    folGroup = mc.group(em=True, n=(prefix + '_' + suffix + '_follicleGrp'))
         
    # CLEANUP: Parent follicleGrp to rigGrp
    mc.parent(folGroup, ribbonRigGrp)
     
    ##Create a list for the follicles
    folList = []
 
    ##Create the follicles and ribbon joints
    for f in range(5):
        follicle = mc.createNode('follicle', n=('{prefix}_{suffix}_FollicleShape_{number}'.format(prefix=prefix, suffix=suffix ,number=(f+1))))
        print follicle
        follicleTransform = mc.listRelatives(follicle,  p=True) #get transform node
 
        ribbonJnt = mc.joint(n='{prefix}_{suffix}_jnt_{f}'.format(prefix=prefix,suffix=suffix,f=f+1))#create joint
        grp=mc.group(n=(ribbonJnt+'_offsetGrp'))#grp joint
 
        ## connect folliclesShapes to the plane
        mc.connectAttr(('{ribbonPlaneShape}.local'.format(ribbonPlaneShape=ribbonPlaneShape[0])) ,('{follicle}.inputSurface'.format(follicle=follicle)))
        mc.connectAttr(('{ribbonPlaneShape}.worldMatrix[0]'.format(ribbonPlaneShape=ribbonPlaneShape[0])) ,('{follicle}.inputWorldMatrix'.format(follicle=follicle)))
        ## connect follicleShapes to follicleTransform
        mc.connectAttr((follicle+'.outTranslate'), (follicleTransform[0]+'.translate') )
        mc.connectAttr((follicle+'.outRotate'), (follicleTransform[0]+'.rotate') )
 
        ##position the follicles along the plane
        mc.setAttr((follicle+'.parameterU'), 0.5)
        vSpanHeight = ((f+1.0)/5.0) - .1
        mc.setAttr((follicle+'.parameterV'), vSpanHeight)
         
        #Turn off inherit transforms on the follicles
        mc.setAttr('{follicleTransform}.inheritsTransform'.format(follicleTransform=follicleTransform[0]),0, lock=True)
         
        ##parent the follicle to the group and add to lists
        mc.parent(follicleTransform[0], folGroup)
        folList.append(follicle)
         
    # Create ribbon bind joints and setup aim constraints
    mc.select(cl=True)
 
    bindBaseJnt = mc.joint(p=(0,-2.5,0), o=(0,0,90), rad=2, n=(prefix+'_'+suffix+'_base_bind_01'))
    mc.joint(p=(0,-2,0), n=(prefix+'_ribbon_base_bind_02'))
 
    mc.select(cl=True)
 
    bindTipJnt = mc.joint(p=(0,2.5,0), o=(0,0,-90), rad=2, n=(prefix+'_'+suffix+'_tip_bind_01'))
    mc.joint(p=(0,2,0), n=(prefix+'_ribbon_tip_bind_02'))
 
    mc.select(cl=True)
 
 
    bindMidJnt = mc.joint(p=(0,0,0), o=(0,0,0), rad=2, n=(prefix+'_'+suffix+'_mid_bind_01'))
    mc.select(cl=True)
 
    # create control Locators and parent bindJoint to aimLocator
    ##baseLocators
    basePosLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_base_pos_loc'))
    baseUpLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_base_up_loc'))
    baseAimLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_base_aim_loc'))
 
    mc.parent(baseUpLoc,baseAimLoc,basePosLoc )#parent locators
    mc.xform(basePosLoc, t=(0,-2.5,0))#move locator to base position
    mc.xform(baseUpLoc, ws=True, t=(0,-2.5,2))# offset Up locator in Z
    mc.parent(bindBaseJnt,baseAimLoc)#parent jnt to aim locator
     
     
    #CLEANUP: startPosLoc to rigGrp
    mc.parent(basePosLoc, ribbonRigGrp)
     
    ##midLocators
    midPosLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_mid_pos_loc'))
    midUpLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_mid_up_loc'))
    midAimLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_mid_aim_loc'))
 
    mc.parent(midUpLoc,midAimLoc,midPosLoc )#parent locators
    mc.xform(midUpLoc, ws=True, t=(0,0,2))# offset Up locator in Z
    mc.parent(bindMidJnt,midAimLoc)#parent jnt to aim locator
     
    mc.parent(midPosLoc, ribbonRigGrp)
     
    ##tipLocators
    tipPosLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_tip_pos_loc'))
    tipUpLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_tip_up_loc'))
    tipAimLoc = mc.spaceLocator(n=(prefix+'_'+suffix+'_tip_aim_loc'))
 
    mc.parent(tipUpLoc,tipAimLoc,tipPosLoc)#parent locators
    mc.xform(tipPosLoc, t=(0,2.5,0))#move locator to tip position
    mc.xform(tipUpLoc, ws=True, t=(0,2.5,2))# offset Up locator in Z
    mc.parent(bindTipJnt,tipAimLoc)#parent jnt to aim locator
     
    #CLEANUP: tipPosLoc to rigGrp 
    mc.parent(tipPosLoc, ribbonRigGrp)
     
    #setup aim relationsips
    ##basic
    if type=='basic':
        ##baseAimLoc > tipPos##
        mc.aimConstraint(tipPosLoc[0],baseAimLoc[0], aim=(0,1,0), u=(0,0,1), wut='object', wuo=baseUpLoc[0])
        ##tipAimLoc > basePos##
        mc.aimConstraint(basePosLoc[0],tipAimLoc[0], aim=(0,-1,0), u=(0,0,1), wut='object', wuo=tipUpLoc[0])
        ##midAimLoc > tipPos##
        mc.aimConstraint(tipPosLoc[0],midAimLoc[0], aim=(0,1,0), u=(0,0,1), wut='object', wuo=midUpLoc[0])
         
        # midPosLoc to follow both base and tip
        mc.pointConstraint(basePosLoc[0],tipPosLoc[0],midPosLoc[0], mo=False)
        # midPosAim to follow both base and tip Aim
        mc.pointConstraint(baseUpLoc[0],tipUpLoc[0],midUpLoc[0], mo=False)
         
    if type=='offset':
         
        ##baseAimLoc > midBindJoint##
        mc.aimConstraint(bindMidJnt,baseAimLoc[0], aim=(0,1,0), u=(0,0,1), wut='object', wuo=baseUpLoc[0])
        #tipAimLoc > midBindJoint##
        mc.aimConstraint(bindMidJnt,tipAimLoc[0], aim=(0,-1,0), u=(0,0,1), wut='object', wuo=tipUpLoc[0])
        ##midAimLoc > tipPos##
        mc.aimConstraint(tipPosLoc[0],midAimLoc[0], aim=(0,1,0), u=(0,0,1), wut='object', wuo=midUpLoc[0])
         
        # midPosLoc to follow both base and tip
        mc.pointConstraint(basePosLoc[0],tipPosLoc[0],midPosLoc[0], mo=False)
        # midPosAim to follow both base and tip Aim
        mc.pointConstraint(baseUpLoc[0],tipUpLoc[0],midUpLoc[0], mo=False)
 
    # Bind skin 
    mc.select(cl=True)
    print bindBaseJnt 
    print bindMidJnt 
    print bindTipJnt
    mc.skinCluster(bindBaseJnt,bindMidJnt,bindTipJnt,ribbonPlane, n=(prefix+'_'+suffix+'_skinCluster'), tsb=True, ih=True, bm=0, sm=0, nw=1, wd=0, mi=3, omi=False, dr=4)
예제 #41
0
    def create(self):
        sGrp = transforms.createTransformNode(
            naming.oName(sType='grp',
                         sSide=self._sSide,
                         sPart='%s%sRig' % (self._sPart, self._sName),
                         iIndex=self._iIndex).sName,
            lLockHideAttrs=[
                'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
            ],
            sParent=self._sConnectInJnt)
        sGrpCtrl = transforms.createTransformNode(
            naming.oName(sType='grp',
                         sSide=self._sSide,
                         sPart='%s%sCtrl' % (self._sPart, self._sName),
                         iIndex=self._iIndex).sName,
            lLockHideAttrs=[
                'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
            ],
            sParent=self._sConnectInCtrl)
        sGrpNode = transforms.createTransformNode(
            naming.oName(sType='grp',
                         sSide=self._sSide,
                         sPart='%s%sNode' % (self._sPart, self._sName),
                         iIndex=self._iIndex).sName,
            lLockHideAttrs=[
                'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
            ],
            sParent=self._sGrpNode)

        lJnts = []
        for i, sBpJnt in enumerate(self._lBpJnts):
            oJntName = naming.oName(sBpJnt)
            oJntName.sType = 'jnt'
            oJntName.sPart = '%s%s' % (oJntName.sPart, self._sName)
            sJnt = joints.createJntOnExistingNode(sBpJnt,
                                                  sBpJnt,
                                                  oJntName.sName,
                                                  sParent=sGrp)
            lJnts.append(sJnt)

        ## create ribbon surface

        ## if no control bpjnt, create controls, cluster ribbon
        lCtrls = []
        if not self._lBpCtrls:
            sRibbon = surfaces.createRibbonFromNodes(naming.oName(
                sType='surface',
                sSide=self._sSide,
                sPart='%s%s' % (self._sPart, self._sName),
                iIndex=self._iIndex).sName,
                                                     lJnts,
                                                     bAuto=True,
                                                     fWidth=2,
                                                     bNormalize=False,
                                                     sParent=sGrpNode)
            cmds.setAttr('%s.v' % sRibbon, 0)
            lCls = surfaces.clusterSurface(sRibbon, sUV='u')
            cmds.rebuildSurface(sRibbon,
                                ch=True,
                                su=len(lJnts) - 1,
                                sv=1,
                                dv=3,
                                du=3)
            for i, sCls in enumerate(lCls):
                oCtrl = controls.create('%s%s' % (self._sPart, self._sName),
                                        sSide=self._sSide,
                                        iIndex=i,
                                        iStacks=self._iStacks,
                                        bSub=self._bSub,
                                        sParent=sGrpCtrl,
                                        sPos=sCls,
                                        sShape='cube',
                                        fSize=4,
                                        lLockHideAttrs=self._lLockHideAttrs)
                cmds.parent(sCls, oCtrl.sOutput)
                lCtrls.append(oCtrl.sName)
        else:
            sRibbon = surfaces.createRibbonFromNodes(naming.oName(
                sType='surface',
                sSide=self._sSide,
                sPart='%s%s' % (self._sPart, self._sName),
                iIndex=self._iIndex).sName,
                                                     self._lBpCtrls,
                                                     bAuto=True,
                                                     fWidth=2,
                                                     bNormalize=False,
                                                     sParent=sGrpNode)
            cmds.setAttr('%s.v' % sRibbon, 0)
            lCls = surfaces.clusterSurface(sRibbon, sUV='u')
            cmds.rebuildSurface(sRibbon,
                                ch=True,
                                su=len(lJnts) - 1,
                                sv=1,
                                dv=3,
                                du=3)
            for i, sCls in enumerate(lCls):
                oJntName = naming.oName(self._lBpCtrls[i])
                iRotateOrder = cmds.getAttr('%s.ro' % self._lBpCtrls[i])
                oCtrl = controls.create('%s%s' % (oJntName.sPart, self._sName),
                                        sSide=oJntName.sSide,
                                        iIndex=oJntName.iIndex,
                                        iStacks=self._iStacks,
                                        bSub=self._bSub,
                                        sParent=sGrpCtrl,
                                        iRotateOrder=iRotateOrder,
                                        sPos=self._lBpCtrls[i],
                                        sShape='cube',
                                        fSize=4,
                                        lLockHideAttrs=self._lLockHideAttrs)
                cmds.parent(sCls, oCtrl.sOutput)
                lCtrls.append(oCtrl.sName)

        ### attach joints
        sGrpFollicle, lFollicles = constraints.follicleConstraint(
            sRibbon, lJnts, bMaintainOffset=True)
        cmds.parent(sGrpFollicle, sGrpNode)

        #### control connect out node
        sConnectOutCtrl = transforms.createTransformNode(naming.oName(
            sType='grp',
            sSide=self._sSide,
            sPart='%s%sRigConnectOutCtrl' % (self._sPart, self._sName),
            iIndex=self._iIndex).sName,
                                                         lLockHideAttrs=[
                                                             'tx', 'ty', 'tz',
                                                             'rx', 'ry', 'rz',
                                                             'sx', 'sy', 'sz',
                                                             'v'
                                                         ],
                                                         sParent=sGrpCtrl,
                                                         bVis=True)
        constraints.constraint([lJnts[-1], sConnectOutCtrl],
                               sType='parent',
                               bForce=True,
                               bMaintainOffset=True)

        #### control root connect out node
        sConnectOutRootCtrl = transforms.createTransformNode(naming.oName(
            sType='grp',
            sSide=self._sSide,
            sPart='%s%sRigConnectOutRootCtrl' % (self._sPart, self._sName),
            iIndex=self._iIndex).sName,
                                                             lLockHideAttrs=[
                                                                 'tx', 'ty',
                                                                 'tz', 'rx',
                                                                 'ry', 'rz',
                                                                 'sx', 'sy',
                                                                 'sz', 'v'
                                                             ],
                                                             sParent=sGrpCtrl,
                                                             bVis=True)
        constraints.constraint([lJnts[0], sConnectOutRootCtrl],
                               sType='parent',
                               bForce=True,
                               bMaintainOffset=True)

        ## write rig info
        sString_lJnts = self._convertListToString(lJnts)
        sString_lCtrls = self._convertListToString(lCtrls)
        lRigInfo = [
            'ribbonRig', self._sConnectInJnt, self._sConnectInCtrl, lJnts[-1],
            sConnectOutCtrl, sConnectOutRootCtrl, sString_lJnts,
            sString_lCtrls, sRibbon, sGrpCtrl, sGrp
        ]
        lAttrs = [
            'sModuleType', 'sConnectInJnt', 'sConnectInCtrl', 'sConnectOutJnt',
            'sConnectOutCtrl', 'sConnectOutRootCtrl', 'lJnts', 'lCtrls',
            'sRibbon', 'sGrpCtrl', 'sModuleNode'
        ]
        self._writeRigInfo(sGrp, lRigInfo, lAttrs)

        self._getRigInfo(sGrp)
예제 #42
0
파일: spine.py 프로젝트: jonntd/glTools
def buildRibbonSpine(startJoint,
                     endJoint,
                     ribbonJoints,
                     spans=0,
                     ikSwitchCtrl='',
                     ikSwitchAttr='spineIk',
                     ctrlScale=1.0,
                     prefix='cn_spine'):
    '''
	'''
    # ==========
    # - Checks -
    # ==========

    # Ribbon Joints
    for jnt in ribbonJoints:
        if not mc.objExists(jnt):
            raise Exception('Ribbon joint "' + jnt + '" does not exist!')

    # ====================
    # - Build Spine Base -
    # ====================

    # Get Joint List
    spineJnts = glTools.utils.joint.getJointList(startJoint, endJoint)

    spine = build(startJoint, endJoint, ikSwitchCtrl, ikSwitchAttr, ctrlScale,
                  prefix)
    spine_module = spine[0]
    spine_attach = spine[1]
    spine_rig_grp = prefix + '_rig_grp'

    # =========================
    # - Process Ribbon Joints -
    # =========================

    for ribbonJoint in ribbonJoints:

        # Delete incoming connections
        mc.delete(mc.listConnections(ribbonJoint, s=True, d=False))

    # ======================
    # - Build Spine Ribbon -
    # ======================

    locList = []
    lfLocList = []
    rtLocList = []

    # Create Ribbon Locators
    for i in range(len(spineJnts)):

        pt = glTools.utils.base.getPosition(spineJnts[i])
        strInd = glTools.utils.stringUtils.alphaIndex(i)
        loc = mc.spaceLocator(p=(0, 0, 0), n=prefix + strInd + '_loc')[0]
        lfLoc = mc.spaceLocator(p=(0.5, 0, 0),
                                n=prefix + '_lf' + strInd + '_loc')[0]
        rtLoc = mc.spaceLocator(p=(-0.5, 0, 0),
                                n=prefix + '_rt' + strInd + '_loc')[0]

        # Parent and position locators
        mc.parent([lfLoc, rtLoc], loc)
        mc.move(pt[0], pt[1], pt[2], loc, ws=True, a=True)
        mc.parent(loc, spineJnts[i])
        mc.setAttr(loc + '.v', 0)

        # Append Lists
        locList.append(loc)
        lfLocList.append(lfLoc)
        rtLocList.append(rtLoc)

    # Create Loft Curves
    lfCurve = glTools.utils.curve.createFromLocators(lfLocList,
                                                     degree=1,
                                                     attach=True,
                                                     prefix=prefix + 'A')
    rtCurve = glTools.utils.curve.createFromLocators(rtLocList,
                                                     degree=1,
                                                     attach=True,
                                                     prefix=prefix + 'B')
    lfCurveShape = mc.listRelatives(lfCurve, s=True, pa=True)[0]
    rtCurveShape = mc.listRelatives(rtCurve, s=True, pa=True)[0]
    glTools.utils.shape.createIntermediate(lfCurveShape)
    glTools.utils.shape.createIntermediate(rtCurveShape)

    # Rebuild Loft Curves
    if not spans: spans = len(spineJnts) - 1
    lfRebuildCrv = mc.rebuildCurve(lfCurve,
                                   ch=1,
                                   rpo=1,
                                   rt=0,
                                   end=1,
                                   kr=0,
                                   kcp=0,
                                   kep=1,
                                   kt=1,
                                   s=spans,
                                   d=3,
                                   tol=0)
    rtRebuildCrv = mc.rebuildCurve(rtCurve,
                                   ch=1,
                                   rpo=1,
                                   rt=0,
                                   end=1,
                                   kr=0,
                                   kcp=0,
                                   kep=1,
                                   kt=1,
                                   s=spans,
                                   d=3,
                                   tol=0)
    lfRebuildCrv = mc.rename(lfRebuildCrv[1], prefix + 'A_rebuildCurve')
    rtRebuildCrv = mc.rename(rtRebuildCrv[1], prefix + 'B_rebuildCurve')

    # Generate Loft Surface
    loft = mc.loft([lfCurve, rtCurve], d=1, n=prefix + '_surface')
    loftNode = mc.rename(loft[1], prefix + '_loft')
    spineSurface = loft[0]
    rebuildSrf = mc.rebuildSurface(spineSurface,
                                   ch=True,
                                   rpo=True,
                                   end=True,
                                   rt=0,
                                   kr=0,
                                   kcp=True,
                                   dir=2,
                                   du=1,
                                   dv=3)
    rebuildSrf = mc.rename(rebuildSrf[1], prefix + '_rebuildSurface')

    # Parent to rig group
    ribbonParts = [lfCurve, rtCurve, spineSurface]
    for ribbonPart in ribbonParts:
        mc.setAttr(ribbonPart + '.v', 0)
        mc.parent(ribbonPart, spine_rig_grp)

    # ========================
    # - Attach Ribbon Joints -
    # ========================

    inc = 1.0 / (len(ribbonJoints) - 1)
    ribbonJointGrps = []
    for i in range(len(ribbonJoints)):

        # Create Joint Buffer Group
        strInd = glTools.utils.stringUtils.alphaIndex(i)
        prefix = glTools.utils.stringUtils.stripSuffix(ribbonJoints[i])
        mc.select(cl=True)
        ribbonJointGrp = mc.joint(n=prefix + 'ConA_jnt')
        mc.delete(mc.pointConstraint(ribbonJoints[i], ribbonJointGrp))
        ribbonJointGrps.append(ribbonJointGrp)

        # Attach Joint Buffer Group
        glTools.utils.attach.attachToSurface(spineSurface,
                                             ribbonJointGrp,
                                             useClosestPoint=True,
                                             orient=True,
                                             uAxis='y',
                                             vAxis='x',
                                             uAttr='uCoord',
                                             vAttr='vCoord',
                                             alignTo='v',
                                             prefix=prefix + strInd)

        # Parent Ribbon Joint
        mc.parent(ribbonJoints[i], ribbonJointGrp)
        mc.parent(ribbonJointGrp, spine_rig_grp)

        # Connect Module Scale
        mc.connectAttr(spine_module + '.uniformScale',
                       ribbonJoints[i] + '.sx',
                       f=True)
        mc.connectAttr(spine_module + '.uniformScale',
                       ribbonJoints[i] + '.sy',
                       f=True)
        mc.connectAttr(spine_module + '.uniformScale',
                       ribbonJoints[i] + '.sz',
                       f=True)

    # ======================
    # - Set Channel States -
    # ======================

    chStateUtil = glTools.utils.channelState.ChannelState()
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=locList)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=lfLocList)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=rtLocList)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[lfCurve, rtCurve, spineSurface])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=ribbonJoints)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=ribbonJointGrps)

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

    return [spine_module, spine_attach]
예제 #43
0
def buildRibbonSpine(startJoint,endJoint,ribbonJoints,spans=0,ikSwitchCtrl='',ikSwitchAttr='spineIk',ctrlScale=1.0,prefix='cn_spine'):
	'''
	'''
	# ==========
	# - Checks -
	# ==========
	
	# Ribbon Joints
	for jnt in ribbonJoints:
		if not mc.objExists(jnt):
			raise Exception('Ribbon joint "'+jnt+'" does not exist!')
		
	# ====================
	# - Build Spine Base -
	# ====================
	
	# Get Joint List
	spineJnts = glTools.utils.joint.getJointList(startJoint,endJoint)
	
	spine = build(startJoint,endJoint,ikSwitchCtrl,ikSwitchAttr,ctrlScale,prefix)
	spine_module = spine[0]
	spine_attach = spine[1]
	spine_rig_grp = prefix+'_rig_grp'
	
	# =========================
	# - Process Ribbon Joints -
	# =========================
	
	for ribbonJoint in ribbonJoints:
		
		# Delete incoming connections
		mc.delete(mc.listConnections(ribbonJoint,s=True,d=False))
	
	# ======================
	# - Build Spine Ribbon -
	# ======================
	
	locList = []
	lfLocList = []
	rtLocList = []
	
	# Create Ribbon Locators
	for i in range(len(spineJnts)):
		
		pt = glTools.utils.base.getPosition(spineJnts[i])
		strInd = glTools.utils.stringUtils.alphaIndex(i)
		loc = mc.spaceLocator(p=(0,0,0),n=prefix+strInd+'_loc')[0]
		lfLoc = mc.spaceLocator(p=(0.5,0,0),n=prefix+'_lf'+strInd+'_loc')[0]
		rtLoc = mc.spaceLocator(p=(-0.5,0,0),n=prefix+'_rt'+strInd+'_loc')[0]
		
		# Parent and position locators
		mc.parent([lfLoc,rtLoc],loc)
		mc.move(pt[0],pt[1],pt[2],loc,ws=True,a=True)
		mc.parent(loc,spineJnts[i])
		mc.setAttr(loc+'.v',0)
		
		# Append Lists
		locList.append(loc)
		lfLocList.append(lfLoc)
		rtLocList.append(rtLoc)
	
	# Create Loft Curves
	lfCurve = glTools.utils.curve.createFromLocators(lfLocList,degree=1,attach=True,prefix=prefix+'A')
	rtCurve = glTools.utils.curve.createFromLocators(rtLocList,degree=1,attach=True,prefix=prefix+'B')
	lfCurveShape = mc.listRelatives(lfCurve,s=True,pa=True)[0]
	rtCurveShape = mc.listRelatives(rtCurve,s=True,pa=True)[0]
	glTools.utils.shape.createIntermediate(lfCurveShape)
	glTools.utils.shape.createIntermediate(rtCurveShape)
	
	# Rebuild Loft Curves
	if not spans: spans = len(spineJnts) - 1
	lfRebuildCrv = mc.rebuildCurve(lfCurve,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=spans,d=3,tol=0)
	rtRebuildCrv = mc.rebuildCurve(rtCurve,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=spans,d=3,tol=0)
	lfRebuildCrv = mc.rename(lfRebuildCrv[1],prefix+'A_rebuildCurve')
	rtRebuildCrv = mc.rename(rtRebuildCrv[1],prefix+'B_rebuildCurve')
	
	# Generate Loft Surface
	loft = mc.loft([lfCurve,rtCurve],d=1,n=prefix+'_surface')
	loftNode = mc.rename(loft[1],prefix+'_loft')
	spineSurface = loft[0]
	rebuildSrf = mc.rebuildSurface(spineSurface,ch=True,rpo=True,end=True,rt=0,kr=0,kcp=True,dir=2,du=1,dv=3)
	rebuildSrf = mc.rename(rebuildSrf[1],prefix+'_rebuildSurface')
	
	# Parent to rig group
	ribbonParts = [lfCurve,rtCurve,spineSurface]
	for ribbonPart in ribbonParts:
		mc.setAttr(ribbonPart+'.v',0)
		mc.parent(ribbonPart,spine_rig_grp)
	
	# ========================
	# - Attach Ribbon Joints -
	# ========================
	
	inc = 1.0 / (len(ribbonJoints) - 1)
	ribbonJointGrps = []
	for i in range(len(ribbonJoints)):
		
		# Create Joint Buffer Group
		strInd = glTools.utils.stringUtils.alphaIndex(i)
		prefix = glTools.utils.stringUtils.stripSuffix(ribbonJoints[i])
		mc.select(cl=True)
		ribbonJointGrp = mc.joint(n=prefix+'ConA_jnt')
		mc.delete(mc.pointConstraint(ribbonJoints[i],ribbonJointGrp))
		ribbonJointGrps.append(ribbonJointGrp)
		
		# Attach Joint Buffer Group
		glTools.utils.attach.attachToSurface(spineSurface,ribbonJointGrp,useClosestPoint=True,orient=True,uAxis='y',vAxis='x',uAttr='uCoord',vAttr='vCoord',alignTo='v',prefix=prefix+strInd)
		
		# Parent Ribbon Joint
		mc.parent(ribbonJoints[i],ribbonJointGrp)
		mc.parent(ribbonJointGrp,spine_rig_grp)
		
		# Connect Module Scale
		mc.connectAttr(spine_module+'.uniformScale',ribbonJoints[i]+'.sx',f=True)
		mc.connectAttr(spine_module+'.uniformScale',ribbonJoints[i]+'.sy',f=True)
		mc.connectAttr(spine_module+'.uniformScale',ribbonJoints[i]+'.sz',f=True)
	
	# ======================
	# - Set Channel States -
	# ======================
	
	chStateUtil = glTools.utils.channelState.ChannelState()
	chStateUtil.setFlags([2,2,2,2,2,2,2,2,2,1],objectList=locList)
	chStateUtil.setFlags([2,2,2,2,2,2,2,2,2,1],objectList=lfLocList)
	chStateUtil.setFlags([2,2,2,2,2,2,2,2,2,1],objectList=rtLocList)
	chStateUtil.setFlags([2,2,2,2,2,2,2,2,2,1],objectList=[lfCurve,rtCurve,spineSurface])
	chStateUtil.setFlags([2,2,2,2,2,2,2,2,2,1],objectList=ribbonJoints)
	chStateUtil.setFlags([2,2,2,2,2,2,2,2,2,1],objectList=ribbonJointGrps)
	
	# =================
	# - Return Result -
	# =================
	
	return [spine_module,spine_attach]
예제 #44
0
cost - pos
eyePnt1 = pupilPoints[0]
eyePnt2 = pupilPoints[1]
virtualPnt = np.array(mc.xform('%s.vtx[0]' % vi, q=1, ws=1, t=1))
surf = mirror
spans = range(4, 20, 3)
bMirror = mirror
for i in spans:
    bMirror = mc.duplicate(bMirror, n='%sSpan%s' % (mirror, i))[0]
    mc.rebuildSurface(bMirror,
                      ch=1,
                      rpo=1,
                      rt=0,
                      end=1,
                      kr=0,
                      kcp=0,
                      kc=0,
                      su=i,
                      sv=i,
                      tol=9.223372037e+018,
                      fr=0,
                      dir=2)
    remap = mapImageInfluences(bMirror, screen, pupilPoints, virtualImage)
    bMirror = optimizeMirrorForImage(bMirror,
                                     screen,
                                     pupilPoints,
                                     virtualImage,
                                     remap,
                                     iterations=100 * i)

spans = range(7, 20, 9)
예제 #45
0
def rebuild(surface,
            spansU=0,
            spansV=0,
            fullRebuildU=False,
            fullRebuildV=False,
            rebuildUfirst=True,
            replaceOrig=False):
    """
    Do brute force surface rebuild for even parameterization
    @param surface: Nurbs surface to rebuild
    @type surface: str
    @param spansU: Number of spans along U. If 0, keep original value.
    @type spansU: int
    @param spansV: Number of spans along V. If 0, keep original value.
    @type spansV: int
    @param replaceOrig: Replace original surface, or create new rebuilt surface.
    @type replaceOrig: bool
    """
    # ==========
    # - Checks -
    # ==========

    # Check surface
    if not isSurface(surface):
        raise Exception('Object "' + surface + '" is not a valid surface!')

    # Check spans
    if not spansU: spansU = cmds.getAttr(surface + '.spansU')
    if not spansV: spansV = cmds.getAttr(surface + '.spansV')

    # =============
    # - Rebuild U -
    # =============

    # Get V range
    if rebuildUfirst:
        dir = 'u'
        opp = 'v'
        spans = spansU
        min = cmds.getAttr(surface + '.minValueV')
        max = cmds.getAttr(surface + '.maxValueV')
    else:
        dir = 'v'
        opp = 'u'
        spans = spansV
        min = cmds.getAttr(surface + '.minValueU')
        max = cmds.getAttr(surface + '.maxValueU')
    val = min + (max - min) * 0.5

    # Caluculate surface length
    iso_crv = cmds.duplicateCurve(surface + '.' + opp + '[' + str(val) + ']',
                                  ch=0,
                                  rn=0,
                                  local=0)[0]
    iso_len = cmds.arclen(iso_crv)
    iso_inc = iso_len / spans

    # Get spaced isoparm list
    curveFn = glTools.utils.curve.getCurveFn(iso_crv)
    iso_list = [
        surface + '.' + dir + '[' +
        str(curveFn.findParamFromLength(iso_inc * i)) + ']'
        for i in range(spans + 1)
    ]
    cmds.delete(iso_crv)

    # Check full rebuild
    if fullRebuildV:
        # Extract isoparm curves
        iso_crv_list = [
            cmds.duplicateCurve(iso, ch=False, rn=False, local=False)[0]
            for iso in iso_list
        ]
        # Rebuild isoparm curves
        for iso_crv in iso_crv_list:
            cmds.rebuildCurve(iso_crv,
                              ch=False,
                              rpo=True,
                              rt=0,
                              end=1,
                              kr=0,
                              kcp=0,
                              kep=1,
                              kt=1,
                              s=0,
                              d=3,
                              tol=0)
        # Loft final surface
        int_surface = cmds.loft(iso_crv_list,
                                ch=0,
                                u=1,
                                c=0,
                                ar=1,
                                d=3,
                                ss=1,
                                rn=0,
                                po=0,
                                rsn=True)[0]
        # Delete intermediate curves
        cmds.delete(iso_crv_list)
    else:
        # Loft intermediate surface
        int_surface = cmds.loft(iso_list,
                                ch=0,
                                u=1,
                                c=0,
                                ar=1,
                                d=3,
                                ss=1,
                                rn=0,
                                po=0,
                                rsn=True)[0]

    # =============
    # - Rebuild V -
    # =============

    # Get V range (intermediate surface)
    if rebuildUfirst:
        dir = 'u'
        opp = 'v'
        spans = spansV
        min = cmds.getAttr(int_surface + '.minValueU')
        max = cmds.getAttr(int_surface + '.maxValueU')
    else:
        dir = 'v'
        opp = 'u'
        spans = spansU
        min = cmds.getAttr(int_surface + '.minValueV')
        max = cmds.getAttr(int_surface + '.maxValueV')
    val = min + (max - min) * 0.5

    # Caluculate surface length (intermediate surface)
    iso_crv = cmds.duplicateCurve(int_surface + '.' + opp + '[' + str(val) +
                                  ']',
                                  ch=0,
                                  rn=0,
                                  local=0)[0]
    iso_len = cmds.arclen(iso_crv)
    iso_inc = iso_len / spans

    # Get spaced isoparm list
    curveFn = glTools.utils.curve.getCurveFn(iso_crv)
    iso_list = [
        int_surface + '.' + dir + '[' +
        str(curveFn.findParamFromLength(iso_inc * i)) + ']'
        for i in range(spans + 1)
    ]
    cmds.delete(iso_crv)

    # Check full rebuild
    if fullRebuildU:
        # Extract isoparm curves
        iso_crv_list = [
            cmds.duplicateCurve(iso, ch=False, rn=False, local=False)[0]
            for iso in iso_list
        ]
        # Rebuild isoparm curves
        for iso_crv in iso_crv_list:
            cmds.rebuildCurve(iso_crv,
                              ch=False,
                              rpo=True,
                              rt=0,
                              end=1,
                              kr=0,
                              kcp=0,
                              kep=1,
                              kt=1,
                              s=0,
                              d=3,
                              tol=0)
        # Loft final surface
        rebuild_surface = cmds.loft(iso_crv_list,
                                    ch=0,
                                    u=1,
                                    c=0,
                                    ar=1,
                                    d=3,
                                    ss=1,
                                    rn=0,
                                    po=0,
                                    rsn=True)[0]
        # Delete intermediate curves
        cmds.delete(iso_crv_list)
    else:
        # Loft final surface
        rebuild_surface = cmds.loft(iso_list,
                                    ch=0,
                                    u=1,
                                    c=0,
                                    ar=1,
                                    d=3,
                                    ss=1,
                                    rn=0,
                                    po=0,
                                    rsn=True)[0]

    # Rename rebuilt surface
    rebuild_surface = cmds.rename(rebuild_surface, surface + '_rebuild')
    rebuild_surfaceShape = cmds.listRelatives(surface,
                                              s=True,
                                              ni=True,
                                              pa=True)[0]
    cmds.delete(int_surface)

    # Re-parameterize 0-1
    cmds.rebuildSurface(rebuild_surface,
                        ch=False,
                        rpo=True,
                        dir=2,
                        rt=0,
                        end=1,
                        kr=0,
                        kcp=1,
                        kc=1,
                        tol=0,
                        fr=0)

    # Initialize return value
    outputShape = rebuild_surfaceShape

    # ====================
    # - Replace Original -
    # ====================

    if replaceOrig:
        """
        # Get original shape
        shapes = glTools.utils.shape.getShapes(surface,nonIntermediates=True,intermediates=False)
        if not shapes:
            # Find Intermediate Shapes
            shapes = glTools.utils.shape.listIntermediates(surface)

        # Check shapes
        if not shapes:
            raise Exception('Unable to determine shape for surface "'+surface+'"!')
        # Check connections
        if cmds.listConnections(shapes[0]+'.create',s=True,d=False):
            # Find Intermediate Shapes
            shapes = glTools.utils.shape.findInputShape(shapes[0])
        """

        # Check history
        shapes = cmds.listRelatives(surface, s=True, ni=True, pa=True)
        if not shapes:
            raise Exception('Unable to determine shape for surface "' +
                            surface + '"!')
        shape = shapes[0]
        shapeHist = cmds.listHistory(shape)
        if shapeHist.count(shape): shapeHist.remove(shape)
        if shapeHist:
            print(
                'Surface "" contains construction history, creating new shape!'
            )

        # Override shape info and delete intermediate
        cmds.connectAttr(rebuild_surfaceShape + '.local',
                         shape + '.create',
                         f=True)
        outputShape = shape

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

    return outputShape
예제 #46
0
	def createRibbon(self, *args):
		self.name = cmds.textFieldGrp(self.widgets["ribbonNameTFG"], q=True, tx=True)
		self.numDiv = (cmds.intFieldGrp(self.widgets["jointsIFG"], q=True, v=True)[0]) -1
		self.fk = cmds.checkBox(self.widgets["fkSetupCB"], q=True, v=True)
		self.height = cmds.floatFieldGrp(self.widgets["heightFFG"], q=True, v1=True)
		self.ratio = cmds.floatFieldGrp(self.widgets["ratioFFG"], q=True, v1=True)
		self.axis = cmds.radioButtonGrp(self.widgets["axis"] , q=True, sl=True)

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

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

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

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

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

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

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

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

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

			self.follicleList.append(follicle)

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

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

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

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

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

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

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

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

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

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

			cmds.parent(locName, groupName)

			#create a parent constraint locator under the aim locator

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

		cmds.select(ribbonGroup)
예제 #47
0
def create(surface, spansU=0, spansV=0, prefix=None):
    """
    """
    # Load Plugins
    loadPlugin()

    # ==========
    # - Checks -
    # ==========

    # Check Surface
    if not glTools.utils.surface.isSurface(surface):
        raise Exception('Object "' + surface + '" is not a valid nurbs surface!')

    # Check Prefix
    if not prefix:
        prefix = glTools.utils.stringUtils.stripSuffix(surface)

    # Get Surface Details
    if not spansU:
        spansU = cmds.getAttr(surface + ".spansU")
    if not spansV:
        spansV = cmds.getAttr(surface + ".spansV")
    minU = cmds.getAttr(surface + ".minValueU")
    maxU = cmds.getAttr(surface + ".maxValueU")
    minV = cmds.getAttr(surface + ".minValueV")
    maxV = cmds.getAttr(surface + ".maxValueV")
    incU = (maxU - minU) / spansU
    incV = (maxV - minV) / spansV

    # =============
    # - Rebuild U -
    # =============

    crvU = []
    for i in range(spansU + 1):
        # Duplicate Surface Curve
        dupCurve = cmds.duplicateCurve(surface + ".u[" + str(incU * i) + "]", ch=True, rn=False, local=False)
        dupCurveNode = cmds.rename(dupCurve[1], prefix + "_spanU" + str(i) + "_duplicateCurve")
        dupCurve = cmds.rename(dupCurve[0], prefix + "_spanU" + str(i) + "_crv")
        crvU.append(dupCurve)

        # Set Curve Length
        arcLen = cmds.arclen(dupCurve)
        setLen = cmds.createNode("setCurveLength", n=prefix + "_spanU" + str(i) + "_setCurveLength")
        crvInfo = cmds.createNode("curveInfo", n=prefix + "_spanU" + str(i) + "_curveInfo")
        blendLen = cmds.createNode("blendTwoAttr", n=prefix + "_spanU" + str(i) + "length_blendTwoAttr")
        cmds.addAttr(dupCurve, ln="targetLength", dv=arcLen, k=True)
        cmds.connectAttr(dupCurveNode + ".outputCurve", crvInfo + ".inputCurve", f=True)
        cmds.connectAttr(dupCurveNode + ".outputCurve", setLen + ".inputCurve", f=True)
        cmds.connectAttr(crvInfo + ".arcLength", blendLen + ".input[0]", f=True)
        cmds.connectAttr(dupCurve + ".targetLength", blendLen + ".input[1]", f=True)
        cmds.connectAttr(blendLen + ".output", setLen + ".length", f=True)
        cmds.connectAttr(setLen + ".outputCurve", dupCurve + ".create", f=True)

        # Add Control Attributes
        cmds.addAttr(dupCurve, ln="lockLength", min=0, max=1, dv=1, k=True)
        cmds.addAttr(dupCurve, ln="lengthBias", min=0, max=1, dv=0, k=True)
        cmds.connectAttr(dupCurve + ".lockLength", blendLen + ".attributesBlender", f=True)
        cmds.connectAttr(dupCurve + ".lengthBias", setLen + ".bias", f=True)

    # Loft New Surface
    srfU = cmds.loft(crvU, ch=True, uniform=True, close=False, autoReverse=False, degree=3)
    srfUloft = cmds.rename(srfU[1], prefix + "_rebuildU_loft")
    srfU = cmds.rename(srfU[0], prefix + "_rebuildU_srf")

    # Rebuild 0-1
    rebuildSrf = cmds.rebuildSurface(srfU, ch=True, rpo=True, rt=0, end=1, kr=0, kcp=1, su=0, du=3, sv=0, dv=3, tol=0)
    rebuildSrfNode = cmds.rename(rebuildSrf[1], prefix + "_rebuildU_rebuildSurface")

    # Add Control Attributes
    cmds.addAttr(srfU, ln="lockLength", min=0, max=1, dv=1, k=True)
    cmds.addAttr(srfU, ln="lengthBias", min=0, max=1, dv=0, k=True)
    for crv in crvU:
        cmds.connectAttr(srfU + ".lockLength", crv + ".lockLength", f=True)
        cmds.connectAttr(srfU + ".lengthBias", crv + ".lengthBias", f=True)

    # =============
    # - Rebuild V -
    # =============

    crvV = []
    for i in range(spansV + 1):
        # Duplicate Surface Curve
        dupCurve = cmds.duplicateCurve(srfU + ".v[" + str(incV * i) + "]", ch=True, rn=False, local=False)
        dupCurveNode = cmds.rename(dupCurve[1], prefix + "_spanV" + str(i) + "_duplicateCurve")
        dupCurve = cmds.rename(dupCurve[0], prefix + "_spanV" + str(i) + "_crv")
        crvV.append(dupCurve)

        # Set Curve Length
        arcLen = cmds.arclen(dupCurve)
        setLen = cmds.createNode("setCurveLength", n=prefix + "_spanV" + str(i) + "_setCurveLength")
        crvInfo = cmds.createNode("curveInfo", n=prefix + "_spanV" + str(i) + "_curveInfo")
        blendLen = cmds.createNode("blendTwoAttr", n=prefix + "_spanV" + str(i) + "length_blendTwoAttr")
        cmds.addAttr(dupCurve, ln="targetLength", dv=arcLen, k=True)
        cmds.connectAttr(dupCurveNode + ".outputCurve", crvInfo + ".inputCurve", f=True)
        cmds.connectAttr(dupCurveNode + ".outputCurve", setLen + ".inputCurve", f=True)
        cmds.connectAttr(crvInfo + ".arcLength", blendLen + ".input[0]", f=True)
        cmds.connectAttr(dupCurve + ".targetLength", blendLen + ".input[1]", f=True)
        cmds.connectAttr(blendLen + ".output", setLen + ".length", f=True)
        cmds.connectAttr(setLen + ".outputCurve", dupCurve + ".create", f=True)

        # Add Control Attribute
        cmds.addAttr(dupCurve, ln="lockLength", min=0, max=1, dv=1, k=True)
        cmds.addAttr(dupCurve, ln="lengthBias", min=0, max=1, dv=0, k=True)
        cmds.connectAttr(dupCurve + ".lockLength", blendLen + ".attributesBlender", f=True)
        cmds.connectAttr(dupCurve + ".lengthBias", setLen + ".bias", f=True)

    # Loft New Surface
    srfV = cmds.loft(crvV, ch=True, uniform=True, close=False, autoReverse=False, degree=3)
    srfVloft = cmds.rename(srfV[1], prefix + "_rebuildV_loft")
    srfV = cmds.rename(srfV[0], prefix + "_rebuildV_srf")

    # Rebuild 0-1
    rebuildSrf = cmds.rebuildSurface(srfV, ch=True, rpo=True, rt=0, end=1, kr=0, kcp=1, su=0, du=3, sv=0, dv=3, tol=0)
    rebuildSrfNode = cmds.rename(rebuildSrf[1], prefix + "_rebuildV_rebuildSurface")

    # Add Control Attribute
    cmds.addAttr(srfV, ln="lockLength", min=0, max=1, dv=1, k=True)
    cmds.addAttr(srfV, ln="lengthBias", min=0, max=1, dv=0, k=True)
    for crv in crvV:
        cmds.connectAttr(srfV + ".lockLength", crv + ".lockLength", f=True)
        cmds.connectAttr(srfV + ".lengthBias", crv + ".lengthBias", f=True)

    # ===================
    # - Build Hierarchy -
    # ===================

    rebuildUGrp = cmds.group(em=True, n=prefix + "_rebuildU_grp")
    cmds.parent(crvU, rebuildUGrp)
    cmds.parent(srfU, rebuildUGrp)

    rebuildVGrp = cmds.group(em=True, n=prefix + "_rebuildV_grp")
    cmds.parent(crvV, rebuildVGrp)
    cmds.parent(srfV, rebuildVGrp)

    rebuildGrp = cmds.group(em=True, n=prefix + "_lockLength_grp")
    cmds.parent(rebuildUGrp, rebuildGrp)
    cmds.parent(rebuildVGrp, rebuildGrp)

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

    return rebuildGrp
예제 #48
0
def buildSpine(prefix):
	### query and set global keyframe interpolation setting for SDK setup
	currentIntangent = cmds.keyTangent( query = True, itt = True, g = True )
	currentOutTangent = cmds.keyTangent( query = True, ott = True, g = True )
	
	cmds.keyTangent( itt = 'linear', g = True )
	cmds.keyTangent( ott = 'linear', g = True )
	
	cmds.select( prefix )
	
	### get curve attributes
	degree = cmds.getAttr( prefix + '.degree' )
	span = cmds.getAttr( prefix + '.spans' )
	pointNumber = degree + span
	points = cmds.getAttr (( prefix + '.cv[0:'+ str(pointNumber)+']'))
	joint = None
	
	###Create and name joint from curve###
	for i in range (0, pointNumber):
		lastJoint = joint
		joint = cmds.joint ( p=(points[i][0], points[i][1], points[i][2]), n=( prefix + '_' + str(i).zfill(3)+"_FK"))
		# print "created joint: " + joint
		
		if i > 0 : 
			# print "orienting joint: " + str( lastJoint )
			cmds.joint ( lastJoint, e=True, zso=True, oj="xyz", sao="xup")
			cmds.setAttr( lastJoint + '.jointOrientX', 0 )
		cmds.joint ( e=True, oj="none", secondaryAxisOrient="xup", zso=True)
	
	#orient endjoint to match spine
	cmds.setAttr( prefix + '_' + str(pointNumber - 1).zfill(3) + '_FK.jointOrient', 0,0,0 )
	
	###Create and connect ikSpline to Spine curve###
	selection = cmds.ls(sl=True)
	startJoint = prefix + '_000_FK'
	endJoint = selection

	cmds.select( startJoint, endJoint )
	cmds.ikHandle (sol="ikSplineSolver", name=( prefix + '_000_IKH'))
	cmds.delete( 'curve1' )
	cmds.connectAttr( prefix + 'Shape.worldSpace[0]', prefix + '_000_IKH.inCurve')

	SpineIkConnections =cmds.listConnections( prefix + '_000_IKH' ,t="ikEffector")
	cmds.rename( str(SpineIkConnections[0]), prefix + '_000_EFF')

	###Create Spine joints###
	cmds.select( prefix + '_000_FK')
	selection = cmds.ls(sl=True)
	rels = [str(s) for s in cmds.listRelatives(selection,ad=True, typ='joint') ] + [str(s) for s in selection ]
	relsSort = sorted(rels)
	count = 0

	for joint in relsSort :
		cmds.select(clear=True)
		newjoint = cmds.joint()
		skinJNT = cmds.rename( newjoint, prefix + '_' + str(count).zfill(3) + '_JNT')
		cmds.parent( skinJNT, joint)
		cmds.setAttr( skinJNT + ".tx", 0 )
		cmds.setAttr( skinJNT + ".ty", 0 )
		cmds.setAttr( skinJNT + ".tz", 0 )
		cmds.setAttr( skinJNT + ".jointOrientX", cmds.getAttr(joint+".jointOrientX" ) )
		cmds.setAttr( skinJNT + ".jointOrientY", cmds.getAttr(joint+".jointOrientY" ) )
		cmds.setAttr( skinJNT + ".jointOrientZ", cmds.getAttr(joint+".jointOrientZ" ) )
		count += 1

	cmds.setAttr( prefix + '_000_JNT.jointOrientX', 0 )
	cmds.setAttr( prefix + '_000_JNT.jointOrientY', 0 )
	cmds.setAttr( prefix + '_000_JNT.jointOrientZ', 0 )

	###Build NURBS controler surfaces###
	for i in range (0,2):
		cmds.duplicate( prefix , n=('loft' + str(i).zfill(3)+"_CRV"))

	cmds.rebuildCurve( 'loft000_CRV', rt=0, s=pointNumber )
	cmds.rebuildCurve( 'loft001_CRV', rt=0, s=pointNumber )

	cmds.move( .5, 0, 0, 'loft000_CRV', absolute=True )
	cmds.move( -.5, 0, 0, 'loft001_CRV', absolute=True )
	cmds.select( 'loft000_CRV', 'loft001_CRV' )

	cmds.loft( 'loft000_CRV', 'loft001_CRV', ch=True, rn=True, ar=True, n=( prefix + '_000_GEO' ) )
	cmds.rebuildSurface( prefix + '_000_GEO',  ch=True, rpo=True, rt=False, end=True, kr=False, kcp=False, kc=False, su=True, du=3, sv=3, dv=3, tol= 0.01, fr=False,  dir=2 )
	cmds.delete( prefix + '_000_GEO', ch=True)

	cmds.loft( 'loft000_CRV', 'loft001_CRV', ch=True, rn=True, ar=True, n=( prefix + '_001_GEO' ) )
	cmds.rebuildSurface( prefix + '_001_GEO',  ch=True, rpo=True, rt=False, end=True, kr=False, kcp=False, kc=False, su=True, du=3, sv=3, dv=3, tol= 0.01, fr=False,  dir=2 )
	cmds.delete( prefix + '_001_GEO', ch=True)

	cmds.delete('loft000_CRV', 'loft001_CRV')

	cmds.reverseSurface( prefix + '_000_GEO', ch=True, d=0, rpo=True )
	cmds.reverseSurface( prefix + '_001_GEO', ch=True, d=0, rpo=True )

	###Create control joints###
	for i in range (0,3):
		cmds.joint( p=(0, 0, 0), name= prefix + '_Geo' + str (i).zfill(3)+"_FK" )
		cmds.group( em=True, name= prefix + '_Geo' + str (i).zfill(3)+"_GRP" )


	cmds.parent( prefix + '_Geo000_FK', prefix + '_Geo000_GRP')
	cmds.parent( prefix + '_Geo001_FK', prefix + '_Geo001_GRP')
	cmds.parent( prefix + '_Geo002_FK', prefix + '_Geo002_GRP')

	###Create control folicle###
	cmds.createNode ('follicle', name= prefix + '_Mid000_FOLShape')
	cmds.connectAttr( prefix + '_000_GEOShape.worldMatrix[0]', prefix + '_Mid000_FOLShape.inputWorldMatrix' )
	cmds.connectAttr( prefix + '_000_GEOShape.local', prefix + '_Mid000_FOLShape.inputSurface' )
	cmds.connectAttr(  prefix + '_Mid000_FOLShape.outTranslate', prefix + '_Mid000_FOL.translate' )
	cmds.connectAttr(  prefix + '_Mid000_FOLShape.outRotate', prefix + '_Mid000_FOL.rotate' )
	cmds.setAttr( prefix + '_Mid000_FOLShape.parameterU', .5 )
	cmds.setAttr( prefix + '_Mid000_FOLShape.parameterV', .5 )

	###Create and position controlers###
	for i in range (0,3):
		cmds.circle( radius = 4, nr=(0, 1, 0), c=(0, 0, 0), n= prefix  + '_' + str (i).zfill(3)+"_CTL", ch = False  )
		cmds.group( em=True, name= prefix + '_CTL' + str (i).zfill(3)+"_GRP" )

	cmds.parent( prefix + '_000_CTL', prefix + '_CTL000_GRP')
	cmds.parent( prefix + '_001_CTL', prefix + '_CTL001_GRP' )
	cmds.parent( prefix + '_002_CTL', prefix + '_CTL002_GRP')

	cmds.group( em=True, name= prefix + '_CTL001_TopSDK_GRP'  )
	cmds.parent( prefix + '_CTL001_TopSDK_GRP', prefix + '_Mid000_FOL')
	cmds.setAttr( prefix + '_CTL001_TopSDK_GRP.translate', 0,0,0 )

	cmds.group( em=True, name= prefix + '_CTL001_TopRotateSDK_GRP'  )
	cmds.parent( prefix + '_CTL001_TopRotateSDK_GRP', prefix + '_CTL001_TopSDK_GRP')
	cmds.setAttr( prefix + '_CTL001_TopRotateSDK_GRP.translate', 0,0,0 )

	cmds.group( em=True, name= prefix + '_CTL001_BtmRotateSDK_GRP'  )
	cmds.parent( prefix + '_CTL001_BtmRotateSDK_GRP', prefix + '_CTL001_TopRotateSDK_GRP')
	cmds.setAttr( prefix + '_CTL001_BtmRotateSDK_GRP.translate', 0,0,0 )

	cmds.parent( prefix + '_CTL001_GRP', prefix + '_CTL001_BtmRotateSDK_GRP')
	cmds.setAttr( prefix + '_CTL001_GRP.translate', 0,0,0 )
	cmds.rename (prefix + '_CTL001_GRP', prefix + '_CTL001_BtmSDK_GRP')


	cmds.parentConstraint( prefix + '_001_CTL', prefix + '_Geo001_FK')
	cmds.setAttr( prefix + '_CTL001_BtmSDK_GRP.rotate', 0,0,0 )
	cmds.pointConstraint( prefix + '_000_EFF', prefix + '_CTL002_GRP', mo=False)
	cmds.delete( prefix +'_CTL002_GRP_pointConstraint1')
	cmds.parentConstraint( prefix + '_002_CTL', prefix + '_Geo002_FK')
	cmds.pointConstraint( prefix + '_000_FK', prefix + '_CTL000_GRP', mo=False)
	cmds.delete( prefix + '_CTL000_GRP_pointConstraint1')
	cmds.parentConstraint( prefix + '_000_CTL', prefix + '_Geo000_FK')

	cmds.spaceLocator(n = 'up')
	cmds.parent( 'up', prefix + '_000_FK')
	cmds.setAttr( 'up.translate', 0,0,-2 )
	cmds.setAttr( 'up.rotate', 0,0,0 )
	cmds.aimConstraint( prefix + '_001_FK', prefix + '_ CTL000_GRP', aimVector = [0, 1, 0], worldUpType = "object", worldUpObject = "up" )
	cmds.delete ( prefix + '_CTL000_GRP_aimConstraint1')

	cmds.parent( 'up', endJoint)
	cmds.setAttr( 'up.translate', 0,0,-2 )
	cmds.setAttr( 'up.rotate', 0,0,0 )
	cmds.aimConstraint( lastJoint , prefix + '_CTL002_GRP', aimVector = [0, -1, 0], upVector = [ 0, 0, -1], worldUpType = "object", worldUpObject = "up" )
	cmds.delete ( prefix + '_CTL002_GRP_aimConstraint1')
	cmds.delete ( 'up')

	###set up groups for advanced twist###
	cmds.group( em=True, name= prefix + '_UpTwist000_NULL' )
	cmds.group( em=True, name= prefix + '_DwnTwist000_NULL' )
	cmds.parent( prefix + '_UpTwist000_NULL', prefix + '_000_CTL')
	cmds.parent( prefix + '_DwnTwist000_NULL', prefix + '_002_CTL')
	cmds.setAttr( prefix + '_DwnTwist000_NULL.translate', 0,0,0)
	cmds.setAttr( prefix + '_UpTwist000_NULL.translate', 0,0,0)
	cmds.setAttr( prefix + '_DwnTwist000_NULL.rotate', 180,0,90)
	cmds.setAttr( prefix + '_UpTwist000_NULL.rotate', 180,0,90)

	cmds.select( prefix + '_000_CTL' )
	cmds.addAttr( keyable=True, longName='twist' )

	cmds.select( prefix + '_002_CTL' )
	cmds.addAttr( keyable=True, longName='twist' )

	###position control joints###
	cmds.parent ( prefix + '_Geo001_GRP', prefix + '_Mid000_FOL')
	cmds.setAttr( prefix + '_Geo001_GRP.translate', 0,0,0)
	cmds.setAttr( prefix + '_Geo001_GRP.rotate', 0,0,0)

	cmds.parentConstraint( prefix + '_000_CTL', prefix + '_Geo000_GRP')
	cmds.delete ( prefix + '_Geo000_GRP_parentConstraint1')

	cmds.parentConstraint( prefix + '_000_CTL', prefix + '_Geo002_GRP')
	cmds.delete( prefix + '_Geo002_GRP_parentConstraint1')

	###Create twist###
	list=[]

	for i in range (0, pointNumber):
	   newNode = cmds.createNode ( 'multiplyDivide', n=( prefix + '_Twist' + str(i).zfill(3)+"_MDN"))
	   list.append( newNode )
	   cmds.connectAttr( prefix + '_002_CTL.twist', str(newNode)+'.input1X' )
	   cmds.connectAttr( prefix + '_001_CTL.rotateY', str(newNode)+'.input1Y' )
	   cmds.connectAttr( prefix + '_000_CTL.twist', str(newNode)+'.input1Z' )




	listPma=[]
	for i in range (0, pointNumber):
	   newPma = cmds.createNode ( 'plusMinusAverage', n=( prefix + '_Twist' + str(i).zfill(3)+"_PMA"))
	   listPma.append( newPma )
	   cmds.setAttr (str(newPma)+'.operation',1)
	   cmds.connectAttr( prefix + '_Twist'+str(i).zfill(3)+'_MDN.outputX', str(newPma)+'.input1D[0]' )
	   cmds.connectAttr( prefix + '_Twist'+str(i).zfill(3)+'_MDN.outputY', str(newPma)+'.input1D[1]' )
	   cmds.connectAttr( prefix + '_Twist'+str(i).zfill(3)+'_MDN.outputZ', str(newPma)+'.input1D[2]' )

	   ###Connect twist###
	for i in range (0, pointNumber):
		cmds.connectAttr( prefix +  '_Twist'+str(i).zfill(3)+'_PMA.output1D', prefix + '_' + str(i).zfill(3)+'_JNT.rotateX' )

	###Squash and stretch###
	cmds.createNode( 'curveInfo', n=( prefix + '_000_CIN'))
	cmds.connectAttr( prefix + 'Shape.worldSpace', prefix + '_000_CIN.inputCurve')
	cmds.createNode( 'multiplyDivide', n=( prefix + '_SquashStretch000_MDN'))
	cmds.setAttr( prefix + '_SquashStretch000_MDN.operation',2)
	cmds.connectAttr( prefix + '_000_CIN.arcLength', prefix + '_SquashStretch000_MDN.input1.input1X')

	stretchInfo = cmds.getAttr( prefix + '_SquashStretch000_MDN.input1X' )

	cmds.setAttr( prefix + '_SquashStretch000_MDN.input2X', stretchInfo)

	for i in range (0, pointNumber):
	   cmds.connectAttr( prefix + '_SquashStretch000_MDN.outputX', prefix + '_' + str(i).zfill(3)+'_FK.scaleX')
	   
	   ###Create follices###
	listLOC=[]

	for i in range (0, pointNumber):
	   newLOC = cmds.spaceLocator( n=('folliclePos' + str(i).zfill(3)+'_LOC' ))
	   listLOC.append( newLOC )
	   cmds.parentConstraint( prefix + '_' + str(i).zfill(3)+'_FK', 'folliclePos' + str(i).zfill(3)+'_LOC')

	listCPOS=[]

	for i in range (0, pointNumber):
	   newCPOS = cmds.createNode ( 'closestPointOnSurface', n=('folliclePos' + str(i).zfill(3)+"_CPOS"))
	   listCPOS.append( newCPOS )
	   cmds.connectAttr( 'folliclePos' + str(i).zfill(3)+'_LOC.translate', 'folliclePos' + str(i).zfill(3)+'_CPOS.inPosition')
	   cmds.connectAttr( prefix  + '_' + '001_GEOShape.worldSpace', 'folliclePos' + str(i).zfill(3)+'_CPOS.inputSurface')

	listFOL=[]

	for i in range (0, pointNumber):
	   newFOL = cmds.createNode ('follicle', n=( prefix  +  '_Joint_' + str(i).zfill(3)+'_FOLShape'))
	   listFOL.append( newFOL )
	   cmds.connectAttr( prefix + '_001_GEOShape.worldMatrix', prefix  +  '_Joint_' + str(i).zfill(3)+'_FOLShape.inputWorldMatrix')
	   cmds.connectAttr( prefix + '_001_GEOShape.local', prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.inputSurface')
	   cmds.connectAttr( prefix + '_Joint_' + str(i).zfill(3)+'_FOLShape.outTranslate', prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.translate')
	   cmds.connectAttr( prefix + '_Joint_' + str(i).zfill(3)+'_FOLShape.outRotate', prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.rotate')

	   cmds.setAttr( prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.translateX', lock=True)
	   cmds.setAttr( prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.translateY', lock=True)
	   cmds.setAttr( prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.translateZ', lock=True)

	   cmds.setAttr( prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.rotateX', lock=True)
	   cmds.setAttr( prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.rotateY', lock=True)
	   cmds.setAttr( prefix  +  '_Joint_' + str(i).zfill(3)+'_FOL.rotateZ', lock=True)

	   cmds.connectAttr( 'folliclePos' + str(i).zfill(3)+'_CPOS.parameterU', prefix +  '_Joint_' + str(i).zfill(3)+'_FOL.parameterU')
	   cmds.connectAttr( 'folliclePos' + str(i).zfill(3)+'_CPOS.parameterV', prefix +  '_Joint_' + str(i).zfill(3)+'_FOL.parameterV')

	   cmds.disconnectAttr( 'folliclePos' + str(i).zfill(3)+'_CPOS.parameterU', prefix + '_Joint_' + str(i).zfill(3)+'_FOL.parameterU')
	   cmds.disconnectAttr( 'folliclePos' + str(i).zfill(3)+'_CPOS.parameterV', prefix + '_Joint_' + str(i).zfill(3)+'_FOL.parameterV')

	   cmds.delete( 'folliclePos' + str(i).zfill(3)+'_CPOS' )
	   cmds.delete( 'folliclePos' + str(i).zfill(3)+'_LOC' )

	###Create Spine joints###
	listJNT=[]

	for i in range (0, pointNumber):
	   newDRV = cmds.joint( n=( prefix + '_Joint_' + str(i).zfill(3)+'_DRV'))
	   listJNT.append( newDRV )
	   cmds.parent( prefix + '_Joint_' + str(i).zfill(3)+'_DRV', prefix + '_Joint_' + str(i).zfill(3)+'_FOL')
	   cmds.setAttr( prefix + '_Joint_' + str(i).zfill(3)+'_DRV.translateX',0 )
	   cmds.setAttr( prefix + '_Joint_' + str(i).zfill(3)+'_DRV.translateY',0 )
	   cmds.setAttr( prefix + '_Joint_' + str(i).zfill(3)+'_DRV.translateZ',0 )

	   cmds.setAttr( prefix + '_Joint_' + str(i).zfill(3)+'_DRV.rotateX',0 )
	   cmds.setAttr( prefix + '_Joint_' + str(i).zfill(3)+'_DRV.rotateY',0 )
	   cmds.setAttr( prefix + '_Joint_' + str(i).zfill(3)+'_DRV.rotateZ',0 )
	   
	###Skin ribbons###
	cmds.skinCluster( prefix + '_Geo000_FK', prefix + '_Geo002_FK', prefix + '_000_GEO', dr=4.5, n = prefix + '_Geo000_SKN')
	cmds.skinCluster( prefix + '_Geo000_FK', prefix + '_Geo002_FK', prefix + '_Geo001_FK', prefix + '_001_GEO', dr=4.5, n = prefix + '_Geo001_SKN')

	###Skin splines###
	driverJoints = cmds.ls(prefix + '_Joint*_DRV')
	cmds.skinCluster( driverJoints, prefix, n = prefix + '_Crv000_SKN' )

	###set up advanced twist
	### cmds.setAttr( prefix + '_000_IKH.dTwistControlEnable', 1)
	### cmds.setAttr( prefix + '_000_IKH.dWorldUpType', 4)

	###Connect twist###
	### cmds.connectAttr (prefix + '_000_CTL.rotateY', prefix + '_000_CTL.twist')
	### cmds.connectAttr (prefix + '_002_CTL.rotateY', prefix + '_002_CTL.twist')

	###Name curve###
	cmds.rename (prefix, prefix + '_000_CRV')

	###Create Master group###
	###cmds.select( clear=True )
	###cmds.group (n = prefix + '_Master_GRP')
	###elements = cmds.ls (prefix)
	###cmds.parent (elements, prefix + '_Master_GRP')
	###Print###
	#print 'dont forget to setup the twist!!!!!!!!!!!!!'

	#get the length of our Spine curve
	lengthOfCnt_Spineurve = cmds.getAttr( prefix + '_SquashStretch000_MDN.input2X')

	#set rotationAmount (to taste)
	rotationAmount = 90

	#Declare top variables (ie "the drivers")
	topTX = prefix  + "_002_CTL.tx"
	topRZ = prefix  + "_002_CTL.rz"
	#Declare bottom variables (ie "the drivers")
	btmTX = prefix  + "_000_CTL.tx"
	btmRZ = prefix  + "_000_CTL.rz"
	#declare mid variables (ie "the driven")
	midTopTranslateSDK = prefix  + "_CTL001_TopSDK_GRP.rz"
	midTopRotateSDK = prefix  + "_CTL001_TopRotateSDK_GRP.rz"
	midBtmTranslateSDK = prefix  + "_CTL001_BtmSDK_GRP.rz"
	midBtmRotateSDK = prefix  + "_CTL001_BtmRotateSDK_GRP.rz"


	#setAttrs for mid moving top control in +X
	cmds.setAttr(topTX, lengthOfCnt_Spineurve)
	cmds.setAttr(midTopTranslateSDK, -rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midTopTranslateSDK, cd=topTX)

	#setAttrs for mid moving top control in -X
	cmds.setAttr(topTX, -lengthOfCnt_Spineurve)
	cmds.setAttr(midTopTranslateSDK, rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midTopTranslateSDK, cd=topTX)

	#return top and mid cntrls to start Position
	cmds.setAttr(topTX, 0)
	cmds.setAttr(midTopTranslateSDK, 0)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midTopTranslateSDK, cd=topTX)


	#################################################
	#setAttrs for mid rotating top control in +Z
	cmds.setAttr(topRZ, rotationAmount)
	cmds.setAttr(midTopRotateSDK, -rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midTopRotateSDK, cd=topRZ)

	#setAttrs for mid rotating top control in -Z
	cmds.setAttr(topRZ, -rotationAmount)
	cmds.setAttr(midTopRotateSDK, rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midTopRotateSDK, cd=topRZ)

	#return top and mid cntrls to start Position
	cmds.setAttr(topRZ, 0)
	cmds.setAttr(midTopRotateSDK, 0)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midTopRotateSDK, cd=topRZ)
	##################################################


	#################################################
	#setAttrs for mid rotating bottom control in +Z
	cmds.setAttr(btmRZ, rotationAmount)
	cmds.setAttr(midBtmRotateSDK, -rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midBtmRotateSDK, cd=btmRZ)

	#setAttrs for mid rotating bottom control in -Z
	cmds.setAttr(btmRZ, -rotationAmount)
	cmds.setAttr(midBtmRotateSDK, rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midBtmRotateSDK, cd=btmRZ)

	#return top and mid cntrls to start Position
	cmds.setAttr(btmRZ, 0)
	cmds.setAttr(midBtmRotateSDK, 0)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midBtmRotateSDK, cd=btmRZ)
	##################################################


	#setAttrs for mid moving bottom control in +X
	cmds.setAttr(btmTX, lengthOfCnt_Spineurve)
	cmds.setAttr(midBtmTranslateSDK, rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midBtmTranslateSDK, cd=btmTX)

	#setAttrs for mid moving bottom control in -X
	cmds.setAttr(btmTX, -lengthOfCnt_Spineurve)
	cmds.setAttr(midBtmTranslateSDK, -rotationAmount)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midBtmTranslateSDK, cd=btmTX)

	#return bottom and mid controls to start Position
	cmds.setAttr(btmTX, 0)
	cmds.setAttr(midBtmTranslateSDK, 0)
	#setDrivenKeyframe NB: "cd" stands for "current driver"
	cmds.setDrivenKeyframe(midBtmTranslateSDK, cd=btmTX)




	theJoints = range(pointNumber)
	theJointsLength = float(len(theJoints))-1

	for aJoint in theJoints:
		MDN = prefix + '_' + "Twist"+str(aJoint).zfill(3)+'_MDN'
		cmds.setAttr( MDN + ".input2Z", (1-float(aJoint)/theJointsLength))

	for aJoint in theJoints:
		MDN = prefix + '_' + "Twist"+str(aJoint).zfill(3)+'_MDN'
		cmds.setAttr( MDN + ".input2X", (float(aJoint)/theJointsLength))

	theMiddleJoint = theJoints.index((len(theJoints))/2)
	theMidApexList=[]

	for aJoint in theJoints[:((len(theJoints))/2)+1]:
		MDN = prefix + '_' + "Twist"+str(aJoint).zfill(3)+'_MDN'
		cmds.setAttr( MDN + ".input2Y", (2*(float(aJoint)/theJointsLength)))
		#theMidApexList.append(theRotationMultipier)

	for aJoint in theJoints[((len(theJoints))/2)+1:]:
		MDN = prefix + '_' + "Twist"+str(aJoint).zfill(3)+'_MDN'
		cmds.setAttr( MDN + ".input2Y", 2*(1- float(aJoint)/theJointsLength))
		#theMidApexList.append(theRotationMultipier)

	#for anItem in theMidApexList:
	#    print anItem 



	#build heirarchy#
	cmds.group( em=True, name=( prefix + '_All000_GRP'))
	cmds.group( em=True, name=( prefix + '_All001_GRP'))
	cmds.group( em=True, name=( prefix + '_All002_GRP'))
	# build master controls
	cmds.curve( name=( prefix + '_All000_CTL'), degree = 3, point = [(-2.5870293526821834e-15, 5.4483909466784861e-36, 8.4899356232051044), (4.086088758749157, 5.4483909466784861e-36, 4.8693000688131338), (6.8101479312486024, 5.4483909466784861e-36, 1.2486645144211457), (5.4481183449988837, 5.4483909466784861e-36, -3.9998118128096531), (2.5874314825403598e-15, 5.4483909466891123e-36, -6.7238709853090981), (-5.4481183449988766, 5.4483909466784861e-36, -3.9998118128096594), (-6.8101479312485997, 5.4483909466784861e-36, 1.248664514421141), (-4.0860887587491641, 5.4483909466784861e-36, 4.8693000688131205), (-1.7246192134784273e-15, 2.0413722306552454e-32, 8.4899356232051044)] )
	cmds.addAttr( longName = 'subControlOneVisibility', keyable = True, min = 0, max = 1, attributeType = 'long' )
	cmds.addAttr( longName = 'subControlTwoVisibility', keyable = True, min = 0, max = 1, attributeType = 'long' )
	cmds.rename( 'curveShape1', prefix + '_All000_CTLShape' )
	cmds.setAttr( prefix + '_All000_CTL.subControlOneVisibility', keyable = False, channelBox = True )
	cmds.setAttr( prefix + '_All000_CTL.subControlTwoVisibility', keyable = False, channelBox = True )
	cmds.curve( name=( prefix + '_All001_CTL'), degree = 3, point = [(-2.4124617763005566e-15, 4.2232448323644054e-35, 7.9372176682272988), (3.8185271911283234, 4.2232448323644054e-35, 4.5536652958006165), (6.3642119852138777, 4.2232448323644054e-35, 1.170112923373918), (5.0913695881711041, 4.2232448323644054e-35, -3.7346874250304691), (2.4231696955851561e-15, 4.2232448323653986e-35, -6.2803722191160229), (-5.091369588171097, 4.2232448323644054e-35, -3.7346874250304749), (-6.364211985213875, 4.2232448323644054e-35, 1.1701129233739136), (-3.8185271911283292, 4.2232448323644054e-35, 4.553665295800605), (-1.6065231976529386e-15, 1.9114150233729631e-32, 7.9372176682272988)])
	cmds.rename( 'curveShape1', prefix + '_All001_CTLShape' )
	cmds.curve( name=( prefix + '_All002_CTL'), degree = 3, point = [(-2.1955804705117755e-15, 8.1207304823966828e-35, 7.246874953712628), (3.4846338500471794, 8.1207304823966828e-35, 4.1591815734589863), (5.80772308341197, 8.1207304823966828e-35, 1.0714881932053306), (4.6461784667295767, 8.1207304823966828e-35, -3.4044347127470127), (2.2172217094583908e-15, 8.1207304823975905e-35, -5.7275239461118046), (-4.6461784667295722, 8.1207304823966828e-35, -3.404434712747018), (-5.8077230834119673, 8.1207304823966828e-35, 1.0714881932053264), (-3.4846338500471838, 8.1207304823966828e-35, 4.1591815734589765), (-1.4601134405167476e-15, 1.7485469988810485e-32, 7.246874953712628)] )
	cmds.rename( 'curveShape1', prefix + '_All002_CTLShape' )
	cmds.parent ( prefix + '_All000_CTL', prefix + '_All000_GRP')
	cmds.parent ( prefix + '_All001_CTL', prefix + '_All001_GRP')
	cmds.parent ( prefix + '_All002_CTL', prefix + '_All002_GRP')
	cmds.parentConstraint( prefix + '_000_CTL', prefix + '_All000_GRP' )
	cmds.parentConstraint( prefix + '_All000_CTL', prefix + '_All001_GRP' )
	cmds.parentConstraint( prefix + '_All001_CTL', prefix + '_All002_GRP' )
	cmds.delete( prefix + '_All000_GRP_parentConstraint1' )
	cmds.group( em=True, name=( prefix + '_NoTransform000_GRP'))
	#connect visibility of sub controls
	cmds.connectAttr( prefix + '_All000_CTL.subControlOneVisibility', prefix + '_All001_CTL.visibility' )
	cmds.connectAttr( prefix + '_All000_CTL.subControlTwoVisibility', prefix + '_All002_CTL.visibility' )
	# constrain master controls into rig
	cmds.parent(  prefix + '_000_FK', prefix + '_All000_GRP')
	cmds.parent(  prefix + '_000_IKH', prefix + '_All000_GRP')
	# pack up heirarchy
	cmds.parent(  prefix + '_000_CRV', prefix + '_NoTransform000_GRP')
	cmds.parent(  prefix + '_000_GEO', prefix + '_NoTransform000_GRP')
	cmds.parent(  prefix + '_001_GEO', prefix + '_NoTransform000_GRP')
	cmds.parent(  prefix + '_Geo000_GRP', prefix + '_NoTransform000_GRP')
	cmds.parent(  prefix + '_Geo001_GRP', prefix + '_NoTransform000_GRP')
	cmds.parent(  prefix + '_Geo002_GRP', prefix + '_NoTransform000_GRP')
	cmds.parent(  prefix + '_Mid000_FOL', prefix + '_NoTransform000_GRP')


	cmds.select ( prefix + '_Joint*_FOL')
	selection = cmds.ls(sl=True)
	list=[]

	for i in selection:
		cmds.parent (  i, prefix + '_NoTransform000_GRP')

	cmds.group ( em=True, name=( prefix + '_Master000_GRP'))
	cmds.parent ( prefix + '_NoTransform000_GRP', prefix + '_Master000_GRP')
	cmds.parent ( prefix + '_All000_GRP', prefix + '_Master000_GRP')
	cmds.parentConstraint( prefix + '_All002_CTL', prefix + '_CTL000_GRP' )
	cmds.group( em = True, name = prefix + '_CTL002constraint_GRP' )
	cmds.parentConstraint( prefix + '_002_CTL', prefix + '_CTL002constraint_GRP' )
	cmds.delete( prefix + '_CTL002constraint_GRP_parentConstraint1' )
	cmds.parentConstraint ( prefix + '_CTL002constraint_GRP', prefix + '_CTL002_GRP' )
	cmds.parent( prefix + '_CTL002constraint_GRP', prefix + '_All002_CTL' )
	cmds.parent ( prefix + '_000_IKH', prefix + '_All000_CTL')
	cmds.parent ( prefix + '_000_FK', prefix + '_All000_CTL')

	#make Spine scaleable#
	cmds.createNode ( 'multiplyDivide', n= prefix + '_GlobalScale000_MDN' )
	arcLen = cmds.getAttr ( prefix + '_000_CIN.arcLength' )
	cmds.setAttr ( prefix + '_GlobalScale000_MDN.input1X', arcLen )
	cmds.select ( prefix + '_All000_CTL', r=True )
	cmds.addAttr ( prefix + '_All000_CTL', longName =  'globalScale', defaultValue= 1, keyable = True )  
	cmds.connectAttr ( prefix + '_All000_CTL.globalScale', prefix + '_GlobalScale000_MDN.input2X' )
	cmds.connectAttr ( prefix + '_GlobalScale000_MDN.outputX', prefix + '_SquashStretch000_MDN.input2X' )
	cmds.connectAttr ( prefix + '_All000_CTL.globalScale',  prefix + '_All000_GRP.scaleX' )
	cmds.connectAttr ( prefix + '_All000_CTL.globalScale',  prefix + '_All000_GRP.scaleY' )
	cmds.connectAttr ( prefix + '_All000_CTL.globalScale',  prefix + '_All000_GRP.scaleZ' )

	for i in range (0, pointNumber):
	   cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix +  '_Joint_' + str(i).zfill(3)+'_FOL.scaleX')
	   cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix +  '_Joint_' + str(i).zfill(3)+'_FOL.scaleY')
	   cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix +  '_Joint_' + str(i).zfill(3)+'_FOL.scaleZ')

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Mid000_FOL.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Mid000_FOL.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Mid000_FOL.scaleZ' )

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo000_FK.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo000_FK.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo000_FK.scaleZ' )

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo001_FK.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo001_FK.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo001_FK.scaleZ' )

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo002_FK.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo002_FK.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_Geo002_FK.scaleZ' )

	cmds.setAttr ( prefix + '_All000_CTL.scaleX', lock=True, keyable = False )
	cmds.setAttr ( prefix + '_All000_CTL.scaleY', lock=True, keyable = False )
	cmds.setAttr ( prefix + '_All000_CTL.scaleZ', lock=True, keyable = False )

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_CTL000_GRP.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_CTL000_GRP.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_CTL000_GRP.scaleZ' )

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_CTL002_GRP.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_CTL002_GRP.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_CTL002_GRP.scaleZ' )

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_All001_GRP.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_All001_GRP.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_All001_GRP.scaleZ' )

	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_All002_GRP.scaleX' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_All002_GRP.scaleY' )
	cmds.connectAttr( prefix + '_All000_CTL.globalScale', prefix + '_All002_GRP.scaleZ' )
	#add extra twist node#

	cmds.createNode ( 'addDoubleLinear', n= prefix +'ExtraTwist000_ADL' )
	cmds.createNode ( 'addDoubleLinear', n= prefix +'ExtraTwist002_ADL' )

	cmds.connectAttr (prefix + '_000_CTL.rotateY', prefix +'ExtraTwist000_ADL.input1' )
	cmds.connectAttr (prefix + '_002_CTL.rotateY', prefix +'ExtraTwist002_ADL.input1' )

	cmds.connectAttr ( prefix +'ExtraTwist000_ADL.output', prefix + '_000_CTL.twist')
	cmds.connectAttr ( prefix +'ExtraTwist002_ADL.output', prefix + '_002_CTL.twist')

	### add _SKL single heirarchy joints
	### find number of joints in spine
	spineCRVdegree = cmds.getAttr( prefix + '_000_CRV.degree' )
	spineCRVspans = cmds.getAttr( prefix + '_000_CRV.spans' )
	totalSpineJoints = spineCRVdegree + spineCRVspans
	
	### zero out joint orient of _JNTs
	for i in range(0,totalSpineJoints):
		cmds.setAttr( prefix + '_' + str(i).zfill(3) + '_JNT.jointOrient', 0,0,0 )
	
	### constrain SKL to JNT
	for i in range(0,totalSpineJoints):
		cmds.select( clear = True )
		cmds.joint( name = prefix + '_' + str(i).zfill(3) + '_SKL' )
		cmds.parentConstraint( prefix + '_' + str(i).zfill(3) + '_JNT', prefix + '_' + str(i).zfill(3) + '_SKL' )
		cmds.delete( prefix + '_' + str(i).zfill(3) + '_SKL_parentConstraint1' )
		cmds.setAttr( prefix + '_' + str(i).zfill(3) + '_SKL.rotate', 0,0,0 )
		cmds.parentConstraint( prefix + '_' + str(i).zfill(3) + '_JNT', prefix + '_' + str(i).zfill(3) + '_SKL' )
	
	### parent _SKL hierarchy
	for i in range(0,(totalSpineJoints -1)):
		cmds.parent( prefix + '_' + str(i + 1).zfill(3) + '_SKL', prefix + '_' + str(i).zfill(3) + '_SKL' )
	### orient _SKL hierarchy
	for i in range(0,(totalSpineJoints -2)):
		cmds.setAttr( prefix + '_' + str(i).zfill(3) + '_SKL.jointOrient', 0,0,0 )
		jointX = cmds.getAttr( prefix + '_' + str(i).zfill(3) + '_SKL.rotateX' )
		jointY = cmds.getAttr( prefix + '_' + str(i).zfill(3) + '_SKL.rotateY' )
		jointZ = cmds.getAttr( prefix + '_' + str(i).zfill(3) + '_SKL.rotateZ' )
		cmds.setAttr( prefix + '_' + str(i).zfill(3) + '_SKL.jointOrientX', jointX )
		cmds.setAttr( prefix + '_' + str(i).zfill(3) + '_SKL.jointOrientY', jointY )
		cmds.setAttr( prefix + '_' + str(i).zfill(3) + '_SKL.jointOrientZ', jointZ )
	
	### orient end _SKL joint to 0,0,0
	cmds.setAttr( prefix + '_' + str(totalSpineJoints -1).zfill(3) + '_SKL.jointOrient', 0,0,0 )
	
	### set rotation order of top control
	cmds.setAttr( prefix + '_002_CTL.rotateOrder', 4 )

	### rename for COG and spine CTL
	cmds.rename( prefix + '_All000_CTL', prefix + 'COG_CTL' )
	cmds.rename( prefix + '_All001_CTL', prefix + 'COG_Mid_CTL' )
	cmds.rename( prefix + '_All002_CTL', prefix + 'COG_Btm_CTL' )

	cmds.rename( prefix + '_000_CTL', prefix + 'Btm_CTL' )
	cmds.rename( prefix + '_001_CTL', prefix + 'Mid_CTL' )
	cmds.rename( prefix + '_002_CTL', prefix + 'Top_CTL' )

	### cleanup hierarchy
	cmds.parent( prefix + '_All000_GRP', prefix + '_NoTransform000_GRP' )
	cmds.parent( prefix + '_NoTransform000_GRP', world = True )
	cmds.group( em = True, name = prefix + '_Controls_GRP' )
	cmds.parent( prefix + '_CTL000_GRP', prefix + '_CTL002_GRP', prefix + '_All001_GRP', prefix + '_All002_GRP', prefix + '_All000_GRP', prefix + '_Controls_GRP' )
	cmds.parent( prefix + '_Controls_GRP', prefix + '_NoTransform000_GRP' )
	cmds.delete( prefix + '_Master000_GRP' )

	cmds.group( em = True, name = prefix + '_Rig_GRP' )
	cmds.parent( prefix + '_Rig_GRP', prefix + '_NoTransform000_GRP' )
	cmds.select( prefix + '_Joint*' + '_FOL', prefix +  '_Mid*' + '_FOL' )
	folList = cmds.ls( sl = True )
	for i in folList:
		cmds.parent( i, prefix + '_Rig_GRP' )

	cmds.select( prefix + '_Geo*' + '_GRP' )
	folList = cmds.ls( sl = True )
	for i in folList:
		cmds.parent( i, prefix + '_Rig_GRP' )

	cmds.parent( prefix + '_000_GEO', prefix + '_001_GEO', prefix + '_000_CRV', prefix + '_Rig_GRP' )
	#color controls
	colorSelection = [ prefix + 'COG_CTLShape', prefix + 'COG_Mid_CTLShape', prefix + 'COG_Btm_CTLShape', prefix + 'Btm_CTLShape', prefix + 'Mid_CTLShape', prefix + 'Top_CTLShape' ]

	for i in colorSelection:
		cmds.setAttr( i + '.overrideEnabled', 1 )
		cmds.setAttr( i + '.overrideColor', 22 )
	cmds.select( clear = True )
	
	# reset global keyframe interpolation types
	print currentIntangent
	print currentOutTangent
	
	cmds.keyTangent( itt = currentIntangent[0], g = True )
	cmds.keyTangent( ott = currentOutTangent[0], g = True )