Example #1
0
def CreatJntAlngCrv():
    selCrv = cmds.ls(sl=1, type='transform')
    Name = cmds.textFieldGrp(NameTextFG, q=1, tx=1)
    IKCtlAmnt = cmds.intSliderGrp(IKCtlintSG, q=1, v=1)
    JntNum = cmds.intSliderGrp(JntNumintSG, q=1, v=1)
    jntAmnt = (JntNum * (IKCtlAmnt - 1)) + 1
    for k in selCrv:
        cmds.setAttr(k + '.visibility', 0)
        cmds.rebuildCurve(k, ch=0, rpo=1, rt=0, end=1, kr=1, kcp=0, kep=1, kt=0, s=jntAmnt - 1, d=3,
                          tol=0.01)  ## Rebuild Crv ##
    preJnt = ""
    rootJnt = ""
    for x in range(len(selCrv)):
        for i in range(0, jntAmnt):
            cmds.select(cl=True)
            newJnt = cmds.joint(n=Name + str(x + 1) + '_joint1')
            motionPath = cmds.pathAnimation(newJnt, c=selCrv[x], fractionMode=True)
            cmds.cutKey(motionPath + ".u", time=())
            cmds.setAttr(motionPath + ".u", i * (1.0 / (jntAmnt - 1)))
            cmds.delete(newJnt + ".tx", icn=True)
            cmds.delete(newJnt + ".ty", icn=True)
            cmds.delete(newJnt + ".tz", icn=True)
            cmds.delete(motionPath)
            if i == 0:
                preJnt = newJnt
                rootJnt = newJnt
                continue
            cmds.parent(newJnt, preJnt)
            preJnt = newJnt
        cmds.joint(rootJnt, e=True, oj="xyz", sao="yup", ch=True, zso=True)  # ---- Orient Joint----#
    selJnt = cmds.ls(Name + "*_joint1", type='joint')
    for a in range(len(selCrv)):  # ---- Orient the End Joint----#
        # print a, SelHi_(selJnt)[a][-1]
        endJnt = SelHi_(selJnt)[a][-1]
        cmds.joint(endJnt, e=1, oj="none", ch=1, zso=1)
Example #2
0
def rebuildByLength(rate):

    sels = cmds.ls(sl=1)

    info = cmds.createNode('curveInfo')
    for sel in sels:
        if cmds.nodeType(sel) == 'transform':
            sel = cmds.listRelatives(sel, s=1)[0]

        if not cmds.isConnected(sel + '.local', info + '.inputCurve'):
            cmds.connectAttr(sel + '.local', info + '.inputCurve', f=1)
        length = cmds.getAttr(info + '.arcLength')
        cmds.rebuildCurve(sel,
                          ch=0,
                          rpo=1,
                          rt=0,
                          end=1,
                          kr=0,
                          kcp=0,
                          kep=0,
                          kt=0,
                          s=length * rate,
                          tol=0.01)

    cmds.delete(info)

    cmds.select(sels)
Example #3
0
def CutRailPieces(curve="", height=1.0, width=1.0):
    mc.delete(curve, ch=True)
    railGeoList = []
    tempCurCurve = [curve]
    mc.rebuildCurve(curve, s=curveLength / trackSegmentLength * 5)

    finalSegmentCurve = mc.detachCurve(
        curve + ".ep[" + str(int(curveLength / trackSegmentLength * 5) - 5) +
        "]",
        rpo=False,
        ch=False)
    finalSegmentGeo = MakeRailPiece(curve=finalSegmentCurve[1],
                                    width=width,
                                    height=height)
    railGeoList.append(finalSegmentGeo)
    mc.delete(finalSegmentCurve[0], finalSegmentCurve[1])
    deleteGroup = []
    for x in range(int(curveLength / trackSegmentLength)):
        tempCurCurve = mc.detachCurve(tempCurCurve[0] + ".ep[5]",
                                      rpo=True,
                                      ch=False)
        curRail = MakeRailPiece(curve=tempCurCurve[1],
                                width=width,
                                height=height)
        railGeoList.append(curRail)
        deleteGroup.append(tempCurCurve[0])
        print "iteration"
    mc.delete(deleteGroup)

    return railGeoList
Example #4
0
def createInterpolatedCurve(curve1, curve2, v):
    interpolatedCurve = mc.duplicate(curve1, rr=True, rc=True)[0]

    for shape in mc.listRelatives(curve2, shapes=True, fullPath=True):
        cvList = (mc.ls([shape + '.cv[*]'], flatten=True))

    mc.rebuildCurve(interpolatedCurve,
                    ch=0,
                    rpo=1,
                    rt=0,
                    end=1,
                    kr=0,
                    kcp=0,
                    kep=1,
                    kt=0,
                    s=len(cvList) - 3,
                    d=3,
                    tol=0)
    for i in range(len(cvList)):
        pos1 = mc.pointPosition('%s.cv[%i]' % (interpolatedCurve, i))
        pos2 = mc.pointPosition('%s.cv[%i]' % (curve2, i))
        newPos = ((pos2[0] - pos1[0]) * v + pos1[0],
                  (pos2[1] - pos1[1]) * v + pos1[1],
                  (pos2[2] - pos1[2]) * v + pos1[2])
        mc.move(newPos[0],
                newPos[1],
                newPos[2],
                '%s.cv[%i]' % (interpolatedCurve, i),
                a=True)

    return interpolatedCurve
Example #5
0
def createCurve(ptList,start,end,group=''):
	'''
	'''
	# Initialize Curves
	crvList = []
	for pt in ptList:
		pos = mc.pointPosition(pt)
		curve = mc.curve(p=[pos,pos],d=1)
		curve = mc.rename(curve,pt+'_curve')
		crvList.append(curve)
	
	# Track Curves
	for i in range(start,end+1):
		mc.currentTime(i)
		for n in range(len(ptList)):
			pos = mc.pointPosition(ptList[n])
			mc.curve(crvList[n],a=True,p=pos)
	
	# Remove Initial CV and Rebuild
	for crv in crvList:
		mc.delete(crv+'.cv[0]')
		mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=2,kcp=True,kep=True)
	
	# Group Curves
	if group:
		# Check Group
		if not mc.objExists(group): group = mc.group(em=True,n=group)
		# Parent Curves to Group
		mc.parent(crvList,group)
	
	# Return Result
	if group: return [group]
	else: return crvList
Example #6
0
def createOnCurve( curve=None, numOfJnts=5, parent=True ):
	"""
	create specified number of joints on input curve
	"""
	curve = curveUtil.getShape(curve)
	if numOfJnts < 2 :
		cmds.error( "number of joints must be greater than 1.")	
	newJnts = []

	curve = cmds.duplicate(curve)[0]
	cmds.rebuildCurve (curve , ch=False ,rpo=True ,rt=0 ,end=1 ,kr=0 ,kcp=False ,kep=True ,kt=0 , s=200 , d=1 , tol=0.01 )
	curveShape = curveUtil.getShape(curve)

	cmds.select(clear=True)
	segSize = 1.0/ (numOfJnts-1)

	for i in range(numOfJnts):
		pos = curveUtil.getPointAtParam(curveShape, segSize*i, 'world')
		if not parent:
			cmds.select(clear=True)
		newJnts.append( cmds.joint(p=pos) )

	cmds.delete(curve)

	return newJnts
Example #7
0
def surface_from_alternate_point(sel_list, name=''):
    """
    Creates surface from alternate point selection
    :param sel_list:
    :param name:
    :return:
    """
    # create interpolated selection list
    start_list = sel_list[::2]
    end_list = sel_list[1::2]
    curve_list = []

    for n, (start, end) in enumerate(zip(start_list, end_list)):
        # create curve from a to b
        curve = curve_from_a_to_b(start, end, name='{}_{:02d}'.format(name, n))
        # rebuild curve to new cv count
        mc.rebuildCurve(curve, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=3, d=3, tol=0.01)
        curve_list.append(curve)

    # loft curves to create surface
    surface = mc.loft(curve_list, name='{}_srf'.format(name),
                      ch=0, u=1, c=0, ar=1, d=3, ss=1, rn=0, po=1, rsn=True)[0]

    # group created nodes
    curve_grp = mc.group(curve_list, name='{}_crv_grp'.format(name))
    main_grp = mc.group(surface, curve_grp, name='{}_srf_grp'.format(name))

    return {'curves': curve_list,
            'surface': surface,
            'container': main_grp}
Example #8
0
 def __init__(self, curve_sel, vertex_list):
     self.curve_sel = curve_sel
     self.verts = vertex_list
     self.find_length = Find_Out()
             
     self.link_length = self.find_length.edge_length(self.verts)
     self.chain_length = self.find_length.curve_length(self.curve_sel)
     self.link_total = int(self.chain_length/self.link_length)
     
     cmds.duplicate(self.curve_sel, n = 'buildCurve')
     cmds.rebuildCurve('buildCurve', ch = 1, rpo = 1, rt = 0, end = 1, kr = 2, kep = 1, kt = 0, kcp = 0, s = self.link_total/2, d = 3, tol = 0.01 )
     
     self.num_cv = int(cmds.getAttr ('buildCurve.degree'))+ (cmds.getAttr ('buildCurve.spans'))
     
     for dummy_cv in range(self.num_cv):
         dummy_cv_pos = (cmds.getAttr ('buildCurve.cv['+ str(dummy_cv) +']'))
         
         if dummy_cv == 0:
             cmds.joint(n=self.curve_sel+'_jointRoot',p = dummy_cv_pos[0])
         elif dummy_cv == self.num_cv - 1:
             cmds.joint(n=self.curve_sel+'_jointEnd', p = dummy_cv_pos[0])
         else:
             cmds.joint(n=self.curve_sel+'_joint_'+(str(dummy_cv)),p = dummy_cv_pos[0])    
     
     cmds.delete('buildCurve')        
     cmds.ikHandle( sj = (self.curve_sel+'_jointRoot'), ee = (self.curve_sel+'_jointEnd'), c = self.curve_sel,
             sol = 'ikSplineSolver', scv = 0, pcv = 0, ccv = 0, ns = 4)       
        def finalize(self):
            log.debug("returnList: %s"% self.returnList)
            log.debug("createdList: %s"% self.createdList)   
            buffer = [] #self.i_module.templateNull.templateStarterData
            log.debug("starting data: %s"% buffer)
            
            #Make sure we have enough points
            #==============  
            handles = self.i_module.templateNull.handles
            if len(self.returnList) < handles:
                log.warning("Creating curve to get enough points")                
                curve = curves.curveFromPosList(self.returnList)
                mc.rebuildCurve (curve, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0,s=(handles-1), d=1, tol=0.001)
                self.returnList = curves.returnCVsPosList(curve)#Get the pos of the cv's
                mc.delete(curve)

            #Store info
            #==============                  
            for i,p in enumerate(self.returnList):
                buffer.append(p)#need to ensure it's storing properly
                #log.info('[%s,%s]'%(buffer[i],p))
                
            #Store locs
            #==============  
            log.debug("finish data: %s"% buffer)
            self.templateNull.__setattr__('templateStarterData',buffer,lock=True)
            #self.i_module.templateNull.templateStarterData = buffer#store it
            log.info("'%s' sized!"%self.i_module.getShortName())
            dragFactory.clickMesh.finalize(self)
Example #10
0
def make_curve():
	new_curve = cmds.polyToCurve(degree=1, form=2, conformToSmoothMeshPreview=1)[0]
	spans =  num_spans(new_curve) *2
	cmds.rebuildCurve(new_curve, rt=0, ch=1, end=1, d=3, kr=2, s=spans, kcp=0, tol=0.01, kt=0, rpo=1, kep=1)
	first_cv = new_curve + '.cv[0]'
	cmds.move(0.0001, 0.0001, 0.0001, first_cv ,r=True, )
	return new_curve
Example #11
0
def createCurveaBasedOnLocator( prevLoc, loc, baseName, hrsSys ):
	leastSquaresMod = mn.createNode( 'leastSquaresModifier' )
	origCurv = crv.Curve( mc.curve( d = 1, ep = [prevLoc.worldPosition, loc.worldPosition] ) )
	index = mm.eval( 'getNextFreeMultiIndex( "'+ hrsSys.name +'.inputHair", 0 )' )
	origCurv.name = 'spiderWeb_base_'+ baseName + '_' + str( index ) + '_CRV'
	mc.rebuildCurve( origCurv.name, rpo = 1, rt = 0, end = 1, kr = 0, kcp = 1, kep = 1, kt =0, s= 4, d = 1, tol = 0.01  )
	origCurv.a.intermediateObject.v = 1
	controledCurv = origCurv.duplicate()
	origCurv.shape.attr( 'worldSpace[0]' ) >> leastSquaresMod.a.inputNurbsObject
	prevLoc.attr( 'worldPosition[0]')      >> leastSquaresMod.attr( 'pointConstraint[0].pointPositionXYZ' )
	leastSquaresMod.attr( 'pointConstraint[0].pointConstraintU' ).v = 0
	loc.attr( 'worldPosition[0]')          >> leastSquaresMod.attr( 'pointConstraint[1].pointPositionXYZ' )
	leastSquaresMod.attr( 'pointConstraint[1].pointConstraintU' ).v = 1
	leastSquaresMod.a.outputNurbsObject    >> controledCurv.shape.a.create
	controledCurv.shape.attr( 'worldMatrix[0]' ) >> leastSquaresMod.a.worldSpaceToObjectSpace
	fol = mn.createNode( 'follicle' )
	fol.a.restPose.v = 1
	fol.a.startDirection.v = 1
	fol.a.pointLock.v = 3
	fol.a.degree.v = 3
	fol.a.sampleDensity.v = 3
	fol.a.outHair >> hrsSys.attr( 'inputHair[' + str( index ) + ']' )
	hrsSys.attr( 'outputHair[' + str( index ) + ']' ) >> fol.a.currentPosition
	controledCurv.shape.attr( 'worldSpace[0]' ) >> fol.a.startPosition
	curv = crv.Curve( mc.curve( d = 3, ep = [prevLoc.worldPosition, loc.worldPosition] ) )
	curv.name = 'spiderWeb_' + baseName + '_' + str( index ) + '_CRV'
	fol.a.outCurve >> curv.a.create
	folPar = fol.parent
	folPar.name = 'spiderWeb_' + baseName + '_' + str( index ) + '_FOL'
	return curv, folPar
Example #12
0
def twoPointCurve(node1, node2, degree=1):
    """Creates a degree 3 NURBS curve from two input objects """
    crvCmd = 'cmds.curve(degree=1, p=['
    startEndCtrls = [node1, node2]
    for ctrl in startEndCtrls:
        tfm = cmds.xform(ctrl, query=True, worldSpace=True, translation=True)
        crvCmd += ' ('
        for tfmItem in tfm:
            crvCmd += ' ' + str(tfmItem) + ','
        crvCmd += '),'

    crvCmd += '], k=[0,1])'
    crv = cmds.python(crvCmd)
    if degree > 1:
        cmds.rebuildCurve(crv,
                          ch=0,
                          rpo=1,
                          rt=0,
                          end=1,
                          kr=0,
                          kcp=0,
                          kep=1,
                          kt=0,
                          s=4,
                          d=degree,
                          tol=0.01)
    crv = cmds.rename(crv, "{}_crv".format(node1))
    crvShp = cmds.listRelatives(crv, shapes=True)[0]
    return crv, crvShp
def ldmt_pfxToCurves():
    if cmds.currentCtx() == 'dynWireCtx1':
        new = cmds.ls(sl=True)
        if not new:
            return
        whichNode = cmds.ls(cmds.listRelatives(new, s=True)[0], st=True)[1]
        if whichNode == 'stroke':
            newStroke = new[0]
            cmds.select(newStroke, r=True)
            #            return
            mel.eval('doPaintEffectsToCurve(1);')
            st = cmds.listRelatives(newStroke, s=True)[0]
            c = cmds.listConnections(st, et=True, t='nurbsCurve')[0]
            cmds.rebuildCurve(c,
                              ch=1,
                              rpo=1,
                              rt=0,
                              end=1,
                              kr=0,
                              kcp=0,
                              kep=1,
                              kt=0,
                              s=10,
                              d=3,
                              tol=0.01)
            cmds.select(cl=True)
            strokeMainCurves = cmds.listRelatives(c, ap=1)
            strokeCurve = cmds.listRelatives(strokeMainCurves, ap=1)
            cmds.ungroup(strokeCurve)
            cmds.ungroup(strokeMainCurves)
            cmds.evalDeferred('cmds.delete("' + newStroke + '")')
Example #14
0
def getLoftSurfaceFromSelCurves(sels, close=False):

    import sgBFunction_dag

    poses = []

    for sel in sels:
        pos = om.MPoint(*cmds.xform(sel + '.cv[0]', q=1, ws=1, t=1))
        poses.append(pos)

    targetIndices = [0]

    nextIndex = 0
    for i in range(len(poses)):
        minDist = 100000.0
        minDistIndex = nextIndex
        for j in range(1, len(poses)):
            if nextIndex == j: continue
            if j in targetIndices: continue
            dist = poses[nextIndex].distanceTo(poses[j])
            if dist < minDist:
                minDist = dist
                minDistIndex = j
        nextIndex = minDistIndex
        if minDistIndex in targetIndices: continue
        targetIndices.append(minDistIndex)

    cmds.select(d=1)
    for i in targetIndices:
        cmds.select(sels[i], add=1)

    sels = cmds.ls(sl=1)
    allSpans = 0
    for sel in sels:
        selShape = sgBFunction_dag.getShape(sel)
        allSpans += cmds.getAttr(selShape + '.spans')

    eachSpan = int(allSpans / len(sels))

    for sel in sels:
        cmds.rebuildCurve(sel, ch=0, s=eachSpan)

    loftNode = cmds.createNode('loft')
    cmds.setAttr(loftNode + '.close', close)
    reverseNode = cmds.createNode('reverseSurface')
    cmds.setAttr(reverseNode + '.direction', 3)
    for i in range(len(sels)):
        sel = sels[i]
        selShape = sgBFunction_dag.getShape(sel)
        cmds.connectAttr(selShape + '.worldSpace',
                         loftNode + '.inputCurve[%d]' % i)

    cmds.connectAttr(loftNode + '.outputSurface',
                     reverseNode + '.inputSurface')
    surf = cmds.createNode('nurbsSurface')
    cmds.connectAttr(reverseNode + '.outputSurface', surf + '.create')
    surfaceObj = cmds.listRelatives(surf, p=1, f=1)[0]
    cmds.sets(surfaceObj, e=1, forceElement='initialShadingGroup')

    return surfaceObj
Example #15
0
def makeCurveDynamic(curveName):
    dynamicHair = cmds.createNode('hairSystem')
    nucleus = cmds.createNode('nucleus')

    cmds.connectAttr('time1.outTime', dynamicHair + '.currentTime')
    cmds.connectAttr('time1.outTime', nucleus + '.currentTime')

    cmds.connectAttr(nucleus + '.startFrame', dynamicHair + '.startFrame')
    cmds.connectAttr(nucleus + '.outputObjects[0]', dynamicHair + '.nextState')
    cmds.connectAttr(dynamicHair + '.currentState', nucleus + '.inputActive[0]')
    cmds.connectAttr(dynamicHair + '.startState', nucleus + '.inputActiveStart[0]')

    cmds.rebuildCurve('Tentacle_curve', rt=0, spans=50, ch=0, replaceOriginal=1)
    _follicle = cmds.createNode('follicle')
    _nurbsCurve = cmds.createNode('nurbsCurve')

    cmds.connectAttr(dynamicHair + '.outputHair[%s]' % (1), _follicle + '.currentPosition')
    cmds.connectAttr(_follicle + '.outHair', dynamicHair + '.inputHair[%s]' % (1))
    # connect follicle node to input curve
    cmds.connectAttr('Tentacle_curve' + '.local', _follicle + '.startPosition')
    cmds.connectAttr('Tentacle_curve' + '.worldMatrix[0]', _follicle + '.startPositionMatrix')
    # connect follicle node to output curve
    cmds.connectAttr(_follicle + '.outCurve', _nurbsCurve + '.create')

    #create IK Spline handle from the current Curve

    ikh, effector, curve = cmds.ikHandle(
        name='{0}_ikh'.format('Tentacle_curve'), solver='ikSplineSolver',
        startJoint='tentacle_jnt1', endEffector='tentacle_jnt11', parentCurve=False, autoCreateCurve = False,
        simplifyCurve=False)
    effector = cmds.rename(effector, '{0}_eff'.format('Tentacle_curve'))
    curve = cmds.rename(curve, '{0}_crv'.format('Tentacle_curve'))
Example #16
0
    def _attach_to_curve(self, joints, side="lower", crvShape=None):

        #rebuild curve first
        cmds.rebuildCurve(crvShape,
                          rpo=1,
                          rt=0,
                          end=1,
                          kr=0,
                          kcp=0,
                          kep=1,
                          kt=0,
                          s=4,
                          d=3,
                          tol=0.01)

        for i, joint in enumerate(joints):
            num = ` i `.zfill(2)
            crvInfo = cmds.createNode('pointOnCurveInfo',
                                      n="%s_%s_%s_crvInfo" %
                                      (self._side, side, num))
            cmds.connectAttr("%s.worldSpace[0]" % crvShape,
                             "%s.inputCurve" % crvInfo,
                             f=True)
            if i == 0:
                param = i
            else:
                param = i + 1
            cmds.setAttr("%s.parameter" % crvInfo, i / (self._zipJoints - 1))

            cmds.connectAttr("%s.position" % crvInfo,
                             "%s.translate" % joint,
                             f=True)
Example #17
0
def generateCurve(segments, name, namespace):
    '''
	This function generates a curve that passes through each item in the user selection.
	It does so by querying xform to get position values of each item in the list, and then
	appending them to a list to be used as CV points on the curve. The curve is then converted
	to NURBS and rebuild, allowing it to be used with Hair dynamics.
	'''
    locators = cmds.ls(selection=True)  #creates a list of the user selection
    numOfLocators = len(locators)
    locatorPositions = []  #an empty tuple for storing coordinates
    for locator in locators:
        pos = cmds.xform(
            locator, q=True, ws=True,
            t=True)  #queries the xform coordinates for each item in the list
        locatorPositions.append(tuple(pos))  #appends the coordinates to a list
    outputCurve = cmds.curve(
        bezier=True,
        point=locatorPositions,
        degree=numOfLocators - 1,
        name=str(namespace) + 'curve#' +
        str(name))  #uses the list of coordinates for CV points on the curve.
    selectchild(outputCurve)
    cmds.bezierCurveToNurbs(
    )  #the curves need to be converted to NURBS so that they can be rebuilt with uniform spans.
    selectchild(outputCurve)
    cmds.rebuildCurve(
        spans=segments
    )  #this is because there needs to be a sufficient number of points on each curve for the attachCurve command to work later on.
    return outputCurve
Example #18
0
def crvTendon(curve,geo,precision=4,prefix='tendon'):
	'''
	'''
	# rebuildCurve degree 1
	baseCurve = mc.rebuildCurve(curve,ch=0,s=1,d=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1)
	
	# create cv locators
	baseLocs = glTools.utils.curve.locatorCurve(baseCurve,prefix=prefix+'_baseCrv')
	
	# generate geo constraint curve
	geoCurve = mc.rebuildCurve(baseCurve,ch=1,s=precsion,d=1,rpo=0,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1)
	geoCurveLocs = glTools.utils.curve.locatorCurve(geoCurve,prefix=prefix+'_geoCrv')
	
	# generate reference curve
	refCurve = mc.rebuildCurve(baseCurve,ch=1,s=precsion,d=1,rpo=0,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1)
	refCurveInfo = mc.createNode('curveInfo',n=prefix+'_ref_curveInfo')
	mc.connectAttr(refCurve+'.worldSpace[0]',refCurveInfo+'.inputCurve',f=True)
	refCurveLocs = []
	for i in range(precsion+1):
		refNull = mc.group(em=True,n=prefix+'_ref'+str(i)+'_null')
		mc.connectAttr(refCurveInfo+'.controlPoints['+str(i)+']',refNull+'.t')
		refCurveLocs.append(refNull)
	
	# Locator Constraints
	for i in range(precsion+1):
		mc.pointConstraint(refCurveLocs[i],geoCurveLocs[i])
		mc.geometryConstraint(geo,geoCurveLocs[i])
		
	# fitBspline
	bSpline = mc.fitBspline(geoCurve,ch=1)
Example #19
0
def build(curve=None, numOfJnts=10, name="brow"):
    # soften input curve and delete history
    curve = util.rename(curve, name=(name + "Low"), suffix="crv")[0]
    curve = curveUtil.getShape(curve=curve)
    cmds.rebuildCurve(curve,
                      ch=0,
                      rpo=1,
                      rt=0,
                      end=1,
                      kr=0,
                      kcp=1,
                      kep=1,
                      kt=0,
                      s=4,
                      d=3,
                      tol=0.01)[0]
    cmds.makeIdentity(curve, apply=True, t=1, r=1, s=1)

    # create the high res curve
    curveHigh = cmds.rebuildCurve(curve,
                                  ch=0,
                                  rpo=0,
                                  rt=0,
                                  end=1,
                                  kr=0,
                                  kcp=0,
                                  kep=1,
                                  kt=0,
                                  s=numOfJnts,
                                  d=1,
                                  tol=0.01)[0]
    curveHigh = util.rename(curveHigh, name=(name + "High"), suffix="crv")[0]

    return curve, curveHigh
Example #20
0
    def create(self, *args):
        # field get
        temp_joint.num = int(
            mc.intField('jntNum', q=True, value=True))
        temp_joint.name = str(
            mc.textField('tempJntName', q=True, text=True))
        stretch_joint.name = str(
            mc.textField('stretchJntName', q=True, text=True))

        # curve rebuild
        name_list = mc.ls(sl=True)
        curve.name = name_list[0]

        # shape node name edit
        mc.rename(curve.name, 'tempCurveName')
        mc.rename('tempCurveName', curve.name)
        mc.rebuildCurve(kr=0)
        mc.select(d=True)

        # short name
        s.tn = '%s_%s' % (curve.name, temp_joint.name)
        s.sn = '%s_%s' % (curve.name, stretch_joint.name)

        # crate temp temp_joint
        for i in range(temp_joint.num):
            mc.joint(p=(0, 0, 0), n='%s%s' % (s.tn, str(i + 1)))
            mc.select(d=True)
            p = 'pointOnCurveInfo'
            mc.createNode('%s' % p, n='%s_%s%s' % (p, s.tn, str(i + 1)))
            node_name = '%s_%s%s' % (p, s.tn, str(i + 1))
            mc.connectAttr(
                '%sShape.local' % curve.name,
                '%s.inputCurve' % node_name)
            mc.setAttr(
                '%s.parameter' % node_name,
                (float(1) / (temp_joint.num - 1)) * i)
            mc.connectAttr(
                '%s.position' % node_name,
                '%s%s.translate' % (s.tn, str(i + 1)))
        for i in range(temp_joint.num):
            mc.select('%s%s' % (s.tn, str(i + 1)), add=True)
        mc.group(n='%s_grp' % s.tn)
        mc.setAttr('.visibility', 0)
        mc.select(d=True)

        # aim constraint
        for i in range(temp_joint.num - 1):
            first = '%s%s' % (s.tn, str(i + 1))
            second = '%s%s' % (s.tn, str(i + 2))
            mc.aimConstraint(second, first)

        # create stretch joint
        for i in range(temp_joint.num):
            mc.joint(p=(0, 0, 0), n='%s%s' % (s.sn, str(i + 1)))
        for i in range(temp_joint.num):
            first = '%s%s' % (s.tn, str(i + 1))
            second = '%s%s' % (s.sn, str(i + 1))
            mc.parentConstraint(first, second)
        mc.select(d=True)
Example #21
0
def makeCenterCurveFromCurves(crvs, rebuildSpanRate=1.0):

    crvShapes = []
    for crv in crvs:
        crvShape = sgModelDag.getShape(crv)
        if not crvShape: continue

        crvShapes.append(crvShape)

    lengthAll = 0.0
    crvInfo = cmds.createNode('curveInfo')
    for crvShape in crvShapes:
        if not cmds.isConnected(crvShape + '.local', crvInfo + '.inputCurve'):
            cmds.connectAttr(crvShape + '.local', crvInfo + '.inputCurve', f=1)
        length = cmds.getAttr(crvInfo + '.arcLength')
        lengthAll += length
    cmds.delete(crvInfo)

    lengthAverage = lengthAll / len(crvShapes)

    rebuildSpans = int(lengthAverage * rebuildSpanRate)

    for crvShape in crvShapes:
        cmds.rebuildCurve(crvShape,
                          constructionHistory=0,
                          replaceOriginal=1,
                          rebuildType=0,
                          endKnots=1,
                          keepRange=0,
                          keepControlPoints=0,
                          keepEndPoints=1,
                          keepTangents=0,
                          s=rebuildSpans,
                          d=3,
                          tol=0.01)

    fnNurbsCurve = om.MFnNurbsCurve(sgModelDag.getDagPath(crvShapes[0]))
    numCVs = fnNurbsCurve.numCVs()

    points = []
    for i in range(numCVs):
        points.append([0, 0, 0])

    curve = cmds.curve(p=points, d=3)

    for i in range(numCVs):
        sumPoints = om.MVector(0, 0, 0)
        for crvShape in crvShapes:
            sumPoints += om.MVector(*cmds.xform(
                crvShape + '.controlPoints[%d]' % i, q=1, ws=1, t=1))
        averagePoints = sumPoints / len(crvShapes)
        cmds.move(averagePoints.x,
                  averagePoints.y,
                  averagePoints.z,
                  curve + '.controlPoints[%d]' % i,
                  os=1)

    return curve
Example #22
0
def generateSpider(input_namespace, startTime, endTime):
    '''
	this function attaches all curves together, without replacing the orignal curves, using it as a motion path
	for an animated spider. the animated spider is imported, and a simple expression links the U value of the motion
	path to a rotation attribute on the spider rig, controlling its walk cycle. there is also a custom attribute on
	the controller that appears with the spider rig, controlling the length of its steps as it walks.
	'''
    filePath = cmds.internalVar(
        usd=True
    ) + 'SpiderGen/spider.ma'  #the file path at which the spider model should exist
    fileExists = cmds.file(filePath, q=True,
                           ex=True)  #queries whether the file exists

    if fileExists is True:
        #selects all of the spiralling curves and connects them, providing a 'path' for the spiders movement.
        cmds.select(str(input_namespace) + 'curve_spiral*')
        curves = cmds.ls(selection=True)
        path = cmds.attachCurve(curves,
                                n=str(input_namespace) + 'spiderpath',
                                rpo=False)
        cmds.rebuildCurve(path, rt=3)
        cmds.hide(path)
        cmds.file(filePath, i=True)

        #renames the spider and it's callable controllers so that they are using the current 'namespace'.
        cmds.rename('SPIDER_RIG', str(input_namespace) + 'SPIDER_RIG')
        cmds.rename('SCALE_HANDLE',
                    str(input_namespace) + 'CONTROLLER_ScaleMe')
        cmds.rename('CONTROLLER', str(input_namespace) + 'CONTROLLER')

        #selects the scale controller and the path and connects them to a path animation.
        cmds.select(str(input_namespace) + 'CONTROLLER_ScaleMe', path)
        cmds.pathAnimation(stu=startTime,
                           etu=endTime,
                           f=True,
                           fa='x',
                           ua='y',
                           name=str(input_namespace) + 'motionpath')

        #creates a command that links the controller rotation to the 'length' of the animation.
        command = str(input_namespace) + 'CONTROLLER.rotateX = ' + str(
            input_namespace) + 'motionpath_uValue.output * ' + str(
                (endTime - startTime) / 10)
        #creates an expression of that command which is used for moving the legs as the spider moves around the path.
        cmds.expression(name=str(input_namespace) + 'leg_movement',
                        alwaysEvaluate=True,
                        s=command)
    else:
        #an error window for if the file is not found
        cmds.confirmDialog(
            title='Error',
            message='Spider Model not found, please ensure it located at: ' +
            str(filePath),
            button=['OK'],
            cancelButton='OK')

    return fileExists  #so that the grouping functions know not to expect the spider model or motionpath
	def doIt(self, args):
		# Initialise values
		self.name = "CaveNode"
		self.depthValue = 1.0
		self.rebuild = False
		# Check if the arguments were parsed correctly
		if (self.parseArguments(args) == True):
			if self.rebuild == True:
				mc.rebuildCurve(self.curveName, kr=0, rt=4)
			self.redoIt()
Example #24
0
    def ctrlLayout(cls, crv, numOfCtrl, numOfSpan, increNum, *args):
        # Initialize un value.
        unNum = 0

        reCrvOpt = cmds.checkBoxGrp(cls.uiWdgDic['preChkBoxGrp'],
                                    q=True,
                                    v1=True)
        if reCrvOpt:
            # Rebuild curve's control points uniformly for even joint distribution.
            cmds.rebuildCurve(crv,
                              ch=1,
                              rpo=1,
                              rt=0,
                              end=1,
                              kr=0,
                              kcp=0,
                              kep=1,
                              kt=0,
                              s=numOfSpan,
                              d=3,
                              tol=0)

        # Delete curve bind joint chain if exists it.
        if cmds.objExists('%s_*_crv_bnd_jnt' % crv):
            cmds.delete('%s_*_crv_bnd_jnt' % crv)

        # Build joint chain hierarchy for orient joints.
        cmds.select(cl=True)
        cls.crvBndJntLs = []
        for i in xrange(numOfCtrl):
            crvBndJntPos = cmds.pointPosition('%s.un[%f]' % (crv, unNum),
                                              w=True)
            crvBndJnt = cmds.joint(p=crvBndJntPos,
                                   n='%s_%d_crv_bnd_jnt' % (crv, i),
                                   radius=10)
            cls.crvBndJntLs.append(crvBndJnt)
            unNum += increNum
        cmds.CompleteCurrentTool()

        # Orient curve bind joints
        oriJntOpt = cmds.checkBoxGrp(cls.uiWdgDic['preChkBoxGrp'],
                                     q=True,
                                     v2=True)
        if oriJntOpt:
            cls.orientJntChain(cls.crvBndJntLs)

        # Unparent curve bind joints.
        for crvBndJnt in cls.crvBndJntLs:
            if cmds.listRelatives(crvBndJnt, p=True):
                cmds.parent(crvBndJnt, w=True)
            else:
                pass

        return cls.crvBndJntLs
 def doIt(self, args):
     # Initialise values
     self.depthValue = 1.0
     self.widthValue = 1.0
     self.name = "RiverNode"
     self.curve = None
     self.rebuild = False
     if (self.parseArguments(args) == True):
         if self.rebuild == True:
             mc.rebuildCurve(self.curve, kr=0, rt=4)
         self.redoIt()
Example #26
0
def make_ikspline_stretchy(*args):
    '''main function to make joints stretching'''
    try:
        #get data of IKfandle and joint
        selected_ikHandle = cmds.ls(sl=True)[0]
        ikJoints = cmds.ikHandle(selected_ikHandle, q=True, jl=True)
        numberOfBones = len(ikJoints)
        ikCurve = cmds.ikHandle(selected_ikHandle, q=True, c=True)
        cmds.rebuildCurve(ikCurve, rt=0, kr=0, d=4, s=1)
        curveInfo = cmds.arclen(ikCurve, ch=True)
        #create Node of length
        multiDivArclen = cmds.shadingNode('multiplyDivide', asUtility=True)
        cmds.setAttr(multiDivArclen + '.operation', 2)
        cmds.addAttr(multiDivArclen, ln="stretchy", at='double', dv=0, k=True)
        #connect curve length
        cmds.connectAttr(curveInfo + '.arcLength',
                         multiDivArclen + '.input1X',
                         f=True)
        cmds.connectAttr(multiDivArclen + '.outputX',
                         multiDivArclen + '.stretchy',
                         f=True)
        input2X = cmds.getAttr(multiDivArclen + '.input1X')
        cmds.setAttr(multiDivArclen + '.input2X',
                     input2X)  #multDivArclen.OutputX == 1
        #create Node of thickness
        multiDivThickness = cmds.shadingNode('multiplyDivide', asUtility=True)
        cmds.setAttr(multiDivThickness + '.operation', 3)
        cmds.connectAttr(multiDivArclen + '.stretchy',
                         multiDivThickness + '.input1X',
                         f=True)
        cmds.setAttr(multiDivThickness + '.input2X', -0.5)
        #cmds.addAttr( multiDivArclen, ln="stretchy", at='double', dv=0, k=True)

        cmds.cluster(ikCurve + '.cv[3]', n="cluster_end")
        cmds.cluster(ikCurve + '.cv[0]',
                     ikCurve + '.cv[1]',
                     ikCurve + '.cv[2]',
                     n="cluster_root")

        for i in range(numberOfBones):
            cmds.connectAttr(multiDivArclen + '.stretchy',
                             ikJoints[i] + '.scaleX',
                             f=True)
            if i > 0 and i < numberOfBones:
                cmds.connectAttr(multiDivThickness + '.outputX',
                                 ikJoints[i] + '.scaleY',
                                 f=True)
                cmds.connectAttr(multiDivThickness + '.outputX',
                                 ikJoints[i] + '.scaleZ',
                                 f=True)
            #cmds.connectAttr( outMultDiv+'.outputX', item+'.scaleX', f=True)
    except:
        print "no curve selected"
def rebuildCrv(_depth):
    cm.rebuildCurve(cm.ls(sl=True),
                    ch=True,
                    rpo=True,
                    rt=False,
                    end=True,
                    kr=False,
                    kcp=False,
                    kep=True,
                    kt=False,
                    s=_depth,
                    tol=0.01)
Example #28
0
def build( curve=None, numOfJnts=10, name="brow" ):
	# soften input curve and delete history
	curve = util.rename(curve, name=(name+"Low"), suffix="crv")[0]
	curve = curveUtil.getShape( curve=curve )
	cmds.rebuildCurve(curve, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=1, kep=1, kt=0, s=4, d=3, tol=0.01 )[0]
	cmds.makeIdentity(curve, apply=True, t=1, r=1, s=1 )

	# create the high res curve
	curveHigh = cmds.rebuildCurve(curve, ch=0, rpo=0, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=numOfJnts, d=1, tol=0.01 )[0]
	curveHigh = util.rename(curveHigh, name=(name+"High"), suffix="crv")[0]

	return curve, curveHigh
Example #29
0
def buidleUpCurve(startOBJ, endObj, upOBJ):
    startPosition = mc.xform(startOBJ, q=True, ws=True, t=True) 
    endPosition   = mc.xform(endObj,   q=True, ws=True, t=True) 
    upPosition    = mc.xform(upOBJ,    q=True, ws=True, t=True) 
    offsetVector  = (upPosition[0] - startPosition[0]) * 0.25, (upPosition[1] - startPosition[1]) * 0.25, (upPosition[2] - startPosition[2]) * 0.25
    
    startPosition = (startPosition[0] + offsetVector[0]), (startPosition[1] + offsetVector[1]), (startPosition[2] + offsetVector[2])
    endPosition   = (endPosition[0]   + offsetVector[0]), (endPosition[1] +   offsetVector[1]), (endPosition[2] +   offsetVector[2])
    
    Curve = mc.curve(d=1, p=(startPosition, endPosition))
    mc.rebuildCurve(Curve, ch=0, s=3, d=3)
    return Curve
Example #30
0
def buidleUpCurve(startOBJ, endObj, upOBJ):
    startPosition = mc.xform(startOBJ, q=True, ws=True, t=True) 
    endPosition   = mc.xform(endObj,   q=True, ws=True, t=True) 
    upPosition    = mc.xform(upOBJ,    q=True, ws=True, t=True) 
    offsetVector  = (upPosition[0] - startPosition[0]) * 0.25, (upPosition[1] - startPosition[1]) * 0.25, (upPosition[2] - startPosition[2]) * 0.25
    
    startPosition = (startPosition[0] + offsetVector[0]), (startPosition[1] + offsetVector[1]), (startPosition[2] + offsetVector[2])
    endPosition   = (endPosition[0]   + offsetVector[0]), (endPosition[1] +   offsetVector[1]), (endPosition[2] +   offsetVector[2])
    
    Curve = mc.curve(d=1, p=(startPosition, endPosition))
    mc.rebuildCurve(Curve, ch=0, s=3, d=3)
    return Curve
 def doIt(self, args):
     # Initialise values
     self.name = "SculptLayerNode"
     self.sculptStrength = 1.0
     self.curveOffset = 1.1
     self.maxProjection = 1000
     self.rebuild = False
     self.parseArguments(args)
     # Check if the arguments were parsed correctly
     if self.rebuild == True:
         mc.rebuildCurve(self.curveMask, kr=0, rt=4)
     self.redoIt()
Example #32
0
	def  RebuildWithNCVs (self,numberOfCvs,curve ):
		if cmds.getAttr (curve+".form")==2:
			if numberOfCvs >= 3:
				curve = cmds.rebuildCurve(curve, spans = numberOfCvs,keepRange = 2)[0]
				return curve
			else:
				return None
		else:
			if numberOfCvs >= 4:
				curve = cmds.rebuildCurve(curve, spans = numberOfCvs - 3,keepRange = 2)[0]
				return curve
			else:
				return None
Example #33
0
def createInterpolatedCurve(curve1, curve2, v):
	interpolatedCurve = mc.duplicate(curve1, rr=True, rc=True)[0]

	for shape in mc.listRelatives(curve2,shapes=True,fullPath=True):
		cvList = (mc.ls([shape+'.cv[*]'],flatten=True))
	
	mc.rebuildCurve(interpolatedCurve, ch=0, rpo=1, rt= 0, end = 1, kr = 0, kcp = 0, kep = 1, kt = 0, s = len(cvList)-3, d = 3, tol = 0)
	for i in range(len(cvList)):
		pos1 = mc.pointPosition('%s.cv[%i]' % (interpolatedCurve,i))
		pos2 = mc.pointPosition('%s.cv[%i]' % (curve2,i))
		newPos = ((pos2[0]-pos1[0])*v+pos1[0], (pos2[1]-pos1[1])*v+pos1[1], (pos2[2]-pos1[2])*v+pos1[2])    
		mc.move(newPos[0], newPos[1], newPos[2], '%s.cv[%i]' % (interpolatedCurve,i), a=True)

	return interpolatedCurve
Example #34
0
def preparecurve(crv, crvtrm, frac):
    cmds.polyToCurve(f=3, dg=3, n='tmpcrv')
    cmds.duplicate('tmpcrv', n=crvtrm)
    cmds.delete('tmpcrv')
    cmds.rebuildCurve(crv,
                      s=frac,
                      kr=2,
                      d=3,
                      tol=0.01,
                      rt=0,
                      kep=1,
                      kt=0,
                      kcp=0,
                      end=1)
Example #35
0
def makeCenterCurve( crvs, rebuildSpanRate= 1.0 ):
    
    crvShapes = []
    for crv in crvs:
        crvShape = getShape( crv )
        if not crvShape: continue
        
        crvShapes.append( crvShape )
        
    lengthAll = 0.0
    crvInfo = cmds.createNode( 'curveInfo' )
    for crvShape in crvShapes:
        if not cmds.isConnected( crvShape+'.local', crvInfo+'.inputCurve' ):
            cmds.connectAttr( crvShape+'.local', crvInfo+'.inputCurve', f=1 )
        length = cmds.getAttr( crvInfo+'.arcLength' )
        lengthAll += length
    cmds.delete( crvInfo )
    
    lengthAverage = lengthAll / len( crvShapes )
    
    rebuildSpans = int( lengthAverage * rebuildSpanRate )
    
    for crvShape in crvShapes:
        cmds.rebuildCurve( crvShape, constructionHistory=0, 
                           replaceOriginal=1, 
                           rebuildType=0, 
                           endKnots=1, 
                           keepRange=0, 
                           keepControlPoints=0, 
                           keepEndPoints=1, 
                           keepTangents=0,
                           s=rebuildSpans, d=3, tol=0.01 )
    
    fnNurbsCurve = om.MFnNurbsCurve( getDagPath( crvShapes[0] ) )
    numCVs = fnNurbsCurve.numCVs()
    
    points = []
    for i in range( numCVs ):
        points.append( [0,0,0] )
    
    curve = cmds.curve( p=points, d=3 )
    
    for i in range( numCVs ):
        sumPoints = om.MVector(0,0,0)
        for crvShape in crvShapes:
            sumPoints += om.MVector( *cmds.xform( crvShape+'.controlPoints[%d]' % i, q=1, os=1, t=1 ) )
        averagePoints = sumPoints / len( crvShapes )
        cmds.move( averagePoints.x, averagePoints.y, averagePoints.z, curve+'.controlPoints[%d]' % i, os=1 )
        
    return curve
Example #36
0
 def CurveShapes(self):
     getSel=self.selection_grab()
     if getSel:
         pass
     else:
         return
     getNames=cmds.ls(sl=1, fl=1)
     if ".e[" not in str(getNames[0]):
         print "selection needs to be continuous edges of two seperate polygon objects: first select one, then continuous edge and then the continuous edge on a seperate poly object that you want to deform it along"
         return
     else:
         pass
     getFirstGrp = getNames[0].split(".")[0]
     getSecondGrp = getNames[-1:][0].split(".")[0]
     if getFirstGrp == getSecondGrp:
         print "Only one poly object has been detected. Select one object and it's continuous edge and then select another object and select it's continuous edge for the first object to align to."
         return
     else:
         pass
     firstList=[(each) for each in getNames if each.split(".")[0]==getFirstGrp]
     secondList=[(each) for each in getNames if each.split(".")[0]==getSecondGrp]
     '''create childfirst curve'''
     cmds.select(firstList)
     cmds.CreateCurveFromPoly()
     getFirstCurve=cmds.ls(sl=1, fl=1)
     '''get cv total of curve'''
     getFirstCurveInfo=cmds.ls(sl=1, fl=1)
     numberCV=str(pm.PyNode(getFirstCurveInfo[0]).numCVs())
     cmds.delete(getFirstCurve[0], ch=1)
     '''wrap child mesh to curve'''
     cmds.select(cmds.ls(getFirstGrp)[0], r=1)
     cmds.wire(w=getFirstCurve[0], gw=0, en=1.000000, ce=0.000000, li=0.000000, dds=[(0, 500)] )
     '''create parent curve'''
     cmds.select(secondList)
     cmds.CreateCurveFromPoly()
     getSecondCurve=cmds.ls(sl=1, fl=1)
     getSecondCurveInfo=cmds.ls(sl=1, fl=1)
     '''rebuilt curve to match first curve built'''
     cmds.rebuildCurve(getSecondCurve[0], getFirstCurve[0], rt=2 )
     getSecondCurve=cmds.ls(sl=1, fl=1)
     getSecondCurveInfo=cmds.ls(sl=1, fl=1)
     cmds.delete(getSecondCurve[0], ch=1)
     '''wrap parent curve to parent mesh'''
     cmds.select(getSecondCurve[0], r=1)
     cmds.select(cmds.ls(getSecondGrp)[0], add=1)
     cmds.CreateWrap()
     '''blend child curve to parent curve'''
     cmds.blendShape(getSecondCurve[0], getFirstCurve[0],w=(0, 1.0))
     return getFirstGrp, getSecondGrp
Example #37
0
def matchCurve(source, destination, *args, **kwargs):
    # Source
    if cmds.objectType(source) == 'transform':
        try:
            source = cmds.listRelatives(source, shapes=True)[0]
        except RuntimeError:
            raise TypeError('Source must be a nurbs curve.')

    sourceMin = cmds.getAttr('{}.minMaxValue.minValue'.format(source))
    sourceMax = cmds.getAttr('{}.minMaxValue.maxValue'.format(source))
    sourceSpans = cmds.getAttr('{}.spans'.format(source))
    sourceDegree = cmds.getAttr('{}.degree'.format(source))
    sourceCVs = cmds.ls('{}.cv[:]'.format(source), fl=True)

    # Destination
    if cmds.objectType(destination) == 'transform':
        try:
            destination = cmds.listRelatives(destination, shapes=True)[0]
        except RuntimeError:
            raise TypeError('Source must be a nurbs curve.')

    destinationMin = cmds.getAttr(
        '{}.minMaxValue.minValue'.format(destination))
    destinationMax = cmds.getAttr(
        '{}.minMaxValue.maxValue'.format(destination))
    destinationSpans = cmds.getAttr('{}.spans'.format(destination))
    destinationDegree = cmds.getAttr('{}.degree'.format(destination))

    # Rebuild
    cmds.rebuildCurve(destination,
                      rebuildType=0,
                      spans=sourceSpans,
                      degree=sourceDegree,
                      ch=False)

    destinationCVs = cmds.ls('{}.cv[:]'.format(destination), fl=True)

    i = 0
    for cv in destinationCVs:
        position = cmds.xform(sourceCVs[i], q=True, ws=True, t=True)
        cmds.xform(cv, ws=True, t=position)
        i += 1

    cmds.rebuildCurve(destination,
                      rebuildType=0,
                      spans=destinationSpans,
                      degree=destinationDegree,
                      ch=False)
    return
def generateSpider(input_namespace, startTime, endTime):
    '''
	this function attaches all curves together, without replacing the orignal curves, using it as a motion path
	for an animated spider. the animated spider is imported, and a simple expression links the U value of the motion
	path to a rotation attribute on the spider rig, controlling its walk cycle. there is also a custom attribute on
	the controller that appears with the spider rig, controlling the length of its steps as it walks.
	'''
    filePath = cmds.internalVar(usd=True) + 'SpiderGen/spider.ma'
    fileExists = cmds.file(filePath, q=True, ex=True)

    if fileExists is True:
        cmds.select(str(input_namespace) + 'curve_spiral*')
        curves = cmds.ls(selection=True)
        path = cmds.attachCurve(curves,
                                n=str(input_namespace) + 'spiderpath',
                                rpo=False)
        cmds.rebuildCurve(path, rt=3)
        cmds.hide(path)
        cmds.file(filePath, i=True)

        cmds.rename('SPIDER_RIG', str(input_namespace) + 'SPIDER_RIG')
        cmds.rename('SCALE_HANDLE',
                    str(input_namespace) + 'CONTROLLER_ScaleMe')
        cmds.rename('CONTROLLER', str(input_namespace) + 'CONTROLLER')

        cmds.select(str(input_namespace) + 'CONTROLLER_ScaleMe', path)
        cmds.pathAnimation(stu=startTime,
                           etu=endTime,
                           f=True,
                           fa='x',
                           ua='y',
                           name=str(input_namespace) + 'motionpath')

        command = str(input_namespace) + 'CONTROLLER.rotateX = ' + str(
            input_namespace) + 'motionpath_uValue.output * ' + str(
                (endTime - startTime) / 10)

        cmds.expression(name=str(input_namespace) + 'leg_movement',
                        alwaysEvaluate=True,
                        s=command)
    else:
        cmds.confirmDialog(
            title='Error',
            message='Spider Model not found, please ensure it located at: ' +
            str(filePath),
            button=['OK'],
            cancelButton='OK')

    return fileExists
Example #39
0
 def rebuild_crv(self):
     if_rebuild = self.if_rebuild_cb.isChecked()
     if if_rebuild:
         spans = self.crv_points_num_sb.value()
         mc.rebuildCurve(self._crv_name,
                         rpo=1,
                         ch=1,
                         end=1,
                         kr=0,
                         kcp=0,
                         kt=0,
                         d=3,
                         tol=0.01,
                         rt=0,
                         s=spans)
Example #40
0
def convertMotionToCurve(target,start=False,end=False,accuracy=100,increment=1):
    if not start:
        start = cmds.playbackOptions(q=1,min=1)
    if not end:
        end = cmds.playbackOptions(q=1,max=1)
    cmds.select(target)
    motionTrail = cmds.snapshot(motionTrail=1,startTime=start,endTime=end,increment=increment,update='animCurve')
    # motionTrail[0] = shape, [1] = xform
    pts = cmds.getAttr(motionTrail[0]+'.pts')
    ptsFix = [f[:-1] for f in pts]
    # make duplicate curve
    newCurve = cmds.curve(d=1,ws=1,p=ptsFix)
    cmds.rebuildCurve(newCurve,rt=0,s=accuracy,kr=0)
    cmds.delete(motionTrail)
    return newCurve
Example #41
0
def rebuildByMinMaxSpans(curves, minSpans, maxSpans):

    import sgBFunction_dag

    sels = sgBFunction_dag.getChildrenShapeExists(curves)

    lengthList = []

    minLength = 10000000.0
    maxLength = 0.0

    targetCurves = []
    for sel in sels:
        selShape = sgBFunction_dag.getShape(sel)
        if not selShape: continue
        if not cmds.nodeType(selShape) == 'nurbsCurve': continue

        fnCurve = om.MFnNurbsCurve(sgBFunction_dag.getMDagPath(selShape))

        curveLength = fnCurve.length()

        if curveLength < minLength:
            minLength = curveLength
        if curveLength > maxLength:
            maxLength = curveLength

        targetCurves.append(sel)
        lengthList.append(fnCurve.length())

    diffSpans = maxSpans - minSpans
    diffLength = maxLength - minLength

    for i in range(len(targetCurves)):
        lengthRate = (lengthList[i] - minLength) / diffLength

        spansRate = lengthRate * diffSpans
        spans = spansRate + minSpans
        cmds.rebuildCurve(targetCurves[i],
                          rpo=1,
                          rt=0,
                          end=1,
                          kr=2,
                          kcp=0,
                          kep=1,
                          kt=1,
                          s=spans,
                          d=3,
                          tol=0.01)
Example #42
0
def trimFromBeginning(inputCurves, shortestLength):
	newCurves = []
	for obj in inputCurves:
		parent = mc.listRelatives(obj, parent=True)
		r = random.random()*(1-shortestLength)
		obj = mc.rebuildCurve(obj,  ch=0, rpo=1, rt=0, end=1, kr=0, kcp=1, kep=1, kt=0, s = 10, d = 3, tol = 0)[0]
		curves = mc.detachCurve( '%s.u[%f]' % (obj, r), ch=0, cos=True, rpo=1 )
		mc.delete(curves[-1])
		mc.rebuildCurve(curves[0], ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=1, kt= 0, s = 0, d = 3, tol = 0)
		curves[0] = mc.rename(curves[0], obj)
		if parent:
			curves[0] = mc.parent(curves[0], parent)[0]
		
		newCurves.append(curves[0])
	
	return newCurves
Example #43
0
def makeHairCurve(hullCurves, u, twist=0.0):
    '''
    Create a curve through a series of hull curves by u parameter
    '''
    p = []
    i = 0
    for hull in hullCurves:
        p.append(mc.pointPosition('%s.u[%f]' % (hull,
                                                (u + (twist * i)) % 1.0)))
        i += 1

    curve = mc.curve(p=p, d=3)
    curve = mc.rebuildCurve(curve,
                            rpo=1,
                            rt=0,
                            end=1,
                            kr=0,
                            kcp=1,
                            kep=1,
                            kt=0,
                            s=4,
                            d=3,
                            tol=0.000129167)

    mc.xform(curve, centerPivots=True)

    return curve
Example #44
0
def build(startPt=[-1,0,0],endPt=[1,0,0],attachments=2,outputMesh=False,radius=0.2,prefix='tendon'):
	'''
	'''
	#
	
	# Get points
	startPt = glTools.utils.base.getMPoint(startPt)
	endPt = glTools.utils.base.getMPoint(endPt)
	
	# Get offset
	offsetVec = endPt - startPt
	offsetInc = 1.0/(attachments-1)
	
	# Get Point List
	ptList = []
	for i in range(attachments-1):
		pt = startPt + (offsetVec * offsetInc)
		ptList.append(pt[0],pt[1],pt[2])
	
	# Build tendon curve base
	tendonCrv = glTools.utils.curve.createFromPointList(ptList,1,prefix)
	# Generate tendon curve locators
	tendonLocList = glTools.utils.curve.locatorCurve(tendonCrv,freeze=False,prefix=prefix)
	# Rebuild tendon curve
	if attachments > 2:
		tendonRebuild = mc.rebuildCurve(tendonCrv,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=0,d=3,tol=0.01)
Example #45
0
def edgeLoopCrv(meshEdgeList,rebuild=False,rebuildSpans=0,form=2,keepHistory=True,prefix=''):
	'''
	Generate a curve from a mesh edge loop.
	@param meshEdgeList: List of mesh edges to generate curve from
	@type meshEdgeList: list
	@param rebuild: Rebuild curve to degree 3
	@type rebuild: bool
	@param rebuildSpans: Number of spans to rebuild the resulting curve to
	@type rebuildSpans: int
	@param form: Form of the resulting curve. 0 = Open, 1 = Periodic, 2 = Best Guess.
	@type form: str
	@param keepHistory: Maintain construction history
	@type keepHistory: bool
	@param prefix: Name prefix for newly created nodes
	@type prefix: str
	'''
	# Check edge list
	if not meshEdgeList:
		raise Exception('Invalid mesh edge list provided!!')
	meshEdgeList = mc.ls(meshEdgeList,fl=True)
	# Check prefix
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(meshEdgeList[0].split('.')[0])
	# Convert edge selection to nurbs curve
	crvDegree = 1
	if rebuild: crvDegree = 3
	curve = mc.polyToCurve(ch=keepHistory,form=form,degree=crvDegree)[0]
	# Rebuild as degree 3
	if rebuild and rebuildSpans:
		curve = mc.rebuildCurve(curve,ch=keepHistory,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=1,kt=1,s=rebuildSpans,d=3,tol=0.01)[0]
	# Rename curve
	curve = mc.rename(curve,prefix+'_curve')
	
	# Return result
	return curve
Example #46
0
def rebuildCurveWithHistory(crv,
                            degree=None,
                            spans=None,
                            range=0,
                            keepCVs=False,
                            keepEnds=False,
                            fitRebuild=True):
    """
    @param crv: Curve to rebuild
    @type crv: str
    @param degree: Rebuild degree. If None, keep original.
    @type degree: str
    @param spans: Number of rebuild spans. If None, keep original.
    @type spans: str
    @param range: Parameterization for the curve. 0 = 0-1, 1 = original, 2 = 0-Nspans
    @type range: int
    @param keepCVs: Keep all original CVs.
    @type keepCVs: bool
    @param keepEnds: Keep end points.
    @type keepEnds: bool
    @param fitRebuild: Fit rebuild
    @type fitRebuild: bool
    """
    # Check Curve
    if not isCurve(crv): raise Exception('Object "' + crv + '" is not a valid curve!')

    # Get Shape
    crvShape = cmds.ls(cmds.listRelatives(crv, s=True, ni=True) or [], type='nurbsCurve') or []
    if not crvShape: raise Exception('Unable to determine curve shape for "' + crv + '"!')
    crvShape = crvShape[0]

    # Check Inputs
    if spans == 0: spans = 0
    if degree == None: degree = cmds.getAttr(crvShape + '.degree')

    # Get Input Shape
    try:
        glTools.utils.shape.findInputShape(crvShape)
    except:
        glTools.utils.shape.createIntermediate(crvShape)

    # Rebuild Curve
    rebuildCrv = cmds.rebuildCurve(crvShape,
                                 ch=True,
                                 rpo=True,
                                 rebuildType=0,  # Uniform
                                 endKnots=1,  # Multiple
                                 keepRange=range,
                                 keepControlPoints=keepCVs,
                                 keepEndPoints=keepEnds,
                                 keepTangents=False,
                                 spans=spans,
                                 degree=degree)

    # Rename Node
    rebuildCrv = cmds.rename(rebuildCrv, crv.replace('_crv', '') + '_rebuildCurve')

    # Return Result
    return rebuildCrv[1]
Example #47
0
def initializeRibbonSpine(startJoint,endJoint,numJoints,spans,prefix='cn_spine'):
	'''
	'''
	# ==========
	# - Checks -
	# ==========
	
	if not mc.objExists(startJoint):
		raise Exception('Start joint "'+startJoint+'" does not exist!')
	if not mc.objExists(endJoint):
		raise Exception('End joint "'+endJoint+'" does not exist!')
	
	# =====================
	# - Build Spine Curve -
	# =====================
	
	# Get Spine Joint List
	spineJnts = glTools.utils.joint.getJointList(startJoint,endJoint)
	
	# Build Spine Locators
	locList = []
	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]
		mc.move(pt[0],pt[1],pt[2],loc,ws=True,a=True)
		mc.parent(loc,spineJnts[i])
		locList.append(loc)
	
	# Build Spine Curve
	spineCurve = glTools.utils.curve.createFromLocators(locList,degree=1,attach=True,prefix=prefix)
	spineCurveShape = mc.listRelatives(spineCurve,s=True,pa=True)[0]
	glTools.utils.shape.createIntermediate(spineCurveShape)
	
	# Rebuild Spine Curve
	if not spans: spans = len(spineJnts) - 1
	rebuildCrv = mc.rebuildCurve(spineCurve,ch=1,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=1,s=spans,d=3,tol=0)
	rebuildCrv = mc.rename(rebuildCrv[1],prefix+'A_rebuildCurve')
	
	# ================================
	# - Attach Joints to Spine Curve -
	# ================================
	
	ribbonJoints = []
	inc = 1.0 / (numJoints - 1)
	for i in range(numJoints):
		mc.select(cl=1)
		strInd = glTools.utils.stringUtils.alphaIndex(i)
		joint = mc.joint(n=prefix+'Ribbon'+strInd+'_jnt')
		glTools.utils.attach.attachToCurve(spineCurve,joint,uValue=inc*i,orient=False,prefix=prefix+'Ribbon'+strInd)
		ribbonJoints.append(joint)
	
	# =================
	# - Return Result -
	# =================
	
	return ribbonJoints
def snap_root_CV_to_mesh(*args):
    '''
    Snap root CV of curve to closest point on mesh for selected mesh
    and curves which are currently selected.
    '''
    initialSelection = cmds.ls(sl=True)
    scalpMesh = cmds.ls(sl=True, dag=True, type='mesh')[0]
    curveSet = cmds.listRelatives(cmds.ls(sl=True, dag=True, type='nurbsCurve'), parent=True)

    CPOM_A = cmds.createNode('closestPointOnMesh')
    CPOM_B = cmds.createNode('closestPointOnMesh')
    cmds.connectAttr(scalpMesh+'.outMesh', CPOM_A+'.inMesh')
    cmds.connectAttr(scalpMesh+'.outMesh', CPOM_B+'.inMesh')

    for CRV in curveSet:
        #CRV = curveSet[0]
        curveLen = int(cmds.arclen(CRV)/3+4)
        rebuildCRV = cmds.rebuildCurve(CRV, d=3, spans=curveLen)
        
        #print CRV
        CRVroot = cmds.pointPosition(CRV+'.cv[0]', world=True)
        CRVvec = cmds.pointPosition(CRV+'.cv[2]', world=True)
        
        abc = ['X', 'Y', 'Z']
        for x in abc:
            cmds.setAttr(CPOM_A+'.inPosition'+x, CRVroot[abc.index(x)])
            cmds.setAttr(CPOM_B+'.inPosition'+x, CRVvec[abc.index(x)])

        CPOM_rootPOS = cmds.getAttr(CPOM_A+'.position')[0]
        CPOM_vecPOS = cmds.getAttr(CPOM_B+'.position')[0]
        #print CRV, CRVroot, CPOM_POS
        
        
        cmds.reverseCurve(CRV)
        CRVcvs = cmds.getAttr(CRV+'.spans')
        #print CRV, curveLen, CRVcvs, rebuildCRV
        cmds.delete(CRV, constructionHistory=True)
        CRVshape = cmds.listRelatives(CRV, children=True)
        cmds.curve(CRVshape, a=True, ws=True, p=[CPOM_vecPOS, CPOM_rootPOS])#[(0,0,0) for x in range(CRVcvs/5)])
        cmds.reverseCurve(CRV)
        cmds.rebuildCurve(CRV, degree=3, spans=CRVcvs+2)
        cmds.smoothCurve(CRV+'.cv[*]', smoothness=10)
    #break

    cmds.select(initialSelection)
Example #49
0
def point2Curve(spans) : 
	sels = mc.ls(sl = True)

	if len(sels) == 2 : 
		point1 = sels[0]
		point2 = sels[1]

		pos1 = mc.xform(point1, q = True, ws = True, t = True)
		pos2 = mc.xform(point2, q = True, ws = True, t = True)

		result = mc.curve(d = 1, p=[pos1, pos2], k=[0,1] )

		mc.rebuildCurve(result, rpo = 1, rt = 0, end = 1, kr = 0, kcp = 0, kep = 1, kt = 0, s = spans, d = 3, tol = 0.0001)

		mc.select(result)
		mm.eval('CenterPivot')

		return result
Example #50
0
def makeCurveFromPoints(p, close=True):
	curve = mc.curve(p=p, d=3)
	if close:
		curve = mc.closeCurve(curve, ps=0, rpo=1, bb=0.5, bki=0, p=0.1)
	curve = mc.rebuildCurve(curve, rpo=1, rt=0, end=1, kr=0, kcp=1, kep=1, kt=0, s=4, d=3, tol=0.000129167)
	
	mc.xform(curve, centerPivots=True)
	
	return curve
Example #51
0
def rebuildByLength( rate ):
    
    sels = cmds.ls( sl=1 )
    
    info = cmds.createNode( 'curveInfo' )
    for sel in sels:
        if cmds.nodeType( sel ) == 'transform':
            sel = cmds.listRelatives( sel, s=1 )[0]
        
        
        if not cmds.isConnected( sel+'.local', info+'.inputCurve' ):
            cmds.connectAttr( sel+'.local', info+'.inputCurve', f=1 )
        length = cmds.getAttr( info+'.arcLength' )
        cmds.rebuildCurve( sel, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=0, kt=0, s=length*rate, tol=0.01 )
    
    cmds.delete( info )
    
    cmds.select( sels )
Example #52
0
	def rebuild(self, basePointsCout = 5, keep = False):
		"""custom rebuild curve, creating an intermidate curve for the process"""
		pnts = []
		for p in range( basePointsCout ):
			param = float( p ) / float( basePointsCout - 1 )
			pnts.append( self.pointAtParam( param ) )
		cur = mc.curve( ep = pnts, d = 3 )
		finalcur = mc.rebuildCurve( cur, ch = 1, rpo = not (keep), rt = 0, end = 1, kr = 0, kcp = 0, kep = 0, kt = 0, s = 2, d = 3, tol = 0.01 )[0]
		return Curve( finalcur )
Example #53
0
def addJntsOnSurfIntersection(surf1, surf2, jntsNum):
    '''
    Places jnts along intersection curve between surf1 and surf2
    naming convention based on surf1
    '''
    
    # intersect surfaces
    crvGrp, intNode = mc.intersect(surf1, surf2, fs=True, ch=True, o=True, cos=False)[:2]
    intNode = mc.rename(intNode, surf1+'_ints')
    crvGrp = mc.rename(crvGrp, surf1+'_ints_crv_grp')
    crv = mc.listRelatives(crvGrp, c=True)[0]
    crv = mc.rename(crv, surf1+'_ints_crv')
    
    # rebuild curve to jntNum spans
    rbdCrv, rbdNode = mc.rebuildCurve(crv, ch=True, o=True, rpo=False, spans=jntsNum, rt=0, kr=2, n=crv+'_rbd_crv')
    rbdNode = mc.rename(rbdNode, crv+'_rbd')
    
    # offset curve to control size of eye hole
    offsetCrv, offsetNode = mc.offsetCurve(rbdCrv, ch=True, distance=0, o=True, ugn=0, n=crv+'_offset_crv')
    offsetNode = mc.rename(offsetNode, crv+'_offset')
    
    locs = []
    locName = '_'.join(surf1.split('_')[:2])
    # attach locators to intersection curve
    for locId in range(jntsNum):
        loc = mc.spaceLocator(n=locName+'_loc_%d' % locId)[0]
        rt.attachToMotionPath(offsetCrv, locId, loc, fm=False)
        mc.setAttr(loc+'.localScale', 0.05, 0.05, 0.05)
        locs.append(loc)
        
    # normal constraint to surf1
    for loc in locs:
        mc.normalConstraint(surf2, loc, aim=(1,0,0))
    
    jnts = []
    # add joints under locators
    for loc in locs:
        mc.select(cl=True)
        jnt = mc.joint(n=loc.replace('_loc_','_jnt_'))
        rt.parentSnap(jnt, loc)
        mc.setAttr(jnt+'.jointOrient', 0,0,0)
        jnts.append(jnt)
        
    # groups
    grp = mc.group(crvGrp, offsetCrv, rbdCrv, locs, n=surf1+'_intersect_loc_grp')
    
    # create offset attribute
    mc.addAttr(grp, ln='collideOffset', at='double', dv=0, k=True)
    offsetPlug = cn.create_multDoubleLinear(grp+'.collideOffset', -1)
    mc.connectAttr(offsetPlug, offsetNode+'.distance', f=True)
    
    # connect debug
    rt.connectVisibilityToggle(offsetCrv, grp, 'offsetCrv', False)
    rt.connectVisibilityToggle(rbdCrv, grp, 'rebuildCrv', False)
    rt.connectVisibilityToggle(crvGrp, grp, 'intersectCrv', False)
    rt.connectVisibilityToggle(locs, grp, 'crvLocs', False)
    rt.connectVisibilityToggle(jnts, grp, 'crvJnts', False)
Example #54
0
def addHairDeformToBag( bag, controller ):
    
    startVtxIndex = 40
    endVtxIndex   = 105
    
    pBag = cmds.listRelatives( bag, p=1,f=1 )[0]
    
    cons = cmds.listConnections( pBag, type='multMatrixDecompose',s=1, d=0 )
    
    if not cons: return None
    
    mmdc = cons[0]
    cons = cmds.listConnections( mmdc+'.i[0]', s=1, d=0 )
    
    if not cons: return None
    
    constObj = cons[0]
    
    constObj
    cmds.select( constObj )
    jnt = cmds.joint()
    
    startPos = cmds.xform( bag+'.vtx[%d]' % startVtxIndex, q=1, ws=1, t=1 )
    endPos   = cmds.xform( bag+'.vtx[%d]' % endVtxIndex, q=1, ws=1, t=1 )
    
    crv = cmds.curve( p=[startPos, endPos], d=1 )
    cmds.rebuildCurve( crv, ch=0, d=3, s=7 )
    
    cmds.skinCluster( [crv, jnt] )
    
    import sgRigCurve
    hairSystem = sgRigCurve.makeDynamicCurveKeepSrc( [crv], 'dynamic_' )
    
    sgRigAttribute.connectHairAttribute( controller, hairSystem )
    
    cmds.select( crv )
    handle, jnts = sgRigCurve.createJointOnEachCurve( crv, 7, False )
    
    topJnt = jnts[0]
    cmds.parent( handle, topJnt, constObj )
    
    jnts.append( bag )
    cmds.parent( bag, w=1 )
    cmds.skinCluster( jnts )
Example #55
0
def addWobbleDeform( mainCtl, targets ):
  
    import math
    if not type( targets ) in [ type(()), type([]) ]:
        targets = [targets]

    failedTargets = []
    for target in targets:
        vtxList = cmds.ls( target+'.vtx[*]', fl=1 )
        topVtxPos = [0,0,0]
        bottomVtxPos = [0,10000,0]
        for vtx in vtxList:
            pos = cmds.xform( vtx, q=1, ws=1, t=1 )
            if math.fabs( pos[1] ) > math.fabs( topVtxPos[1] ):
                topVtxPos = pos
            if math.fabs( pos[1] ) < math.fabs( bottomVtxPos[1] ):
                bottomVtxPos = pos
        
        if( (topVtxPos[0]-bottomVtxPos[0])**2 + (topVtxPos[1]-bottomVtxPos[1])**2 + (topVtxPos[2]-bottomVtxPos[2])**2 ) < 0.001:
            failedTargets.append( target )
            continue 
        crv = cmds.curve( p=[bottomVtxPos,topVtxPos], d=1 )
        cmds.rebuildCurve( crv, ch=0, d=3, s=10 )
        
        sgRigCurve.createSgWobbleCurve( crv, False )
        
        copyAttrs = [ 'globalEnvelope', 'globalTimeMult', 'globalOffset' ]
        
        for copyAttr in copyAttrs:
            sgRigAttribute.copyAttribute( crv+'.'+copyAttr, mainCtl )
            cmds.connectAttr( mainCtl+'.'+copyAttr, crv+'.'+copyAttr )

        wire = cmds.deformer( target, type='wire' )[0]
        crvOrig = sgModelDag.getOrigShape( crv )
        crvShape= sgModelDag.getShape( crv )

        cmds.connectAttr( crvOrig+'.local', wire+'.baseWire[0]' )
        cmds.connectAttr( crvShape+'.local', wire+'.deformedWire[0]' )

        cmds.setAttr( wire+'.rotation', 0.2 )
        cmds.setAttr( wire+'.dropoffDistance[0]', 10 )
    
    return failedTargets
Example #56
0
    def createSpiralCurve(self, baseCurve, numRounds, radius, profileScale):

        surfaceCV = float(numRounds+2)*(float(numRounds+2)/2.0)
        
        # duplicate curve and get the maxValue
        cmds.select(baseCurve, r=True)
        curveMaxValue = cmds.getAttr(baseCurve+".maxValue")
        cmds.rebuildCurve(ch=0, rpo=1, rt=0, end=1, kr=2, kcp=0, kep=1, kt=0, s=0, d=3)
        # create a circle profile
        profile = cmds.circle(nr=[0, 1, 0], c=[0, 0, 0], r=radius)
        # put it at the start of the baseCurve
        cmds.pathAnimation(profile, fm=True, f=True, fa="y", ua="x", wut=4, wu=[0, 1, 0], c=baseCurve)
        # extrude the profile
        extrudesurface = cmds.extrude(profile[0], baseCurve, et=2, sc=profileScale)
        # curve on surface
        curveonsurface = cmds.curveOnSurface(extrudesurface, append=False, uv=(0, 0))
        
        y = 0.0
        for i in range(int(surfaceCV)):
            y += curveMaxValue/surfaceCV
            x = math.fmod(y*2*surfaceCV/curveMaxValue, 8)
            #print x, y
            cmds.curveOnSurface(curveonsurface, append=True, uv=(x, y))
            
        # duplicate the created curve
        cmds.duplicateCurve(ch = False)
        cmds.rename("duplicated_"+baseCurve)
        spiralCurve = cmds.ls(sl = True)
        cmds.rebuildCurve(ch=0, rpo=1, rt=0, end=1, kr=2, kcp=0, kep=1, kt=0, s=0, d=3)
        # create wire
        #cmds.wire(spiralCurve, dds = [(0, 100)], gw = True, en = 1.0, ce = 0.0, li = 0.0, w = baseCurve)
        #cmds.pickWalk(d = "up")
        cmds.select(spiralCurve, r = True)
        arcCurveGroup = cmds.group(n = "spiralCurveWire"+baseCurve+"___GRP")
        
        #delete unused nodes
        cmds.delete(profile)
        cmds.delete(extrudesurface[0])    
        
        #print "spiral curve created."
    
        return spiralCurve, arcCurveGroup
Example #57
0
def makeCurveAsBindedCurve( crv, rebuildRate = 1 ):
    
    crvShape = getShape( crv )
    crvShapePath = getDagPath( crvShape )
    fnNurbsCurve = om.MFnNurbsCurve( crvShapePath )
    spans = fnNurbsCurve.numSpans()
    rebuildSpans = spans * rebuildRate
    
    cmds.rebuildCurve( crvShape, constructionHistory=0, 
                           replaceOriginal=1,
                           rebuildType=0, 
                           endKnots=1, 
                           keepRange=0, 
                           keepControlPoints=0, 
                           keepEndPoints=1, 
                           keepTangents=0,
                           s=rebuildSpans, d=3, tol=0.01 )
    
    exclusiveMtx = crvShapePath.exclusiveMatrix()
    
    localPoints = om.MPointArray()
    fnNurbsCurve.getCVs( localPoints )
    mtxList = []
    for i in range( 4 ):
        for j in range( 4 ):
            mtxList.append( exclusiveMtx( i, j ) )
    
    grp = cmds.createNode( 'transform' )
    for i in range( localPoints.length() ):
        jnt = cmds.joint()
        cmds.move( localPoints[i].x, localPoints[i].y, localPoints[i].z, jnt, ws=1 )
        multMtx = cmds.createNode( 'multMatrix' )
        dcmp    = cmds.createNode( 'decomposeMatrix' )
        cmds.connectAttr( jnt+'.wm', multMtx+'.i[0]' )
        cmds.connectAttr( grp+'.wim', multMtx+'.i[1]' )
        cmds.connectAttr( multMtx+'.o', dcmp+'.imat' )
        cmds.connectAttr( dcmp+'.ot', crvShape+'.controlPoints[%d]' % i )
        cmds.select( jnt )
    
    cmds.xform( grp, ws=1, matrix=mtxList )
Example #58
0
def createGuideCurves( orderedVertices, centerVertPos, hrsSys, dynamic = True ):
	crvs = []
	fols = []
	locs = []
	centerLoc = mn.Node( mc.spaceLocator(  )[0] )
	centerLoc.a.t.v = centerVertPos
	locs.append( centerLoc )
	for i,v in enumerate( orderedVertices ):
		vPos = mc.xform( v, q = True, ws = True, t = True )
		if dynamic:
			loc = mn.Node( mc.spaceLocator( )[0] )
			loc.a.t.v = vPos
			curv, folPar = createCurveaBasedOnLocator( centerLoc, loc, 'guide', hrsSys )
			fols.append( folPar )
			locs.append( loc )
		else:
			curv = crv.Curve( mc.curve( d = 3, ep = [centerVertPos, vPos] ) )
			mc.rebuildCurve( curv.name, rpo = 1, rt = 0, end = 1, kr = 2, kcp = 0, kep = 1, kt =0, s= 3, d = 3, tol = 0.01  )
			curv.name = 'spiderWeb_guide_' + str( i ) + '_CRV'
		curv.shape.a.aiRenderCurve.v = 1
		crvs.append( curv )
	return crvs, fols, locs
Example #59
0
def rebuildByMinMaxSpans( curves, minSpans, maxSpans ):
    
    import sgBFunction_dag
    
    sels = sgBFunction_dag.getChildrenShapeExists( curves )
    
    lengthList = []
    
    minLength = 10000000.0
    maxLength = 0.0
    
    targetCurves = []
    for sel in sels:
        selShape = sgBFunction_dag.getShape( sel )
        if not selShape: continue
        if not cmds.nodeType( selShape ) == 'nurbsCurve': continue
        
        fnCurve = om.MFnNurbsCurve( sgBFunction_dag.getMDagPath( selShape ) )
        
        curveLength = fnCurve.length()
        
        if curveLength < minLength:
            minLength = curveLength
        if curveLength > maxLength:
            maxLength = curveLength
        
        targetCurves.append( sel )
        lengthList.append( fnCurve.length() )
    
    
    diffSpans = maxSpans - minSpans
    diffLength = maxLength - minLength
    
    for i in range( len( targetCurves ) ):
        lengthRate = ( lengthList[i] - minLength ) / diffLength
        
        spansRate = lengthRate * diffSpans
        spans = spansRate + minSpans
        cmds.rebuildCurve( targetCurves[i], rpo=1, rt=0, end=1, kr=2, kcp=0, kep=1, kt=1, s=spans, d=3, tol=0.01 )
Example #60
0
 def _create_curve(self, joint_chain):
     """
     Responsible for creating the dynamic curve for the IK Spline solver.
     """
     # create our curve
     curve_name = self._get_unique_name("dynamicCurve", "DyCrv")
     self.joint_positions = list()
     for joint in joint_chain:
         joint_pos = cmds.xform(joint, q=True, ws=True, t=True)
         self.joint_positions.append(joint_pos)
     tmp_curve = cmds.curve(d=3, ep=self.joint_positions)
     tmp_curve = cmds.rename(tmp_curve, curve_name)
     self.curve = cmds.rebuildCurve(tmp_curve, s=len(joint_chain)*3,
                                    ch=False)