Ejemplo n.º 1
0
 def createCrv(self,*a):
  cmds.radioCollection('rc_ancUv',q=1,select=1)
  cmds.radioCollection('rc_ancCct',q=1,select=1)
  cmds.radioCollection('rc_ancNct',q=1,select=1)
  sl = cmds.ls(selection=1,long=1)
  sls = cmds.ls(selection=1)
  selList = []
  for i,x in enumerate(sl):
   sn = sls[i]
   if cmds.nodeType(x) == 'transform':
    ns = cmds.listRelatives(x,type='nurbsSurface')
    if ns : x= ns[0]
   if cmds.nodeType(x) == 'nurbsSurface':
    svAttr = '.spansV' ; vAttr = '.v' ; maxAttr = '.minMaxRangeV'
    if cmds.radioCollection('rc_ancUv',q=1,select=1) == 'rb_ancU' : svAttr = '.spansU' ; vAttr = '.u' ; maxAttr = '.minMaxRangeU'
    v = cmds.getAttr(x+svAttr)
    crvList = []
    for j in range(v):
     vv = float(j)
     if cmds.getAttr(x+maxAttr)[0][1] == 1.0 : vv = 1.0 / v * j
     dc = cmds.duplicateCurve(x+vAttr+'['+str(vv)+']',constructionHistory=0,object=1)[0]
     crvList.append(dc)
    cCrv = cmds.duplicateCurve(x+vAttr+'[0]',constructionHistory=0,object=1,name='crv_'+sls[i])[0]
    bs = cmds.blendShape(crvList,cCrv)[0]
    cmds.delete(crvList)
    for j in range(v): cmds.setAttr(bs+'.'+crvList[j],1.0/v)
    cmds.delete(cCrv,constructionHistory=1)
    selList.append(cCrv)
    if cmds.radioCollection('rc_ancNct',q=1,select=1) == 'rb_ancWire' :
     cmds.wire(x,w=cCrv,dropoffDistance=[0,100])
  if len(selList) > 0 : cmds.select(selList,replace=1)
  else : sys.stderr.write('No NURBS surface select.')
Ejemplo n.º 2
0
def curvesFromSurface(surface, UorV="v", crvAmount=10, name=""):
    """ This funciton extracts curves from a NURBS Surface """

    # Get max U V valeus
    maxValueU = cmds.getAttr(surface + ".maxValueU")
    maxValueV = cmds.getAttr(surface + ".maxValueV")

    # Calculate space between each curve
    uStep = maxValueU / (crvAmount - 1)
    vStep = maxValueV / (crvAmount - 1)

    # Select U or V valeu based on user input
    step = uStep if UorV == "u" else vStep
    crv_list = []

    for n in range(crvAmount):
        # Calculate current crv position
        crv_parameter = n * step
        crv = cmds.duplicateCurve("{}.{}[{}]".format(surface, UorV,
                                                     crv_parameter),
                                  local=True,
                                  ch=0,
                                  n="{}_{:02d}_Crv".format(name, n))
        # Unparent from surface
        cmds.parent(crv, w=1)
        # Add curve list
        crv_list.append(crv[0])

    return crv_list
Ejemplo n.º 3
0
def isoparmCoord(surfaceSkin,influence,controlPoints,coord,direction='u'):
	'''
	Set the target coordinates for the specified control points to lie along a given isoparm
	@param surfaceSkin: surfaceSkin node to apply the coordinates to
	@type surfaceSkin: str
	@param influence: surfaceSkin influence to get coordinate for
	@type influence: str
	@param controlPoints: List of control points to set the target coordinates for
	@type controlPoints: list
	@param coord: Coordinate value of the target isoparm
	@type coord: float
	@param direction: Direction of the isoparm
	@type direction: str
	'''
	# Get surface curve
	crv = mc.duplicateCurve(influence+'.'+direction+'['+str(coord)+']',ch=False,rn=0,local=0,n=influence+'TEMP_CRV')[0]
	
	# Iterate through control point list
	for controlPoint in controlPoints:
		# Get component position
		pos = mc.pointPosition(controlPoint)
		# Get closest point on curve
		cCoord = glTools.utils.curve.closestPoint(crv,pos)
		# Apply Coord
		uvCoord = (0,0)
		if direction == 'u': uvCoord = (coord,cCoord)
		else: uvCoord = (cCoord,coord)
		applyCoord(surfaceSkin,influence,controlPoint,uvCoord)
	
	# Delete surface curve
	mc.delete(crv)
Ejemplo n.º 4
0
def curves_from_surface(surface, u_or_v="v", crv_amount=10, name=""):
    """
    This function extracts curves from a NURBS Surface
    :param surface:
    :param u_or_v:
    :param crv_amount:
    :param name:
    :return: curve list
    """

    # cet max U V values
    max_value_u = cmds.getAttr(surface + ".maxValueU")
    max_value_v = cmds.getAttr(surface + ".maxValueV")

    # calculate space between each curve
    u_step = max_value_u / (crv_amount - 1)
    v_step = max_value_v / (crv_amount - 1)

    # Select U or V value based on user input
    step = u_step if u_or_v == "u" else v_step
    crv_list = []

    for n in range(crv_amount):
        # calculate current crv position
        crv_parameter = n * step
        crv = cmds.duplicateCurve("{}.{}[{}]".format(surface, u_or_v, crv_parameter),
                                  local=True, ch=0, n="{}_{:02d}_Crv".format(name, n))
        # un-parent from surface
        cmds.parent(crv, w=1)
        # Add curve list
        crv_list.append(crv[0])

    return crv_list
Ejemplo n.º 5
0
def chordLength(surface, param=0.0, direction='u'):
    """
    Return the length of a surface isoparm given a parameter and a direction
    @param surface: Surface to query closest point from
    @type surface: str
    @param param: The parameter on the surface to query length of
    @type param: float
    @param direction: Direction along the surface to measure length of
    @type direction: str
    """
    # Check surface
    if not isSurface(surface):
        raise Exception('Object ' + surface + ' is not a valid surface!')
    # Duplicate surface curve
    curve = cmds.duplicateCurve(surface + '.' + direction + '[' + str(param) +
                                ']',
                                ch=0,
                                rn=0,
                                local=0)
    # Measure curve length
    length = cmds.arclen(curve[0])
    # Cleanup
    cmds.delete(curve)
    # Return result
    return length
Ejemplo n.º 6
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
Ejemplo n.º 7
0
 def getCurve(uValue, l_newCurves):
     _crv = d_curves.get(uValue)
     if _crv: return _crv
     _crv = mc.duplicateCurve("{0}.u[{1}]".format(_shape, uValue),
                              ch=0,
                              rn=0,
                              local=0)[0]
     if offset:
         DIST.offsetShape_byVector(_crv, offset, component='cv')
     d_curves[uValue] = _crv
     log.debug("|{0}| >> created: {1} ...".format(_str_func, _crv))
     l_newCurves.append(_crv)
     return _crv
Ejemplo n.º 8
0
    def mk_len_crv(self):
        """
        Create a curve skinned along with ribbon that provides you with
        your ribbon's length data for volume preservation
        """
        crv = mc.duplicateCurve("{}.v[0.5]".format(
            self.ribbon), ch=False, rn=False, l=False, n=self.ribbon.replace("ribbon", "crv"))[0]
        mc.setAttr("{}.visibility".format(crv), 0)
        mc.parent(crv, "{}{}".format(self.ribbon, GRP))

        # Add curve to lenCurves cless variable
        self.lenCurves.append(crv)

        return crv
Ejemplo n.º 9
0
def get_shapeCurve(shape, value, mode='u', offset=None, d_curves={}):
    _str_func = 'get_shapeCurve'

    _crv = d_curves.get(value)
    if _crv: return _crv
    _crv = mc.duplicateCurve("{0}.{1}[{2}]".format(shape, mode, value),
                             ch=0,
                             rn=0,
                             local=0)[0]
    if offset:
        DIST.offsetShape_byVector(_crv, offset, component='cv')
    if d_curves:
        d_curves[value] = _crv
    log.debug("|{0}| >> created: {1} ...".format(_str_func, _crv))
    return _crv
Ejemplo n.º 10
0
def	createSpherical4Arrowhead	():
	_controlled		=	cmds.ls		(	long	=	True,	selection	=	True	)
	_baseCurve		=	cmds.curve	( 	degree	=	1,	point	=	[	(0,1,1),(0,3,1),(0,3,2),(0,6,0),(0,3,-2),(0,3,-1),
										(0,1,-1),(0,1,-3),(0,2,-3),(0,0,-6),(0,-2,-3),(0,-1,-3),(0,-1,-1),(0,-3,-1),
										(0,-3,-2),(0,-6,0),(0,-3,2),(0,-3,1),(0,-1,1),(0,-1,3),(0,-2,3),(0,0,6),(0,2,3),
										(0,1,3),(0,1,1)	]	)
	_tempSphere		=	cmds.sphere	(	radius	=	7,	axis	=	(	0,	1,	0	),	sections	=	4,
										startSweep	=	270,	endSweep	=	90,	constructionHistory	=	0	)
	_control 		=	cmds.projectCurve	(	_baseCurve,	_tempSphere,
												constructionHistory	=	False,	direction	=	(	1,	0,	0	),	)
	_control		=	cmds.duplicateCurve	(	_control,	constructionHistory	=	True,	object	=	True	)
		
	cmds.delete		(	_tempSphere	)
	cmds.delete		(	_baseCurve	)
	
	postProcessControl	(	_control[0],	'rotate',	_controlled	)
Ejemplo n.º 11
0
 def runEmitCurve(self,state):
     '''
     Executes the code to emit particles from a curve using the variables defined in snowflakeUI.curveEmitUI and starts the progress window
     Will create an error popup if the variable values would stop the code from functioning correctly
     '''
     if cmds.intField(self.endFrame,v=1,q=1)<=cmds.intField(self.startFrame,v=1,q=1):
         errorPopup('End Frame must be after Start Frame')
         return
     if cmds.intField(self.lifeTime,v=1,q=1)<=0:
         errorPopup('Particles have to have a lifetime')
         return
     if cmds.intField(self.fadeOut,v=1,q=1)>cmds.intField(self.lifeTime,v=1,q=1):
         errorPopup('Lifetime must be larger than fadeout time')
         return
     try:
         tmp = cmds.duplicateCurve(cmds.textField(self.sourceCurve,tx=1,q=1))[0]
         cmds.delete(tmp)
     except:
         errorPopup('Choose a source curve')
         return
     particleFX.reloadFile()
     cmds.progressWindow(title='SnowFX',
                                   progress=0,
                                   status='Starting up...')
     try:
         particles=self.makeAllParticles()
         particleFX.emitCurve(cmds.textField(self.sourceCurve,tx=1,q=1),
                                        cmds.intField(self.startFrame,v=1,q=1),
                                        cmds.intField(self.endFrame,v=1,q=1)-cmds.intField(self.startFrame,v=1,q=1),
                                        particles,
                                        cmds.floatField(self.maxDistance,v=1,q=1),
                                        cmds.floatField(self.minDistance,v=1,q=1),
                                        cmds.intField(self.emitTime,v=1,q=1),
                                        cmds.intField(self.lifeTime,v=1,q=1),
                                        cmds.intField(self.lifeTimeVar,v=1,q=1),
                                        cmds.intField(self.fadeOut,v=1,q=1),
                                        cmds.floatField(self.turbulenceAmp,v=1,q=1),
                                        cmds.intField(self.turbulencePer,v=1,q=1),
                                        (cmds.floatField(self.driftX,v=1,q=1),cmds.floatField(self.driftY,v=1,q=1),cmds.floatField(self.driftZ,v=1,q=1)))
         group = cmds.group(em=1,n='snowFX')
         for x in particles:
             cmds.parent(x.name,group)
         cmds.progressWindow(ep=1)
     except Exception, err:
         sys.stderr.write('ERROR: %s\n' % str(err))
         cmds.progressWindow(ep=1)
         errorPopup('Something went wrong :( \n Check the script editor for detials')
Ejemplo n.º 12
0
def buildEdgeCurve():
	global sortedList
	global newEdgeCurve
	global spacerNode
	#Create a curve that fits the selected edges
	crvGarbageCollect = []
	for edgCrv in sortedList:
		curveAttach = mc.duplicateCurve(edgCrv, ch=True, rn=0, local=0, n=("edgeCurve"))
		crvGarbageCollect.append(curveAttach[0])
	newEdgeCurve = mc.attachCurve(crvGarbageCollect, ch=False, rpo=False, kmk = 1, m = 0, n= 'bigEdgeCurve', bb = 0.5, bki = 0, p=0.1)
	mc.rebuildCurve(newEdgeCurve, ch=False, rpo=True, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=400, d=1, tol=0.01)
	#Rebuild is mandatory otherwise the EP joints are too unevenly spaced, this helps to correct the problem. Uneven EP's result in poor placement of the locators for snapping.
	mc.delete(crvGarbageCollect) # A bit of tidyness
	bigCrvShp =  mc.ls(newEdgeCurve, s=True, dag=True)
	spacerNode = mc.shadingNode('pointOnCurveInfo',au=True,  n='spacerCurveInfo')
	mc.setAttr(spacerNode + '.turnOnPercentage', 1)
	mc.connectAttr(bigCrvShp[0] + '.worldSpace[0]', spacerNode + '.inputCurve')
Ejemplo n.º 13
0
def surfaceToHairGroup(curve_num = 4):
    select_surfaces = mc.ls(sl = True)
    for mesh in select_surfaces:
        v_range = mc.getAttr('%s.mmv' % mesh)[0]
        v_step = v_range[1] / (curve_num - 1)
        # create curves
        curves = []
        for i in range(curve_num):
            d_curve = mc.duplicateCurve('%s.v[%f]' % (mesh, (i * v_step)), ch = True, rn = False, local = False)[0]
            curves.append(d_curve)

        # create polygon
        p = []
        for curve in curves:
            p.append(mc.xform('%s.cv[0]' % curve, q = True, t = True))

        mc.polyCreateFacet(p = p)
Ejemplo n.º 14
0
 def runCurveFollow(self,state):
     '''
     Executes the code to animate particles following a curve using the variables defined in snowflakeUI.curveFollowUI and starts the progress window
     Will create an error popup if the variable values would stop the code from functioning correctly
     '''
     if cmds.intField(self.endFrame,v=1,q=1)<=cmds.intField(self.startFrame,v=1,q=1):
         errorPopup('End Frame must be after Start Frame')
         return
     if cmds.intField(self.nose,v=1,q=1)+cmds.intField(self.tail,v=1,q=1)>cmds.intField(self.length,v=1,q=1):
         errorPopup('Nose and Tail must be less than Trail Length')
         return
     try:
         tmp = cmds.duplicateCurve(cmds.textField(self.sourceCurve,tx=1,q=1))[0]
         cmds.delete(tmp)
     except:
         errorPopup('Choose a source curve')
         return
     particleFX.reloadFile()
     cmds.progressWindow(title='SnowFX',
                                   progress=0,
                                   status='Starting up...')
     try:
         particles=self.makeAllParticles()
         particleFX.followCurve(cmds.textField(self.sourceCurve,tx=1,q=1),
                                        cmds.intField(self.startFrame,v=1,q=1),
                                        cmds.intField(self.endFrame,v=1,q=1)-cmds.intField(self.startFrame,v=1,q=1),
                                        particles,
                                        cmds.floatField(self.maxDistance,v=1,q=1),
                                        cmds.floatField(self.minDistance,v=1,q=1),
                                        cmds.intField(self.nose,v=1,q=1),
                                        cmds.intField(self.tail,v=1,q=1),
                                        cmds.intField(self.length,v=1,q=1),
                                        cmds.floatField(self.turbulenceAmp,v=1,q=1),
                                        cmds.intField(self.turbulencePer,v=1,q=1))
         group = cmds.group(em=1,n='snowFX')
         for x in particles:
             cmds.parent(x.name,group)
         cmds.progressWindow(ep=1)
     except Exception, err:
         sys.stderr.write('ERROR: %s\n' % str(err))
         cmds.progressWindow(ep=1)
         errorPopup('Something went wrong :( \n Check the script editor for detials')
Ejemplo n.º 15
0
def duplicate_shape(shape):
    """
    mc.duplicate can't duplicate a shape. This provides for it

    :parameters:
    	shape(str): shape to dupliate

    :returns
    	[shape,transform]

    """
    try:
        _str_func = 'duplicate_shape'
        _type = VALID.get_mayaType(shape)
        if _type == 'nurbsCurve':
            _bfr = mc.duplicateCurve(shape)

            parentObj = mc.listRelatives(shape, p=True, fullPath=True)
            mc.delete(mc.parentConstraint(parentObj, _bfr[0]))
            _l_shapes = mc.listRelatives(_bfr[0], s=True, f=True)

            return [_bfr[0]] + _l_shapes
        else:
            log.debug("|{0}|  >> mesh shape assumed...".format(_str_func))
            _transform = SEARCH.get_transform(shape)
            _shapes = mc.listRelatives(_transform, s=True, fullPath=True)
            _idx = _shapes.index(coreNames.get_long(shape))

            _bfr = mc.duplicate(shape)
            _newShapes = mc.listRelatives(_bfr[0], s=True, fullPath=True)
            _dupShape = _newShapes[_idx]
            _newShapes.pop(_idx)
            mc.delete(_newShapes)

            return [_bfr[0], _dupShape]

    except Exception, err:
        pprint.pprint(vars())
        if not SEARCH.is_shape(shape):
            log.error("|{0}|  >> Failure >> Not a shape: {1}".format(
                _str_func, shape))
        raise Exception, "|{0}|  >> failed! | err: {1}".format(_str_func, err)
Ejemplo n.º 16
0
 def updateSourceCurve(self,state):
     '''
     Adds the name of the selected curve to the text field.
     Will create an error popup if a single curve isn't selected
     '''
     if len(cmds.ls(sl=1))>1:
         errorPopup('Select only the target curve')
         return
     elif len(cmds.ls(sl=1))==0:
         errorPopup('Select a curve')
         return
     selected = cmds.ls(sl=1)[0]
     try:
         tmp = cmds.duplicateCurve(cmds.ls(sl=1)[0])[0]
         cmds.delete(tmp)
     except:
         errorPopup('Select a curve')
         return
     cmds.textField(self.sourceCurve,tx=selected,edit=1)
     return
Ejemplo n.º 17
0
def chordLength(surface,param=0.0,direction='u'):
	'''
	Return the length of a surface isoparm given a parameter and a direction
	@param surface: Surface to query closest point from
	@type surface: str
	@param param: The parameter on the surface to query length of
	@type param: float
	@param direction: Direction along the surface to measure length of
	@type direction: str
	'''
	# Check surface
	if not isSurface(surface): raise UserInputError('Object '+surface+' is not a valid surface!')
	# Duplicate surface curve
	curve = mc.duplicateCurve(surface+'.'+direction+'['+str(param)+']',ch=0,rn=0,local=0)
	# Measure curve length
	length = mc.arclen(curve[0])
	# Cleanup
	mc.delete(curve)
	# Return result
	return length
Ejemplo n.º 18
0
def curve_from_edge():
    '''
    creates a curve from the selected edges
    Need to select the edges individually in the order that makes up the curve for attach curve to work
    it's crude, but it does what I need it to do 
    
    This is dodgy and doesn't always work....need to re-write
    '''
    edges = cmds.ls(sl=True)
    curves = list()

    for edge in edges:
        crv = cmds.duplicateCurve(edge)
        curves.append(crv[0])

    new_curve = cmds.attachCurve(curves,
                                 ch=1,
                                 rpo=0,
                                 kmk=1,
                                 m=1,
                                 bb=0.5,
                                 bki=0,
                                 p=0.1)
    cmds.delete(curves)
    cmds.rebuildCurve(new_curve[0],
                      ch=1,
                      rpo=1,
                      rt=0,
                      end=1,
                      kr=0,
                      kcp=1,
                      kep=1,
                      kt=0,
                      s=4,
                      d=3,
                      tol=0.01)

    return new_curve
Ejemplo n.º 19
0
def isoparmCoord(surfaceSkin, influence, controlPoints, coord, direction='u'):
    '''
	Set the target coordinates for the specified control points to lie along a given isoparm
	@param surfaceSkin: surfaceSkin node to apply the coordinates to
	@type surfaceSkin: str
	@param influence: surfaceSkin influence to get coordinate for
	@type influence: str
	@param controlPoints: List of control points to set the target coordinates for
	@type controlPoints: list
	@param coord: Coordinate value of the target isoparm
	@type coord: float
	@param direction: Direction of the isoparm
	@type direction: str
	'''
    # Get surface curve
    crv = mc.duplicateCurve(influence + '.' + direction + '[' + str(coord) +
                            ']',
                            ch=False,
                            rn=0,
                            local=0,
                            n=influence + 'TEMP_CRV')[0]

    # Iterate through control point list
    for controlPoint in controlPoints:
        # Get component position
        pos = mc.pointPosition(controlPoint)
        # Get closest point on curve
        cCoord = glTools.utils.curve.closestPoint(crv, pos)
        # Apply Coord
        uvCoord = (0, 0)
        if direction == 'u': uvCoord = (coord, cCoord)
        else: uvCoord = (cCoord, coord)
        applyCoord(surfaceSkin, influence, controlPoint, uvCoord)

    # Delete surface curve
    mc.delete(crv)
Ejemplo n.º 20
0
def ribbonize(surf_tr,
              equal=1,
              num_of_ctrls=5,
              num_of_jnts=29,
              prefix="",
              constrain=1,
              add_fk=0,
              wire=0):

    attrs = [
        ".tx", ".ty", ".tz", ".rx", ".ry", ".rz", ".sx", ".sy", ".sz", ".v"
    ]

    if prefix == "":
        mc.warning("te importa nombrarlo?")
        return

    else:
        prefix = prefix + "_"

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

    surf_tr = mc.rename(surf_tr, prefix + "ribbon_surface")
    surf = mc.listRelatives(surf_tr, shapes=True)[0]

    # Congelar transformaciones y borrar el historial de superficies.
    mc.makeIdentity(surf_tr, t=True, r=True, s=True, apply=True)
    mc.delete(surf_tr, ch=True)

    # duplicar la superficie curvas para determinar la direccion.
    u_curve = mc.duplicateCurve(surf_tr + ".v[.5]", local=True, ch=0)
    v_curve = mc.duplicateCurve(surf_tr + ".u[.5]", local=True, ch=0)

    # borro historial solo porsiaca.
    mc.delete(surf_tr, ch=True)

    u_length = mc.arclen(u_curve)
    v_length = mc.arclen(v_curve)

    if u_length < v_length:
        mc.reverseSurface(surf_tr, d=3, ch=False, rpo=True)
        mc.reverseSurface(surf_tr, d=0, ch=False, rpo=True)

    parameter = ".parameterU"
    other_param = ".parameterV"

    # corrija u_curve despues de invertir para calcular la longitud.
    u_curve_corr = mc.duplicateCurve(surf_tr + ".v[.5]", local=True, ch=0)[0]

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

    # La superficie seleccionada es periodica o abierta? (cilindro o plano)
    if mc.getAttr(surf + ".formU") == 2 or mc.getAttr(surf + ".formV") == 2:
        curve_type = "periodic"
        divider_for_ctrls = num_of_ctrls
    elif mc.getAttr(surf + ".formU") == 0 or mc.getAttr(surf + ".formV") == 0:
        curve_type = "open"
        divider_for_ctrls = num_of_ctrls - 1

    #############################################################################
    param_ctrls = param_from_length(u_curve_corr, num_of_ctrls, curve_type,
                                    "uv")
    param_joints = param_from_length(u_curve_corr, num_of_jnts, curve_type,
                                     "uv")

    length = mc.arclen(u_curve_corr)
    mc.delete(u_curve, v_curve, u_curve_corr)

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

    # Creo grupos, Control General y control general de offset
    final_group = mc.group(n=prefix + "ribbon_grp", em=True)
    ctrl_joints_grp = mc.group(n=prefix + "ctrl_joints_grp", em=True)
    ctrl_grp = mc.group(n=prefix + "ctrls_grp", em=True)
    follicles_grp = mc.group(n=prefix + "follicles_grp", em=True)
    rig_grp = mc.group(n=prefix + "rig_grp", em=True)
    main_ctrl = mc.circle(n=prefix + "ctrl_main",
                          nr=(0, 1, 0),
                          r=length / 5,
                          ch=0)[0]
    main_ctrl_offset = mc.group(n=prefix + "ctrl_main_offset", em=True)

    mc.parent(main_ctrl, main_ctrl_offset)
    mc.parent(ctrl_grp, main_ctrl)
    mc.parent(main_ctrl_offset, rig_grp, final_group)
    mc.parent(surf_tr, ctrl_joints_grp, follicles_grp, rig_grp)

    # Muevo main_ctrl_offset al centro de la geometria bbox (en caso de que el pivote este en otro lugar)
    mid_point = get_bbox_center(surf_tr)
    for attr, mid_pnt_el in izip(attrs[:3], mid_point):
        mc.setAttr(main_ctrl_offset + attr, mid_pnt_el)

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

    fols = []
    fols_tr = []
    bind_jnts = []
    bnd_joints_rad = (length / 60) / (float(num_of_jnts) / 40)

    for x in range(num_of_jnts):

        fol = mc.createNode("follicle")
        mc.setAttr(fol + ".visibility", 0)
        temp_fol = mc.listRelatives(fol, p=True)[0]
        fols_tr.append(
            mc.rename(temp_fol, "{}follicle_{:02d}".format(prefix, x + 1)))
        fols.append(mc.listRelatives(fols_tr[-1], s=True)[0])

        # conecto follicle shapes al transform
        mc.connectAttr(fols[-1] + ".outTranslate",
                       fols_tr[-1] + ".translate",
                       f=True)
        mc.connectAttr(fols[-1] + ".outRotate",
                       fols_tr[-1] + ".rotate",
                       f=True)

        # atacho follicle shapes a la superficie
        mc.connectAttr(surf + ".worldMatrix[0]",
                       fols[-1] + ".inputWorldMatrix")
        mc.connectAttr(surf + ".local", fols[-1] + ".inputSurface")

        mc.setAttr(fols[-1] + parameter, param_joints[x])
        mc.setAttr(fols[-1] + other_param, 0.5)

        mc.parent(fols_tr[-1], follicles_grp)

        # creo el  bind final y joints en la superficie
        bind_jnts.append(
            mc.createNode("joint", n="{}bnd_jnt_{:02d}".format(prefix, x + 1)))

        mc.parent(bind_jnts[-1], fols_tr[-1], r=True)
        mc.setAttr(bind_jnts[-1] + ".radius", bnd_joints_rad)

    set_color(bind_jnts, "mid_blue")

    #creo un  temporal follicles para controles offset groups para alinear
    temp_fols = []
    temp_fols_tr = []

    for x in range(num_of_ctrls):

        temp_fols.append(mc.createNode("follicle"))
        temp_fols_tr.append(mc.listRelatives(temp_fols[-1], p=True)[0])

        mc.connectAttr(temp_fols[-1] + ".outTranslate",
                       temp_fols_tr[-1] + ".translate",
                       f=True)
        mc.connectAttr(temp_fols[-1] + ".outRotate",
                       temp_fols_tr[-1] + ".rotate",
                       f=True)

        mc.connectAttr(surf + ".worldMatrix[0]",
                       temp_fols[-1] + ".inputWorldMatrix")
        mc.connectAttr(surf + ".local", temp_fols[-1] + ".inputSurface")

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

    if equal == 1:
        for x, temp_fol in enumerate(temp_fols):
            mc.setAttr(temp_fol + parameter, param_ctrls[x])
            mc.setAttr(temp_fol + other_param, 0.5)
    if equal == 0:
        v = 0
        for temp_fol in temp_fols:
            mc.setAttr(temp_fol + parameter, v)
            mc.setAttr(temp_fol + other_param, 0.5)
            v = v + (1.0 / divider_for_ctrls)

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

    #creo controles y controle para joints
    controls = ctrl_maker(prefix,
                          ctrl_type="cube",
                          count=num_of_ctrls,
                          deg=3,
                          sp=8)

    ctrl_ofs_grps = []
    ctrl_joints = []
    ctrl_jnt_ofs_grps = []
    ctrl_joints_rad = bnd_joints_rad * 2
    ik_ctrl_scale = (length / 35) / (float(num_of_ctrls) / 5)

    for x, ctrl in enumerate(controls):

        ctrl_ofs_grp = mc.group(ctrl, n="{}_offset".format(ctrl))
        mc.delete(mc.parentConstraint(temp_fols_tr[x], ctrl_ofs_grp))
        ctrl_ofs_grps.append(ctrl_ofs_grp)

        #escala ik controls
        ctrl_shapes = mc.listRelatives(ctrl, s=True)
        for ctrl_shape in ctrl_shapes:
            ctrl_cvs_count = mc.getAttr(ctrl_shape + ".controlPoints",
                                        size=True)
            mc.scale(ik_ctrl_scale,
                     ik_ctrl_scale,
                     ik_ctrl_scale,
                     "{}.cv[0:{}]".format(ctrl_shape, ctrl_cvs_count - 1),
                     r=True,
                     ocp=True)

        #creo los controles de joints
        ctrl_joints.append(
            mc.createNode("joint", n="{}ctrl_jnt_{:02d}".format(prefix,
                                                                x + 1)))
        #seteo el radio de controles para joints de 2 tiepos. de el surface y joints
        mc.setAttr(ctrl_joints[x] + ".radius", ctrl_joints_rad)
        #creo offset groups para cotroles de joints
        ctrl_jnt_ofs_grp = mc.group(ctrl_joints[-1],
                                    n="{}_offset".format(ctrl_joints[-1]))
        mc.delete(mc.parentConstraint(temp_fols_tr[x], ctrl_jnt_ofs_grp))
        ctrl_jnt_ofs_grps.append(ctrl_jnt_ofs_grp)

    ###
    set_color(controls, "green")
    set_color(ctrl_joints, "red")

    mc.parent(ctrl_ofs_grps, ctrl_grp)
    mc.parent(ctrl_jnt_ofs_grps, ctrl_joints_grp)

    lock_hide(ctrl_ofs_grps, attrs[:9])
    lock_hide(ctrl_jnt_ofs_grps, attrs[:9])

    mc.delete(temp_fols_tr)

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

    #determino que constraint o coneccion o metodo es elegido# que formalidad
    if constrain == 0:
        for (c, j) in izip(controls, ctrl_joints):
            for attr in attrs[:7]:  #skip de la escala de atributos
                mc.connectAttr(c + attr, j + attr)

        mc.parentConstraint(main_ctrl, ctrl_joints_grp, mo=True)
        mc.scaleConstraint(main_ctrl, ctrl_joints_grp)

        #escala del foliculo con el main // por coneccion del editor
        for flt in fols_tr:
            mc.connectAttr(main_ctrl + ".sx", flt + ".sx")
            mc.connectAttr(main_ctrl + ".sx", flt + ".sy")
            mc.connectAttr(main_ctrl + ".sx", flt + ".sz")

    elif constrain == 1:
        for (c, j) in izip(controls, ctrl_joints):
            mc.parentConstraint(c, j)
            mc.scaleConstraint(c, j)

        #scala del folliculos con el main control
        for flt in fols_tr:
            mc.scaleConstraint(main_ctrl, flt)

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

    if wire == True and num_of_ctrls > 1:

        temp_crv = mc.duplicateCurve(surf_tr + ".v[.5]",
                                     n=prefix + "wire_crv",
                                     local=False,
                                     ch=0)[0]

        if num_of_ctrls == 2:
            degree = 1
        else:
            degree = 3

        wire_crv = mc.curve(p=param_from_length(
            temp_crv, num_of_ctrls + (num_of_ctrls - 1), "open", "world"),
                            d=degree)

        mc.delete(temp_crv)

        wire_crv = mc.rename(
            wire_crv, prefix + "wire_crv"
        )  # Si el nombre va en el momento de la creacion, la forma no se renombra
        mc.delete(wire_crv, ch=True)
        wire = mc.wire(surf_tr,
                       gw=False,
                       en=1.0,
                       ce=0.0,
                       li=0.0,
                       dds=(0, 50),
                       w=wire_crv,
                       n=prefix + "wire")[0]
        mc.connectAttr(main_ctrl + ".sx", wire + ".scale[0]")

        cps = param_from_length(wire_crv,
                                num_of_ctrls,
                                "open",
                                "uv",
                                normalized=False)

        for cp in cps:
            mc.select("{}.u[{}]".format(wire_crv, cp), r=True)
            mc.dropoffLocator(1.0, 1.0, wire)

        mc.select(cl=True)

        for x, ctrl in enumerate(controls):
            mc.connectAttr(ctrl + ".rx",
                           "{}.wireLocatorTwist[{}]".format(wire, x))

        wire_grp = mc.group(wire_crv,
                            wire_crv + "BaseWire",
                            n=prefix + "wire_crv_grp")
        mc.parent(wire_grp, rig_grp)
        lock_hide([wire_grp], attrs[:9])

        wire_skin_cluster = mc.skinCluster(ctrl_joints,
                                           wire_crv,
                                           dr=2,
                                           mi=2,
                                           bm=0)[0]

    else:
        #bind de la superficie a los joints
        nurbs_skin_cluster = mc.skinCluster(ctrl_joints,
                                            surf_tr,
                                            dr=2,
                                            mi=num_of_ctrls - 1,
                                            ns=num_of_ctrls * 5,
                                            bm=0,
                                            n=prefix + "skinCluster")[0]
        mc.skinPercent(nurbs_skin_cluster, surf_tr, pruneWeights=0.2)

    if wire == True and num_of_ctrls == 1:
        mc.warning("wire skipped. at least 2 controls needed")

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

    mc.setAttr(surf_tr + ".v", 0)
    mc.setAttr(rig_grp + ".v", 0)

    mc.connectAttr(main_ctrl + ".sx", main_ctrl + ".sy")
    mc.connectAttr(main_ctrl + ".sx", main_ctrl + ".sz")
    mc.aliasAttr("Scale", main_ctrl + ".sx")

    set_color(main_ctrl, "yellow")

    mc.connectAttr(main_ctrl_offset + ".sx", main_ctrl_offset + ".sy")
    mc.connectAttr(main_ctrl_offset + ".sx", main_ctrl_offset + ".sz")
    mc.aliasAttr("Scale", main_ctrl_offset + ".sx")

    #lock and hide atributos
    lock_hide([
        final_group, follicles_grp, ctrl_joints_grp, surf_tr, ctrl_grp, rig_grp
    ], attrs[:9])
    lock_hide([ctrl_grp, main_ctrl, main_ctrl_offset], attrs[7:])
    lock_hide(controls, attrs[7:])

    #limpiamos seleccion (clear selection)
    mc.select(
        cl=True
    )  #Si la seleccion no se borra, se agrega un bind de control al conjunto de bind de enlace

    #crea a set con bind joints
    bind_jnts_set = mc.sets(n=prefix + "bind_jnts_set")
    mc.sets(bind_jnts, add=bind_jnts_set)

    mc.select(cl=True)

    ik_ctrls_set = mc.sets(n=prefix + "ik_ctrls_set")
    mc.sets(controls, add=ik_ctrls_set)

    mc.select(cl=True)

    controls_set = mc.sets(n=prefix + "controls_set")
    mc.sets(main_ctrl, ik_ctrls_set, add=controls_set)

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

    if add_fk == 1 and mc.getAttr(surf + ".formU") != 2 and mc.getAttr(
            surf + ".formV") != 2:

        fk_ctrls, fk_ctrl_off_grps = make_fk_ctrls(prefix, num_of_ctrls)
        mc.parent(fk_ctrl_off_grps[0], ctrl_grp)

        #scala fk controls
        fk_ctrl_scale = ik_ctrl_scale * 2

        for fk_ctrl in fk_ctrls:
            fk_ctrl_shapes = mc.listRelatives(fk_ctrl, s=True)
            for fk_ctrl_shape in fk_ctrl_shapes:
                fk_ctrl_cvs_count = mc.getAttr(fk_ctrl_shape +
                                               ".controlPoints",
                                               size=True)
                mc.scale(fk_ctrl_scale,
                         fk_ctrl_scale,
                         fk_ctrl_scale,
                         "{}.cv[0:{}]".format(fk_ctrl_shape,
                                              fk_ctrl_cvs_count - 1),
                         r=True,
                         ocp=True)

        #add fk controls al set
        mc.select(cl=True)
        fk_ctrls_set = mc.sets(n=prefix + "fk_ctrls_set")
        mc.sets(fk_ctrls, add=fk_ctrls_set)

        ########
        ik_ctrl_constr_grps = [
            mc.group(ctrl, n=ctrl + "_constr_grp") for ctrl in controls
        ]
        [
            mc.xform(ik_ctrl_constr_grp, piv=(0, 0, 0), os=True)
            for ik_ctrl_constr_grp in ik_ctrl_constr_grps
        ]

        for ik, fk in izip(controls[:-1], fk_ctrl_off_grps):
            mc.delete(mc.parentConstraint(ik, fk))

        for fk, ik in izip(fk_ctrls, ik_ctrl_constr_grps[:-1]):
            mc.parentConstraint(fk, ik)

        #constrain ultimo ik ctrl
        mc.parentConstraint(fk_ctrls[-1], ik_ctrl_constr_grps[-1], mo=True)
        lock_hide(ik_ctrl_constr_grps, attrs[:9])

        ########
        set_color(fk_ctrls, "blue")
        lock_hide(fk_ctrl_off_grps, attrs[:9])

        mc.sets(fk_ctrls_set, add=controls_set)

        mc.select(cl=True)

    elif add_fk == 1 and (mc.getAttr(surf + ".formU") == 2
                          or mc.getAttr(surf + ".formV") == 2):

        mc.warning("surface is periodic. fk controls skipped")

    ################ ADD mensaje de atributo ################

    mc.addAttr(main_ctrl, ln="joints", at="message")
    mc.addAttr(main_ctrl, ln="follicles", at="message")
    mc.addAttr(main_ctrl, ln="surface", at="message")

    if mc.attributeQuery("i_am_the_surface", node=surf, exists=True) == False:
        mc.addAttr(surf, ln="i_am_the_surface", at="message")

    mc.connectAttr(main_ctrl + ".surface", surf + ".i_am_the_surface")

    for j, f in izip(bind_jnts, fols):
        mc.addAttr(j, ln="i_am_a_joint", at="message")
        mc.addAttr(f, ln="i_am_a_follicle", at="message")
        mc.connectAttr(main_ctrl + ".joints", j + ".i_am_a_joint")
        mc.connectAttr(main_ctrl + ".follicles", f + ".i_am_a_follicle")
Ejemplo n.º 21
0
def createGroupOnSurface(NURBS='', jntNum=5):
    nameRbnCrv = ''
    nameRbnPosGrpList = []
    nameRbnPosiList = []
    nameRbnAimList = []
    jntDistance = [0.050, 0.275, 0.500, 0.725, 0.950]
    ampNum = 0
    name = NURBS.split('_')[0]
    side = NURBS.split('_')[1]
    # create em Grp, pointOnSurfaceInfo Node, aimConstraint Node
    for i in range(0, jntNum):
        # em
        grp = mc.group(em=True,
                       n=name + str(i + 1) + '_rbnPos' + side + '_grp')
        # pointOnSurfaceInfo
        posiNode = mc.createNode('pointOnSurfaceInfo',
                                 n=name + str(i + 1) + '_rbnPos' + side +
                                 '_posi')
        # aimConstraint
        aimNode = mc.createNode('aimConstraint',
                                n=name + str(i + 1) + '_rbnPos' + side +
                                '_aim',
                                parent=grp)
        # add to List
        nameRbnPosGrpList.append(grp)
        nameRbnPosiList.append(posiNode)
        nameRbnAimList.append(aimNode)
        # connect Node Path
        mc.connectAttr(NURBS + 'Shape.worldSpace', posiNode + '.inputSurface')
        mc.connectAttr(posiNode + '.normal', aimNode + '.worldUpVector')
        mc.connectAttr(posiNode + '.tangentU',
                       aimNode + '.target[0].targetTranslate')
        mc.connectAttr(posiNode + '.position', grp + '.translate')
        mc.connectAttr(aimNode + '.constraintRotate', grp + '.rotate')
        # set grp's Position
        mc.setAttr(posiNode + '.parameterV', 0.5)
        mc.setAttr(posiNode + '.parameterU', jntDistance[i])
        # set aimVector
        mc.setAttr(aimNode + '.aimVector', 0, 1, 0)
        mc.setAttr(aimNode + '.upVector', 0, 0, 1)
    # create crv
    crvName = mc.duplicateCurve(NURBS + '.v[0.5]',
                                ch=0,
                                rn=1,
                                local=1,
                                n=name + '_rbn' + side + '_crv')[0]
    # create curveFromSurfaceIso Node and connect
    cfsNodeName = mc.createNode('curveFromSurfaceIso',
                                n=name + '_rbnPos' + side + '_cfs')
    mc.setAttr(cfsNodeName + '.isoparmValue', 0.5)
    mc.connectAttr(NURBS + 'Shape.worldSpace', cfsNodeName + '.inputSurface')
    mc.connectAttr(cfsNodeName + '.outputCurve', crvName + '.create')
    # create still grp
    stillGrpName = mc.group(em=True, n=name + '_rbnStill' + side + '_grp')
    mc.parent(nameRbnPosGrpList, stillGrpName)
    mc.parent(NURBS, stillGrpName)
    mc.parent(crvName, stillGrpName)
    mc.setAttr(NURBS + '.v', False)
    mc.setAttr(crvName + '.v', False)

    return {
        'stillGrpName': stillGrpName,
        'nameRbnPosGrpList': nameRbnPosGrpList,
        'crvName': crvName
    }
Ejemplo n.º 22
0
def duplicateCurve(*args, **kwargs):
    tmp = mc.duplicateCurve(*args, **kwargs)
    crv = Dag(tmp[0])
    cfs = Node(tmp[1])
    return crv, cfs
Ejemplo n.º 23
0
def projectToSurface(surface,
                     targetSurface,
                     direction='u',
                     keepOriginal=False,
                     prefix=''):
    """
    Project the edit points of the specified nurbs surface to another nurbs or polygon object
    @param surface: Surface to project
    @type surface: str
    @param targetSurface: Surface to project onto
    @type targetSurface: str
    @param direction: Surface direction to extract isoparm curves from
    @type direction: str
    @param keepOriginal: Create new surface or replace original
    @type keepOriginal: bool
    @param prefix: Name prefix for all created nodes
    @type prefix: str
    """
    # Check surface
    if not cmds.objExists(surface):
        raise Exception('Surface "' + surface + '" does not exist!!')
    if not isSurface(surface):
        raise Exception('Object "' + surface +
                        '" is not a valid nurbs surface!!')

    # Check target surface
    if not cmds.objExists(targetSurface):
        raise Exception('Target surface "' + targetSurface +
                        '" does not exist!!')

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

    # Check direction
    direction = direction.upper()
    if (direction != 'U') and (direction != 'V'):
        raise Exception(
            'Invalid surface direction specified! Must specify either "u" or "v"!!'
        )

    # Get surface information
    spans = cmds.getAttr(surface + '.spans' + direction)
    minVal = cmds.getAttr(surface + '.minValue' + direction)
    maxVal = cmds.getAttr(surface + '.maxValue' + direction)

    # Create main surface group
    mainGrp = cmds.createNode('transform', n=prefix + '_grp')

    # Extract curves
    curveList = []
    curveGrpList = []
    curveLocList = []
    geocmdsonstraintList = []
    spanInc = (maxVal - minVal) / spans
    for i in range(spans + 1):
        # Curve prefix
        strInd = glTools.utils.stringUtils.stringIndex(i, 2)
        crvPrefix = prefix + '_crv' + strInd
        # Create curve group
        curveGrp = crvPrefix + '_grp'
        curveGrp = cmds.createNode('transform', n=curveGrp)
        curveGrp = cmds.parent(curveGrp, mainGrp)[0]
        curveGrpList.append(curveGrp)
        # Get surface curve
        srfCurveName = crvPrefix + '_crv'
        srfCurve = cmds.duplicateCurve(surface + '.' + direction.lower() +
                                       '[' + str(i * spanInc) + ']',
                                       ch=0,
                                       rn=0,
                                       local=0,
                                       n=srfCurveName)
        srfCurve = cmds.parent(srfCurve[0], curveGrp)[0]
        curveList.append(srfCurve)
        # Generate curve locators
        curveLocatorList = glTools.utils.curve.locatorEpCurve(
            srfCurve, locatorScale=0.05, prefix=crvPrefix)
        curveLocatorList = cmds.parent(curveLocatorList, curveGrp)
        curveLocList.append(curveLocatorList)
        # Create geometry constraints
        for loc in curveLocatorList:
            geocmdsonstraint = crvPrefix + '_geometryConstraint'
            geocmdsonstraint = cmds.geometryConstraint(targetSurface,
                                                       loc,
                                                       n=geocmdsonstraint)
            geocmdsonstraintList.append(geocmdsonstraint[0])
        # Center group pivot
        cmds.xform(curveGrp, cp=True)

    # Delete original surface
    surfaceName = prefix + '_surface'
    if not keepOriginal:
        surfaceName = surface
        cmds.delete(surface)

    # Loft new surface
    surfaceLoft = cmds.loft(curveList,
                            ch=1,
                            u=1,
                            c=0,
                            ar=1,
                            d=3,
                            ss=1,
                            rn=0,
                            po=0,
                            rsn=True)
    surface = cmds.rename(surfaceLoft[0], surface)
    surface = cmds.parent(surface, mainGrp)[0]
    cmds.reorder(surface, f=True)
    loft = cmds.rename(surfaceLoft[1], prefix + '_loft')

    # Return result
    return [
        surface, loft, curveList, curveGrpList, curveLocList,
        geocmdsonstraintList
    ]
Ejemplo n.º 24
0
def buildSystem(ctrl_amount=3, fk_ctrl_amount=3, bindJnt_amount=30.0, name=""):
    #########################################################################
    # SETUP SECTION ---
    # We need free controls only in the middle - so increasing the ctrl count by 2, considering the start and end
    crvStep = 100 / (ctrl_amount + 1) / 100

    ctrl_color_dic = {
        'yellow': (0, 1, 1),
        'orange': (0.28, 0.42, 0.99),
        'red': (0.83, 0.04, 1),
        'magenta': (1, 0.04, 0.57),
        'purple': (1, 0, 0),
        'babyBlue': (1, 0.5, 0),
        'aqua': (1, 1, 0)
    }

    # Get surface from selection
    raw_surface = cmds.ls(sl=1)
    # Duplicate and rename surface
    surface = cmds.duplicate(raw_surface, n="{}_Output_Srf".format(name))
    cmds.setAttr(raw_surface[0] + ".visibility", 0)
    cmds.select(cl=1)
    # Create wire curve from surface
    v_curve = cmds.duplicateCurve(surface[0] + ".v[.5]",
                                  local=True,
                                  ch=0,
                                  n=name + "_MainWire_Crv")

    # Get degrees and spans to calculte CV's
    v_curve_shape = cmds.listRelatives(v_curve, s=1)[0]
    curveDeg = cmds.getAttr(v_curve_shape + ".degree")
    curveSpa = cmds.getAttr(v_curve_shape + ".spans")
    # CV's = degrees + spans
    cvCount = curveDeg + curveSpa

    # Deletes extra cvs, rebuilds curve, del hist, unparent curve
    cmds.delete(v_curve[0] + '.cv[{}]'.format(cvCount - 2),
                v_curve[0] + '.cv[1]')
    cmds.rebuildCurve(v_curve,
                      ch=0,
                      rpo=1,
                      rt=0,
                      end=1,
                      kr=0,
                      kcp=1,
                      kep=1,
                      kt=0,
                      d=1,
                      tol=0.01)
    cmds.rebuildCurve(v_curve,
                      ch=0,
                      rpo=1,
                      rt=0,
                      end=1,
                      kr=0,
                      kcp=1,
                      kep=1,
                      kt=0,
                      d=3,
                      tol=0.01)
    cmds.delete(surface[0], v_curve, ch=1)
    cmds.parent(v_curve, w=1)
    cmds.select(cl=1)

    # Declaring lists for Group and Hide
    surface_list = []
    crv_list = []
    freeSys_ctrl_list = []
    main_ctrl_list = []
    cluster_list = []
    follicle_list = []

    #########################################################################
    # FK SYSTEM SECTION
    fk_sys_data = createFKSys(ctrl_amount=fk_ctrl_amount,
                              curve=v_curve,
                              name=name,
                              color1=ctrl_color_dic['purple'],
                              color2=ctrl_color_dic['magenta'])
    crv_list.append(fk_sys_data['curve'])
    crv_list.append(fk_sys_data['base_wire'])

    #########################################################################
    # FREE CONTROL SYSTEM SECTION ---
    # Create FreeCtrl Sys - According to Ctrl Amount
    for i in range(int(ctrl_amount)):
        # i starts in 0, so adding 1 to skip
        # Find current ctrl parameter
        parameter = (i + 1) * crvStep
        # Duplicate curve and surface for parallel sys
        crv_copy = cmds.duplicate(v_curve,
                                  n="{}_{}_freeSys_Wire_Crv".format(
                                      name, str(i)))
        surface_copy = cmds.duplicate(surface,
                                      n="{}_{}_freeSys_Srf".format(
                                          name, str(i)))
        cmds.select(cl=1)

        # Create free control system
        new_ctrl_data = createCtrlSys(crv=crv_copy,
                                      rootCrv=v_curve,
                                      surface=surface_copy,
                                      rootSurface=surface,
                                      name=name,
                                      parameter=parameter,
                                      iteration=i)
        # Set control color
        setCtrlColor(new_ctrl_data[3], color=ctrl_color_dic['babyBlue'])

        # Add surface to blend list
        surface_list.append(surface_copy[0])
        # Get base wire - Append curve and Base Wire to group list
        crv_copy_bWire = crv_copy[0] + "BaseWire"
        crv_list.append(crv_copy[0])
        crv_list.append(crv_copy_bWire)
        # Append cluster, ctrl and follicle
        cluster_list.append(new_ctrl_data[0])
        freeSys_ctrl_list.append(new_ctrl_data[1])
        follicle_list.append(new_ctrl_data[2])

    # Group freeSys follicles
    follicle_freeSys_grp = cmds.group(follicle_list,
                                      n="{}_FreeSys_Flc_Grp".format(name))

    #########################################################################
    # MAIN SYSTEM SECTION ---
    # Build Start/End(Main) control system
    baseSys_surface_copy = cmds.duplicate(surface,
                                          n="{}_MainSys_Srf".format(name))
    main_ctrl_data = createBaseCtrl(v_curve,
                                    baseSys_surface_copy,
                                    name=name + "_Main",
                                    color1=ctrl_color_dic['orange'],
                                    color2=ctrl_color_dic['red'])

    # Append created clusters
    cluster_list.append(main_ctrl_data[4][1])
    cluster_list.append(main_ctrl_data[5][1])
    # Append created surface to blendshape list
    surface_list.append(baseSys_surface_copy[0])
    # Append created control groups to list
    main_ctrl_list.append(main_ctrl_data[1])
    main_ctrl_list.append(main_ctrl_data[3])
    # Append curve and base wire to group list
    v_curve_bWire = v_curve[0] + "BaseWire"
    crv_list.append(v_curve[0])
    crv_list.append(v_curve_bWire)

    #########################################################################
    # GLOBAL CTRL SECTION ---
    # Create joint
    outputSrf_jnt = cmds.joint(n="{}_GlobalCtrl_Jnt".format(name))
    # Position joint on surface middle - find mid position
    ctrl_avg = []
    ctrl_start_ws = cmds.xform(main_ctrl_data[0], q=1, t=1, ws=1)
    ctrl_end_ws = cmds.xform(main_ctrl_data[2], q=1, t=1, ws=1)
    for t, p in zip(ctrl_start_ws, ctrl_end_ws):
        ctrl_avg.append((t + p) / 2)
    cmds.xform(outputSrf_jnt, t=ctrl_avg)
    # Skin bind to output surface
    skinBind_node = cmds.skinCluster(surface[0], outputSrf_jnt)
    # Create global ctrl + grp - ADD- Make scale variable to arcLength
    global_ctrl_data = bd_buildCtrl(ctrl_type="sphere",
                                    name=name + "_Global",
                                    scale=5)
    # Change Ctrl color
    setCtrlColor(global_ctrl_data[0], color=ctrl_color_dic['yellow'])
    # Position ctrl
    cmds.xform(global_ctrl_data[1], t=ctrl_avg)
    '''
	# Add control visibility attributes - Bind Ctrls, Free Ctrls
	cmds.addAttr(control, ln="bindCtrls", nn="Bind_Ctrls", at="double", min=0, max=1, dv=0.5, keyable=True)
	cmds.addAttr(control, ln="freeCtrls", nn="Free_Ctrls", at="double", min=0, max=360, dv=0, keyable=True)
	for i in follicle_list: cmds.connectAttr(global_ctrl_data[0] + ".bindCtrls", i + ".visibility")
	# Add search keyword as attr to  select bind joints 
	'''

    #########################################################################
    # SINE DEFORMER SYSTEM SECTION ---
    sine_data = createSineSys(surface, global_ctrl_data[0], name)
    # Append surface to surface list
    surface_list.append(sine_data[2])
    surface_list.append(sine_data[3])

    #########################################################################
    # BLENDSHAPE WRAP UP SECTION ---
    # Appends the output surface as the last surface - Selects in order and creates blendShape node
    surface_list.append(surface[0])
    cmds.select(cl=1)
    for x in surface_list:
        cmds.select(x, add=1)
    blnd_node = cmds.blendShape(automatic=1)
    # Gets number of shapes - Sets all weights to 1
    blnd_weights = cmds.blendShape(blnd_node, q=True, w=1)
    for y, z in enumerate(blnd_weights):
        cmds.blendShape(blnd_node, edit=1, w=[(y, 1.0)])
    cmds.select(cl=1)
    # Parent constrain output Ribbon jnt to global ctrl
    cmds.parentConstraint(global_ctrl_data[0], outputSrf_jnt, mo=1)
    cmds.scaleConstraint(global_ctrl_data[0], outputSrf_jnt)

    #########################################################################
    # FOLLICLE BIND JNTS SECTION ---
    # Place Follicle Grp and Joint Grp on proper groups bellow
    follicle_bindSys_data = createFlcBindSys(surface=surface,
                                             ctrl_amount=bindJnt_amount,
                                             ctrl_color=ctrl_color_dic['aqua'],
                                             global_ctrl=global_ctrl_data[0],
                                             name=name)

    #########################################################################
    # ORGANIZING, GROUP AND HIDE SECTION ---
    wire_grp = cmds.group(crv_list, n=name + "_Wire_Grp")
    cluster_grp = cmds.group(cluster_list, n=name + "_Cluster_Grp")
    follicle_grp = cmds.group(follicle_freeSys_grp,
                              follicle_bindSys_data[0],
                              sine_data[4],
                              n=name + "_Follicle_Grp")
    surface_grp = cmds.group(surface_list, n=name + "_Surface_Grp")
    joint_grp = cmds.group(fk_sys_data['joint_group'],
                           outputSrf_jnt,
                           follicle_bindSys_data[2],
                           n=name + "_Jnt_Grp")
    # Create new group for deformers
    deformer_grp = cmds.group(sine_data[1], n=name + "_Def_Grp")

    # Parent ctrl groups to global control
    freeSys_ctrl_grp = cmds.group(freeSys_ctrl_list,
                                  n=name + "_FreeSys_Ctrl_Grp")
    cmds.parent(main_ctrl_list, freeSys_ctrl_grp, fk_sys_data['fk_ctrl_grp'],
                global_ctrl_data[0])

    hide_list = [
        wire_grp, cluster_grp, surface_grp, follicle_freeSys_grp, joint_grp,
        deformer_grp, fk_sys_data['fk_remoteCtrl_grp']
    ]
    for w in hide_list:
        cmds.setAttr(w + ".visibility", 0)

    # Parent Def group to noTransform group
    noTransform_grp = cmds.group(fk_sys_data['fk_remoteCtrl_grp'],
                                 wire_grp,
                                 cluster_grp,
                                 follicle_grp,
                                 surface_grp,
                                 joint_grp,
                                 deformer_grp,
                                 n=name + "_NoTransform_Grp")
    transform_grp = cmds.group(global_ctrl_data[1], n=name + "_Transform_Grp")
    cmds.group(noTransform_grp, transform_grp, n=name + "_Bd_Ribbon_Rig_Grp")
    cmds.parent(surface, transform_grp)
    cmds.select(cl=1)
Ejemplo n.º 25
0
from util.homeNul import *

from util.getUParam import *

side = 'Z'
surfix = 'tentacle1'

#mel.eval('nurbsPlane -p 0 0 0 -ax 0 1 0 -w 24 -lr 0.04166666667 -d 3 -u 12 -v 2 -ch 1; objectMoveCommand;')
mel.eval(
    'nurbsPlane -p 0 0 0 -ax 0 1 0 -w 24 -lr 0.04166666667 -d 3 -u 6 -v 2 -ch 1; objectMoveCommand;'
)
nsfName = cmds.rename('nurbsPlane1', side + '_' + surfix + '_NSF')
nsfShape = cmds.listRelatives(nsfName, s=True)[0]

tentacleCurve = cmds.duplicateCurve(side + '_' + surfix + "_NSF.v[0.5]",
                                    ch=True,
                                    n=side + '_' + surfix + '_CRV')[0]

# curve seting

moNode = pathToU(side, surfix, tentacleCurve, 25)
outputLocator = [i for i in moNode[0]]
motionPathNode = [i for i in moNode[1]]
#print outputLocator
#print motionPathNode

cmds.delete(outputLocator, cn=True)
"""
follicleList = cmds.listConnections( nsfName + 'Shape', type='follicle' )
FL = list( set(follicleList) )
follocleShapeList = cmds.listRelatives( FL, s=True )
Ejemplo n.º 26
0
def create(piv=[0,0,0],axis=[0,0,-1],rad=1,dilate_ctrl='',prefix='eyeball'):
	
	#------------------------
	# Generate Profile Curve
	
	# sphere
	eye_sphere = mc.sphere(p=piv,ax=axis,r=rad,n=prefix+'_history')
	# curve from sphere
	eye_crv = mc.duplicateCurve(eye_sphere[0]+'.v[0]')
	eye_crv[0] = mc.rename(eye_crv[0],prefix+'_pfl01_crv')
	# rebuild curve 0-1
	mc.rebuildCurve(eye_crv[0],rpo=1,end=1,kcp=1,kr=0,d=3,tol=0.01)
	
	#------------------------
	# Extract Curve Segments
	
	# detach curve
	eye_crv_detach = mc.detachCurve(eye_crv[0]+'.u[0.125]',eye_crv[0]+'.u[0.25]',rpo=0,ch=1)
	eye_crv_detach[0] = mc.rename(eye_crv_detach[0],prefix+'_pl01_crv')
	eye_crv_detach[1] = mc.rename(eye_crv_detach[1],prefix+'_ir01_crv')
	eye_crv_detach[2] = mc.rename(eye_crv_detach[2],prefix+'_sc01_crv')
	eye_crv_detach[3] = mc.rename(eye_crv_detach[3],prefix+'_cr01_dtc')
	# rebuild curve segments
	pupil_rebuild = mc.rebuildCurve(eye_crv_detach[0],rpo=1,end=1,kep=1,kt=1,kr=0,s=2,d=3,tol=0.01)
	iris_rebuild = mc.rebuildCurve(eye_crv_detach[1],rpo=1,end=1,kep=1,kt=1,kr=0,s=2,d=3,tol=0.01)
	sclera_rebuild = mc.rebuildCurve(eye_crv_detach[2],rpo=1,end=1,kep=1,kt=1,kr=0,s=4,d=3,tol=0.01)
	pupil_rebuild[1] = mc.rename(pupil_rebuild[1],prefix+'_pl01_rbc')
	iris_rebuild[1] = mc.rename(iris_rebuild[1],prefix+'_ir01_rbc')
	sclera_rebuild[1] = mc.rename(sclera_rebuild[1],prefix+'_sc01_rbc')
	
	#------------------------
	# Generate Eye Surfaces
	
	# revolve
	pupil_revolve = mc.revolve(eye_crv_detach[0],po=0,rn=0,ut=0,tol=0.01,degree=3,s=8,ulp=1,ax=[0,0,1])
	iris_revolve = mc.revolve(eye_crv_detach[1],po=0,rn=0,ut=0,tol=0.01,degree=3,s=8,ulp=1,ax=[0,0,1])
	sclera_revolve = mc.revolve(eye_crv_detach[2],po=0,rn=0,ut=0,tol=0.01,degree=3,s=8,ulp=1,ax=[0,0,1])
	# rename surfaces
	pupil_revolve[0] = mc.rename(pupil_revolve[0],prefix+'_pl01_srf')
	pupil_revolve[1] = mc.rename(pupil_revolve[1],prefix+'_pl01_rvl')
	iris_revolve[0] = mc.rename(iris_revolve[0],prefix+'_ir01_srf')
	iris_revolve[1] = mc.rename(iris_revolve[1],prefix+'_ir01_rvl')
	sclera_revolve[0] = mc.rename(sclera_revolve[0],prefix+'_sc01_srf')
	sclera_revolve[1] = mc.rename(sclera_revolve[1],prefix+'_sc01_rvl')
	# Connect Revolve Pivot
	mc.connectAttr(eye_sphere[0]+'.t',pupil_revolve[1]+'.pivot',f=1)
	mc.connectAttr(eye_sphere[0]+'.t',iris_revolve[1]+'.pivot',f=1)
	mc.connectAttr(eye_sphere[0]+'.t',sclera_revolve[1]+'.pivot',f=1)
	
	#------------------------
	# Connect Dilate Control
	
	if len(dilate_ctrl):
		
		# Verify Control
		if not mc.objExists(dilate_ctrl):
			raise UserInputError('Object ' + dilate_ctrl + ' does not exist!')
		
		# Check Attributes Exist
		if not mc.objExists(dilate_ctrl+'.iris'):
			mc.addAttr(dilate_ctrl,ln='iris',min=0,max=4,dv=1)
			mc.setAttr(dilate_ctrl+'.iris',k=1)
		if not mc.objExists(dilate_ctrl+'.pupil'):
			mc.addAttr(dilate_ctrl,ln='pupil',min=0,max=1,dv=0.5)
			mc.setAttr(dilate_ctrl+'.pupil',k=1)
		
		# Connect Attributes
		iris_md = mc.createNode('multDoubleLinear',n=prefix+'_irs01_mdl')
		pupil_md = mc.createNode('multDoubleLinear',n=prefix+'_ppl01_mdl')
		mc.connectAttr(dilate_ctrl+'.iris',iris_md+'.input1')
		mc.setAttr(iris_md+'.input2',0.25)
		mc.connectAttr(iris_md+'.output',eye_crv_detach[3]+'.parameter[1]')
		mc.connectAttr(dilate_ctrl+'.pupil',pupil_md+'.input1')
		mc.connectAttr(iris_md+'.output',pupil_md+'.input2')
		mc.connectAttr(pupil_md+'.output',eye_crv_detach[3]+'.parameter[0]')
Ejemplo n.º 27
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 = 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,
                                            pa=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, pa=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
# #############################################################################
Ejemplo n.º 29
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
Ejemplo n.º 30
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
Ejemplo n.º 31
0
def rebuild_old(surface,spansU=0,spansV=0,fullRebuildU=False,fullRebuildV=False,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 V -
	
	# Get V range
	minu = mc.getAttr(surface+'.minValueU')
	maxu = mc.getAttr(surface+'.maxValueU')
	u = minu + (maxu - minu) * 0.5
	
	# Extract isoparm curve
	iso_crv = mc.duplicateCurve(surface+'.u['+str(u)+']',ch=0,rn=0,local=0)[0]
	iso_len = mc.arclen(iso_crv)
	iso_inc = iso_len / spansV
	curveFn = glTools.utils.curve.getCurveFn(iso_crv)
	iso_list = [surface+'.v['+str(curveFn.findParamFromLength(iso_inc*i))+']' for i in range(spansV+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
		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 U -
	
	# Get V range (intermediate surface)
	minv = mc.getAttr(int_surface+'.minValueV')
	maxv = mc.getAttr(int_surface+'.maxValueV')
	v = minv + (maxv - minv) * 0.5
	
	# Extract isoparm curve (intermediate surface)
	iso_crv = mc.duplicateCurve(int_surface+'.v['+str(v)+']',ch=0,rn=0,local=0)[0]
	iso_len = mc.arclen(iso_crv)
	iso_inc = iso_len / spansU
	curveFn = glTools.utils.curve.getCurveFn(iso_crv)
	iso_list = [int_surface+'.u['+str(curveFn.findParamFromLength(iso_inc*i))+']' for i in range(spansU+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
		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]
	
	rebuild_surface = mc.rename(rebuild_surface,surface+'_rebuild')
	rebuild_surfaceShape = mc.listRelatives(surface,s=True,ni=True)[0]
	mc.delete(int_surface)
	
	# 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
Ejemplo n.º 32
0
def buildRig(surface,uValue):
	'''
	Build basic groom surface scuplting rig.
	@param surface: Surface to build joints along
	@type surface: str
	@param uValue: U isoparm to build joints along
	@type uValue: float
	'''
	# ==========
	# - Checks -
	# ==========
	
	if not glTools.utils.surface.isSurface(surface):
		raise Exception('Object "'+surface+'" is not a valid surface!')
	
	# Check Domain
	if uValue > mc.getAttr(surface+'.maxValueU'):
		raise Exception('U value "'+str(uValue)+'" is outside the parameter range!')
	if uValue < mc.getAttr(surface+'.minValueU'):
		raise Exception('U value "'+str(uValue)+'" is outside the parameter range!')
	
	# Check SkinCluster
	skinCluster = glTools.utils.skinCluster.findRelatedSkinCluster(surface)
	if skinCluster:
		raise Exception('Surface "'+skinCluster+'" is already attached to an existing skinCluster!')
	
	# Get Surface Info
	surfFn = glTools.utils.surface.getSurfaceFn(surface)
	cvs = surfFn.numCVsInU()
	
	# ================
	# - Build Joints -
	# ================
	
	# Extract IsoParm
	crv = mc.duplicateCurve(surface+'.u['+str(uValue)+']',ch=False)[0]
	
	# Get Curve Points
	pts = glTools.utils.base.getPointArray(crv)
	mc.delete(crv)
	
	# Create Joint Chain
	jnts = []
	mc.select(cl=True)
	for i in range(len(pts)):
		# Select Prev Joint
		if i: mc.select(jnts[-1])
		# Get Index String
		ind = glTools.utils.stringUtils.stringIndex(i)
		# Create Joint
		jnt = mc.joint(p=pts[i],n=surface+str(i)+'_jnt')
		# Append Return List
		jnts.append(jnt)
	for i in range(len(pts)):
		# Orient Joint
		uv = glTools.utils.surface.closestPoint(surface,pos=pts[i])
		uTangent = mc.pointOnSurface(surface,u=uv[0],v=uv[1],ntu=True)
		glTools.utils.joint.orient(jnts[i],upVec=uTangent)
	
	# ======================
	# - Create SkinCluster -
	# ======================
	
	skinCluster = mc.skinCluster(surface,jnts,tsb=True)[0]
	
	# Clear Weights
	glTools.utils.skinCluster.clearWeights(surface)
	# Set Weights
	for i in range(len(pts)):
		# Generate Weights
		wts = []
		for k in range(cvs):
			for n in range(len(pts)):
				if i == n:
					wts.append(1.0)
				else:
					wts.append(0.0)
		# Set Influence Weights
		glTools.utils.skinCluster.setInfluenceWeights(skinCluster,jnts[i],wts,normalize=False)
	
	# =================
	# - Return Result -
	# =================
	
	return jnts
Ejemplo n.º 33
0
def projectToSurface(surface,targetSurface,direction='u',keepOriginal=False,prefix=''):
	'''
	Project the edit points of the specified nurbs surface to another nurbs or polygon object
	@param surface: Surface to project
	@type surface: str
	@param targetSurface: Surface to project onto
	@type targetSurface: str
	@param direction: Surface direction to extract isoparm curves from
	@type direction: str
	@param keepOriginal: Create new surface or replace original
	@type keepOriginal: bool
	@param prefix: Name prefix for all created nodes
	@type prefix: str
	'''
	# Check surface
	if not mc.objExists(surface):
		raise UserInputError('Surface "'+surface+'" does not exist!!')
	if not isSurface(surface):
		raise UserInputError('Object "'+surface+'" is not a valid nurbs surface!!')
	
	# Check target surface
	if not mc.objExists(targetSurface):
		raise UserInputError('Target surface "'+targetSurface+'" does not exist!!')
	
	# Check prefix
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(surface)
	
	# Check direction
	direction = direction.upper()
	if (direction != 'U') and (direction != 'V'):
		raise UserInputError('Invalid surface direction specified! Must specify either "u" or "v"!!')
	
	# Get surface information
	spans = mc.getAttr(surface+'.spans'+direction)
	minVal = mc.getAttr(surface+'.minValue'+direction)
	maxVal = mc.getAttr(surface+'.maxValue'+direction)
	
	# Create main surface group
	mainGrp = mc.createNode('transform',n=prefix+'_grp')
	
	# Extract curves
	curveList = []
	curveGrpList = []
	curveLocList = []
	geomConstraintList = []
	spanInc = (maxVal - minVal)/spans
	for i in range(spans+1):
		# Curve prefix
		strInd = glTools.utils.stringUtils.stringIndex(i,2)
		crvPrefix = prefix+'_crv'+strInd
		# Create curve group
		curveGrp = crvPrefix+'_grp'
		curveGrp = mc.createNode('transform',n=curveGrp)
		curveGrp = mc.parent(curveGrp,mainGrp)[0]
		curveGrpList.append(curveGrp)
		# Get surface curve
		srfCurveName = crvPrefix+'_crv'
		srfCurve = mc.duplicateCurve(surface+'.'+direction.lower()+'['+str(i*spanInc)+']',ch=0,rn=0,local=0,n=srfCurveName)
		srfCurve = mc.parent(srfCurve[0],curveGrp)[0]
		curveList.append(srfCurve)
		# Generate curve locators
		curveLocatorList = glTools.utils.curve.locatorEpCurve(srfCurve,locatorScale=0.05,prefix=crvPrefix)
		curveLocatorList = mc.parent(curveLocatorList,curveGrp)
		curveLocList.append(curveLocatorList)
		# Create geometry constraints
		for loc in curveLocatorList:
			geomConstraint = crvPrefix+'_geometryConstraint'
			geomConstraint = mc.geometryConstraint(targetSurface,loc,n=geomConstraint)
			geomConstraintList.append(geomConstraint[0])
		# Center group pivot
		mc.xform(curveGrp,cp=True)
	
	# Delete original surface
	surfaceName = prefix+'_surface'
	if not keepOriginal:
		surfaceName = surface
		mc.delete(surface)
	
	# Loft new surface
	surfaceLoft = mc.loft(curveList,ch=1,u=1,c=0,ar=1,d=3,ss=1,rn=0,po=0,rsn=True)
	surface = mc.rename(surfaceLoft[0],surface)
	surface = mc.parent(surface,mainGrp)[0]
	mc.reorder(surface,f=True)
	loft = mc.rename(surfaceLoft[1],prefix+'_loft')
	
	# Return result
	return[surface,loft,curveList,curveGrpList,curveLocList,geomConstraintList]
Ejemplo n.º 34
0
def linearWeightsOnSurf(surf, dir, reverseInf):
    '''

    changes weights on a surfaces with 2 influences tu get a linear weighting
    
    linearWeightsOnSurf(surf,dir,reverseInf)

    surf = 'nurbsPlane1'
    dir = 'u'
    reverseInf = False
    '''

    cvPercent = []
    crvPointNum = []

    # --- get surface skinCluster and infs
    surfShape = dag.getFirstShape(surf)
    surkSKN = mc.listConnections('%s.create' % surfShape, s=True)[0]
    if mc.objectType(surkSKN) == 'skinCluster':
        surfSknInfs = mc.skinPercent(surkSKN,
                                     '%s.cv[*][*]' % surf,
                                     q=True,
                                     t=None)

        if not len(surfSknInfs) == 2:
            print 'only works with 2 influencies'

        else:
            # --- create curve from surface to get CV position percentages
            curveFromSurf = mc.duplicateCurve('%s.%s[0.5]' % (surf, dir),
                                              ch=False,
                                              o=True)[0]
            mc.rebuildCurve(curveFromSurf, ch=False, kcp=True, kr=0)
            crvSpans = mc.getAttr('%s.spans' % curveFromSurf)
            crvDeg = mc.getAttr('%s.degree' % curveFromSurf)
            crvPointNum = crvSpans + crvDeg
            # --- get cv position percentages and use it as linear skinWeights on surface
            for i in range(0, crvPointNum):
                cvPos = mc.pointPosition('%s.cv[%d]' % (curveFromSurf, i))
                param = curveLib.getClosestPointOnCurve(curveFromSurf,
                                                        cvPos,
                                                        space='world')[1]
                percent = curveLib.findPercentFromParam(curveFromSurf, param)

                if reverseInf == False:
                    if dir == 'u':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[*][%d]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[0], 1 - percent),
                                           (surfSknInfs[1], percent)
                                       ])
                    if dir == 'v':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[%d][*]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[0], 1 - percent),
                                           (surfSknInfs[1], percent)
                                       ])
                elif reverseInf == True:
                    if dir == 'u':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[*][%d]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[1], 1 - percent),
                                           (surfSknInfs[0], percent)
                                       ])
                    if dir == 'v':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[%d][*]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[1], 1 - percent),
                                           (surfSknInfs[0], percent)
                                       ])
        mc.delete(curveFromSurf)
    else:
        print 'No skinCluster on surf'
Ejemplo n.º 35
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
Ejemplo n.º 36
0
def fromCurveWeightsOnSurf(surf, dir, reverseInf, animeCurve):
    ''' 
    
    changes weights on a surfaces with 2 influences, uses an animationCurve to go from linear to custom (curve must be from 0 to 1 in every axis )
    
    fromCurveWeightsOnSurf(surf,dir,reverseInf,animeCurve)
    
    surf = 'nurbsPlane1'
    dir = 'u'
    reverseInf = False
    animeCurve = 'locator3_translateY'   
    '''

    cvPercent = []
    crvPointNum = []

    # --- get surface skinCluster and infs
    surfShape = dag.getFirstShape(surf)
    surkSKN = mc.listConnections('%s.create' % surfShape, s=True)[0]
    if mc.objectType(surkSKN) == 'skinCluster':
        surfSknInfs = mc.skinPercent(surkSKN,
                                     '%s.cv[*][*]' % surf,
                                     q=True,
                                     t=None)

        if not len(surfSknInfs) == 2:
            print 'only works with 2 influencies'

        else:
            # --- create curve from surface to get CV position percentages
            curveFromSurf = mc.duplicateCurve('%s.%s[0.5]' % (surf, dir),
                                              ch=False,
                                              o=True)[0]
            mc.rebuildCurve(curveFromSurf, ch=False, kcp=True, kr=0)
            crvSpans = mc.getAttr('%s.spans' % curveFromSurf)
            crvDeg = mc.getAttr('%s.degree' % curveFromSurf)
            crvPointNum = crvSpans + crvDeg
            # --- creates frameCacheNode for linear convert
            convertFC = mc.createNode('frameCache', n='tempConvert_fc')
            mc.connectAttr('%s.output' % animeCurve,
                           '%s.stream' % convertFC,
                           f=True)
            # --- get cv position percentages and use it as linear skinWeights on surface
            for i in range(0, crvPointNum):
                cvPos = mc.pointPosition('%s.cv[%d]' % (curveFromSurf, i))
                param = curveLib.getClosestPointOnCurve(curveFromSurf,
                                                        cvPos,
                                                        space='world')[1]
                percent = curveLib.findPercentFromParam(curveFromSurf, param)
                mc.setAttr('%s.varyTime' % convertFC, percent)
                percent = mc.getAttr('%s.varying' % convertFC)

                if reverseInf == False:
                    if dir == 'u':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[*][%d]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[0], 1 - percent),
                                           (surfSknInfs[1], percent)
                                       ])
                    if dir == 'v':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[%d][*]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[0], 1 - percent),
                                           (surfSknInfs[1], percent)
                                       ])
                elif reverseInf == True:
                    if dir == 'u':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[*][%d]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[1], 1 - percent),
                                           (surfSknInfs[0], percent)
                                       ])
                    if dir == 'v':
                        mc.skinPercent(surkSKN,
                                       '%s.cv[%d][*]' % (surf, i),
                                       transformValue=[
                                           (surfSknInfs[1], 1 - percent),
                                           (surfSknInfs[0], percent)
                                       ])
        mc.delete(curveFromSurf, convertFC)
    else:
        print 'No skinCluster on surf'
Ejemplo n.º 37
0
def rebuild_old(surface,
                spansU=0,
                spansV=0,
                fullRebuildU=False,
                fullRebuildV=False,
                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 = cmds.getAttr(surface + '.spansU')
    if not spansV: spansV = cmds.getAttr(surface + '.spansV')

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

    # Get V range
    minu = cmds.getAttr(surface + '.minValueU')
    maxu = cmds.getAttr(surface + '.maxValueU')
    u = minu + (maxu - minu) * 0.5

    # Extract isoparm curve
    iso_crv = cmds.duplicateCurve(surface + '.u[' + str(u) + ']',
                                  ch=0,
                                  rn=0,
                                  local=0)[0]
    iso_len = cmds.arclen(iso_crv)
    iso_inc = iso_len / spansV
    curveFn = glTools.utils.curve.getCurveFn(iso_crv)
    iso_list = [
        surface + '.v[' + str(curveFn.findParamFromLength(iso_inc * i)) + ']'
        for i in range(spansV + 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
        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 U -

    # Get V range (intermediate surface)
    minv = cmds.getAttr(int_surface + '.minValueV')
    maxv = cmds.getAttr(int_surface + '.maxValueV')
    v = minv + (maxv - minv) * 0.5

    # Extract isoparm curve (intermediate surface)
    iso_crv = cmds.duplicateCurve(int_surface + '.v[' + str(v) + ']',
                                  ch=0,
                                  rn=0,
                                  local=0)[0]
    iso_len = cmds.arclen(iso_crv)
    iso_inc = iso_len / spansU
    curveFn = glTools.utils.curve.getCurveFn(iso_crv)
    iso_list = [
        int_surface + '.u[' + str(curveFn.findParamFromLength(iso_inc * i)) +
        ']' for i in range(spansU + 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
        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]

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

    # 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
Ejemplo n.º 38
0
def buildRig(surface, uValue):
    '''
	Build basic groom surface scuplting rig.
	@param surface: Surface to build joints along
	@type surface: str
	@param uValue: U isoparm to build joints along
	@type uValue: float
	'''
    # ==========
    # - Checks -
    # ==========

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

    # Check Domain
    if uValue > mc.getAttr(surface + '.maxValueU'):
        raise Exception('U value "' + str(uValue) +
                        '" is outside the parameter range!')
    if uValue < mc.getAttr(surface + '.minValueU'):
        raise Exception('U value "' + str(uValue) +
                        '" is outside the parameter range!')

    # Check SkinCluster
    skinCluster = glTools.utils.skinCluster.findRelatedSkinCluster(surface)
    if skinCluster:
        raise Exception('Surface "' + skinCluster +
                        '" is already attached to an existing skinCluster!')

    # Get Surface Info
    surfFn = glTools.utils.surface.getSurfaceFn(surface)
    cvs = surfFn.numCVsInU()

    # ================
    # - Build Joints -
    # ================

    # Extract IsoParm
    crv = mc.duplicateCurve(surface + '.u[' + str(uValue) + ']', ch=False)[0]

    # Get Curve Points
    pts = glTools.utils.base.getPointArray(crv)
    mc.delete(crv)

    # Create Joint Chain
    jnts = []
    mc.select(cl=True)
    for i in range(len(pts)):
        # Select Prev Joint
        if i: mc.select(jnts[-1])
        # Get Index String
        ind = glTools.utils.stringUtils.stringIndex(i)
        # Create Joint
        jnt = mc.joint(p=pts[i], n=surface + str(i) + '_jnt')
        # Append Return List
        jnts.append(jnt)
    for i in range(len(pts)):
        # Orient Joint
        uv = glTools.utils.surface.closestPoint(surface, pos=pts[i])
        uTangent = mc.pointOnSurface(surface, u=uv[0], v=uv[1], ntu=True)
        glTools.utils.joint.orient(jnts[i], upVec=uTangent)

    # ======================
    # - Create SkinCluster -
    # ======================

    skinCluster = mc.skinCluster(surface, jnts, tsb=True)[0]

    # Clear Weights
    glTools.utils.skinCluster.clearWeights(surface)
    # Set Weights
    for i in range(len(pts)):
        # Generate Weights
        wts = []
        for k in range(cvs):
            for n in range(len(pts)):
                if i == n:
                    wts.append(1.0)
                else:
                    wts.append(0.0)
        # Set Influence Weights
        glTools.utils.skinCluster.setInfluenceWeights(skinCluster,
                                                      jnts[i],
                                                      wts,
                                                      normalize=False)

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

    return jnts
Ejemplo n.º 39
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
Ejemplo n.º 40
0
Archivo: core.py Proyecto: pecktd/pkrig
def duplicateCurve( *args , **kwargs ) :
	tmp = mc.duplicateCurve( *args , **kwargs )
	crv = Dag( tmp[0] )
	cfs = Node( tmp[1] )
	return crv , cfs
Ejemplo n.º 41
0
def create(piv=[0, 0, 0],
           axis=[0, 0, -1],
           rad=1,
           dilate_ctrl='',
           prefix='eyeball'):
    # ------------------------
    # Generate Profile Curve

    # sphere
    eye_sphere = cmds.sphere(p=piv, ax=axis, r=rad, n=prefix + '_history')
    # curve from sphere
    eye_crv = cmds.duplicateCurve(eye_sphere[0] + '.v[0]')
    eye_crv[0] = cmds.rename(eye_crv[0], prefix + '_pfl01_crv')
    # rebuild curve 0-1
    cmds.rebuildCurve(eye_crv[0], rpo=1, end=1, kcp=1, kr=0, d=3, tol=0.01)

    # ------------------------
    # Extract Curve Segments

    # detach curve
    eye_crv_detach = cmds.detachCurve(eye_crv[0] + '.u[0.125]',
                                      eye_crv[0] + '.u[0.25]',
                                      rpo=0,
                                      ch=1)
    eye_crv_detach[0] = cmds.rename(eye_crv_detach[0], prefix + '_pl01_crv')
    eye_crv_detach[1] = cmds.rename(eye_crv_detach[1], prefix + '_ir01_crv')
    eye_crv_detach[2] = cmds.rename(eye_crv_detach[2], prefix + '_sc01_crv')
    eye_crv_detach[3] = cmds.rename(eye_crv_detach[3], prefix + '_cr01_dtc')
    # rebuild curve segments
    pupil_rebuild = cmds.rebuildCurve(eye_crv_detach[0],
                                      rpo=1,
                                      end=1,
                                      kep=1,
                                      kt=1,
                                      kr=0,
                                      s=2,
                                      d=3,
                                      tol=0.01)
    iris_rebuild = cmds.rebuildCurve(eye_crv_detach[1],
                                     rpo=1,
                                     end=1,
                                     kep=1,
                                     kt=1,
                                     kr=0,
                                     s=2,
                                     d=3,
                                     tol=0.01)
    sclera_rebuild = cmds.rebuildCurve(eye_crv_detach[2],
                                       rpo=1,
                                       end=1,
                                       kep=1,
                                       kt=1,
                                       kr=0,
                                       s=4,
                                       d=3,
                                       tol=0.01)
    pupil_rebuild[1] = cmds.rename(pupil_rebuild[1], prefix + '_pl01_rbc')
    iris_rebuild[1] = cmds.rename(iris_rebuild[1], prefix + '_ir01_rbc')
    sclera_rebuild[1] = cmds.rename(sclera_rebuild[1], prefix + '_sc01_rbc')

    # ------------------------
    # Generate Eye Surfaces

    # revolve
    pupil_revolve = cmds.revolve(eye_crv_detach[0],
                                 po=0,
                                 rn=0,
                                 ut=0,
                                 tol=0.01,
                                 degree=3,
                                 s=8,
                                 ulp=1,
                                 ax=[0, 0, 1])
    iris_revolve = cmds.revolve(eye_crv_detach[1],
                                po=0,
                                rn=0,
                                ut=0,
                                tol=0.01,
                                degree=3,
                                s=8,
                                ulp=1,
                                ax=[0, 0, 1])
    sclera_revolve = cmds.revolve(eye_crv_detach[2],
                                  po=0,
                                  rn=0,
                                  ut=0,
                                  tol=0.01,
                                  degree=3,
                                  s=8,
                                  ulp=1,
                                  ax=[0, 0, 1])
    # rename surfaces
    pupil_revolve[0] = cmds.rename(pupil_revolve[0], prefix + '_pl01_srf')
    pupil_revolve[1] = cmds.rename(pupil_revolve[1], prefix + '_pl01_rvl')
    iris_revolve[0] = cmds.rename(iris_revolve[0], prefix + '_ir01_srf')
    iris_revolve[1] = cmds.rename(iris_revolve[1], prefix + '_ir01_rvl')
    sclera_revolve[0] = cmds.rename(sclera_revolve[0], prefix + '_sc01_srf')
    sclera_revolve[1] = cmds.rename(sclera_revolve[1], prefix + '_sc01_rvl')
    # Connect Revolve Pivot
    cmds.connectAttr(eye_sphere[0] + '.t', pupil_revolve[1] + '.pivot', f=1)
    cmds.connectAttr(eye_sphere[0] + '.t', iris_revolve[1] + '.pivot', f=1)
    cmds.connectAttr(eye_sphere[0] + '.t', sclera_revolve[1] + '.pivot', f=1)

    # ------------------------
    # Connect Dilate Control

    if len(dilate_ctrl):

        # Verify Control
        if not cmds.objExists(dilate_ctrl):
            raise UserInputError('Object ' + dilate_ctrl + ' does not exist!')

        # Check Attributes Exist
        if not cmds.objExists(dilate_ctrl + '.iris'):
            cmds.addAttr(dilate_ctrl, ln='iris', min=0, max=4, dv=1)
            cmds.setAttr(dilate_ctrl + '.iris', k=1)
        if not cmds.objExists(dilate_ctrl + '.pupil'):
            cmds.addAttr(dilate_ctrl, ln='pupil', min=0, max=1, dv=0.5)
            cmds.setAttr(dilate_ctrl + '.pupil', k=1)

        # Connect Attributes
        iris_md = cmds.createNode('multDoubleLinear', n=prefix + '_irs01_mdl')
        pupil_md = cmds.createNode('multDoubleLinear', n=prefix + '_ppl01_mdl')
        cmds.connectAttr(dilate_ctrl + '.iris', iris_md + '.input1')
        cmds.setAttr(iris_md + '.input2', 0.25)
        cmds.connectAttr(iris_md + '.output',
                         eye_crv_detach[3] + '.parameter[1]')
        cmds.connectAttr(dilate_ctrl + '.pupil', pupil_md + '.input1')
        cmds.connectAttr(iris_md + '.output', pupil_md + '.input2')
        cmds.connectAttr(pupil_md + '.output',
                         eye_crv_detach[3] + '.parameter[0]')
Ejemplo n.º 42
0
def ribbonize(surf_tr,
              equal=1,
              num_of_ctrls=5,
              num_of_jnts=29,
              prefix="",
              constrain=1,
              add_fk=0,
              wire=0):

    attrs = [
        ".tx", ".ty", ".tz", ".rx", ".ry", ".rz", ".sx", ".sy", ".sz", ".v"
    ]

    if prefix == "":
        mc.warning("care to name it?")
        return

    else:
        prefix = prefix + "_"

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

    surf_tr = mc.rename(surf_tr, prefix + "ribbon_surface")
    surf = mc.listRelatives(surf_tr, shapes=True)[0]

    # freeze transformations and delete the surface history
    mc.makeIdentity(surf_tr, t=True, r=True, s=True, apply=True)
    mc.delete(surf_tr, ch=True)

    # duplicate surface curves to determine the direction
    u_curve = mc.duplicateCurve(surf_tr + ".v[.5]", local=True, ch=0)
    v_curve = mc.duplicateCurve(surf_tr + ".u[.5]", local=True, ch=0)

    # delete the history just in case
    mc.delete(surf_tr, ch=True)

    u_length = mc.arclen(u_curve)
    v_length = mc.arclen(v_curve)

    if u_length < v_length:
        mc.reverseSurface(surf_tr, d=3, ch=False, rpo=True)
        mc.reverseSurface(surf_tr, d=0, ch=False, rpo=True)

    parameter = ".parameterU"
    other_param = ".parameterV"

    # correct u_curve after reversing to calculate the length
    u_curve_corr = mc.duplicateCurve(surf_tr + ".v[.5]", local=True, ch=0)[0]

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

    # selected surface is periodic or open? (cylinder or a plane)
    if mc.getAttr(surf + ".formU") == 2 or mc.getAttr(surf + ".formV") == 2:
        curve_type = "periodic"
        divider_for_ctrls = num_of_ctrls
    elif mc.getAttr(surf + ".formU") == 0 or mc.getAttr(surf + ".formV") == 0:
        curve_type = "open"
        divider_for_ctrls = num_of_ctrls - 1

    #############################################################################
    param_ctrls = param_from_length(u_curve_corr, num_of_ctrls, curve_type,
                                    "uv")
    param_joints = param_from_length(u_curve_corr, num_of_jnts, curve_type,
                                     "uv")

    length = mc.arclen(u_curve_corr)
    mc.delete(u_curve, v_curve, u_curve_corr)

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

    # create groups, main control and main control offset
    final_group = mc.group(n=prefix + "ribbon_grp", em=True)
    ctrl_joints_grp = mc.group(n=prefix + "ctrl_joints_grp", em=True)
    ctrl_grp = mc.group(n=prefix + "ctrls_grp", em=True)
    follicles_grp = mc.group(n=prefix + "follicles_grp", em=True)
    rig_grp = mc.group(n=prefix + "rig_grp", em=True)
    main_ctrl = mc.circle(n=prefix + "ctrl_main",
                          nr=(0, 1, 0),
                          r=length / 5,
                          ch=0)[0]
    main_ctrl_offset = mc.group(n=prefix + "ctrl_main_offset", em=True)

    mc.parent(main_ctrl, main_ctrl_offset)
    mc.parent(ctrl_grp, main_ctrl)
    mc.parent(main_ctrl_offset, rig_grp, final_group)
    mc.parent(surf_tr, ctrl_joints_grp, follicles_grp, rig_grp)

    # move main_ctrl_offset to the center of the surfaces bbox (in case its pivot is somewhere else)
    mid_point = get_bbox_center(surf_tr)
    for attr, mid_pnt_el in izip(attrs[:3], mid_point):
        mc.setAttr(main_ctrl_offset + attr, mid_pnt_el)

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

    fols = []
    fols_tr = []
    bind_jnts = []
    bnd_joints_rad = (length / 60) / (float(num_of_jnts) / 40)

    for x in range(num_of_jnts):

        fol = mc.createNode("follicle")
        mc.setAttr(fol + ".visibility", 0)
        temp_fol = mc.listRelatives(fol, p=True)[0]
        fols_tr.append(
            mc.rename(temp_fol, "{}follicle_{:02d}".format(prefix, x + 1)))
        fols.append(mc.listRelatives(fols_tr[-1], s=True)[0])

        # connect follicle shapes to their transforms
        mc.connectAttr(fols[-1] + ".outTranslate",
                       fols_tr[-1] + ".translate",
                       f=True)
        mc.connectAttr(fols[-1] + ".outRotate",
                       fols_tr[-1] + ".rotate",
                       f=True)

        # attach follicle shapes to the surface
        mc.connectAttr(surf + ".worldMatrix[0]",
                       fols[-1] + ".inputWorldMatrix")
        mc.connectAttr(surf + ".local", fols[-1] + ".inputSurface")

        mc.setAttr(fols[-1] + parameter, param_joints[x])
        mc.setAttr(fols[-1] + other_param, 0.5)

        mc.parent(fols_tr[-1], follicles_grp)

        # create final bind joints on the surface
        bind_jnts.append(
            mc.createNode("joint", n="{}bnd_jnt_{:02d}".format(prefix, x + 1)))

        mc.parent(bind_jnts[-1], fols_tr[-1], r=True)
        mc.setAttr(bind_jnts[-1] + ".radius", bnd_joints_rad)

    set_color(bind_jnts, "mid_blue")

    #create temp follicles for control offset groups to align
    temp_fols = []
    temp_fols_tr = []

    for x in range(num_of_ctrls):

        temp_fols.append(mc.createNode("follicle"))
        temp_fols_tr.append(mc.listRelatives(temp_fols[-1], p=True)[0])

        mc.connectAttr(temp_fols[-1] + ".outTranslate",
                       temp_fols_tr[-1] + ".translate",
                       f=True)
        mc.connectAttr(temp_fols[-1] + ".outRotate",
                       temp_fols_tr[-1] + ".rotate",
                       f=True)

        mc.connectAttr(surf + ".worldMatrix[0]",
                       temp_fols[-1] + ".inputWorldMatrix")
        mc.connectAttr(surf + ".local", temp_fols[-1] + ".inputSurface")

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

    if equal == 1:
        for x, temp_fol in enumerate(temp_fols):
            mc.setAttr(temp_fol + parameter, param_ctrls[x])
            mc.setAttr(temp_fol + other_param, 0.5)
    if equal == 0:
        v = 0
        for temp_fol in temp_fols:
            mc.setAttr(temp_fol + parameter, v)
            mc.setAttr(temp_fol + other_param, 0.5)
            v = v + (1.0 / divider_for_ctrls)

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

    #create controls and control joints
    controls = ctrl_maker(prefix,
                          ctrl_type="cube",
                          count=num_of_ctrls,
                          deg=3,
                          sp=8)

    ctrl_ofs_grps = []
    ctrl_joints = []
    ctrl_jnt_ofs_grps = []
    ctrl_joints_rad = bnd_joints_rad * 2
    ik_ctrl_scale = (length / 35) / (float(num_of_ctrls) / 5)

    for x, ctrl in enumerate(controls):

        ctrl_ofs_grp = mc.group(ctrl, n="{}_offset".format(ctrl))
        mc.delete(mc.parentConstraint(temp_fols_tr[x], ctrl_ofs_grp))
        ctrl_ofs_grps.append(ctrl_ofs_grp)

        #scale ik controls
        ctrl_shapes = mc.listRelatives(ctrl, s=True)
        for ctrl_shape in ctrl_shapes:
            ctrl_cvs_count = mc.getAttr(ctrl_shape + ".controlPoints",
                                        size=True)
            mc.scale(ik_ctrl_scale,
                     ik_ctrl_scale,
                     ik_ctrl_scale,
                     "{}.cv[0:{}]".format(ctrl_shape, ctrl_cvs_count - 1),
                     r=True,
                     ocp=True)

        #create the control joints
        ctrl_joints.append(
            mc.createNode("joint", n="{}ctrl_jnt_{:02d}".format(prefix,
                                                                x + 1)))
        #set the radius of controls joints to 2 times that of the surface joints
        mc.setAttr(ctrl_joints[x] + ".radius", ctrl_joints_rad)
        #create offset groups for ctrl joints
        ctrl_jnt_ofs_grp = mc.group(ctrl_joints[-1],
                                    n="{}_offset".format(ctrl_joints[-1]))
        mc.delete(mc.parentConstraint(temp_fols_tr[x], ctrl_jnt_ofs_grp))
        ctrl_jnt_ofs_grps.append(ctrl_jnt_ofs_grp)

    ###
    set_color(controls, "green")
    set_color(ctrl_joints, "red")

    mc.parent(ctrl_ofs_grps, ctrl_grp)
    mc.parent(ctrl_jnt_ofs_grps, ctrl_joints_grp)

    lock_hide(ctrl_ofs_grps, attrs[:9])
    lock_hide(ctrl_jnt_ofs_grps, attrs[:9])

    mc.delete(temp_fols_tr)

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

    #determine if constraint or connection method is chosen
    if constrain == 0:
        for (c, j) in izip(controls, ctrl_joints):
            for attr in attrs[:7]:  #skip scale attributes
                mc.connectAttr(c + attr, j + attr)

        mc.parentConstraint(main_ctrl, ctrl_joints_grp, mo=True)
        mc.scaleConstraint(main_ctrl, ctrl_joints_grp)

        #scale the follicles with the main control
        for flt in fols_tr:
            mc.connectAttr(main_ctrl + ".sx", flt + ".sx")
            mc.connectAttr(main_ctrl + ".sx", flt + ".sy")
            mc.connectAttr(main_ctrl + ".sx", flt + ".sz")

    elif constrain == 1:
        for (c, j) in izip(controls, ctrl_joints):
            mc.parentConstraint(c, j)
            mc.scaleConstraint(c, j)

        #scale the follicles with the main control
        for flt in fols_tr:
            mc.scaleConstraint(main_ctrl, flt)

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

    if wire == True and num_of_ctrls > 1:

        temp_crv = mc.duplicateCurve(surf_tr + ".v[.5]",
                                     n=prefix + "wire_crv",
                                     local=False,
                                     ch=0)[0]

        if num_of_ctrls == 2:
            degree = 1
        else:
            degree = 3

        wire_crv = mc.curve(p=param_from_length(
            temp_crv, num_of_ctrls + (num_of_ctrls - 1), "open", "world"),
                            d=degree)

        mc.delete(temp_crv)

        wire_crv = mc.rename(
            wire_crv, prefix + "wire_crv"
        )  # if name at the creation time, the shape doesn't get renamed
        mc.delete(wire_crv, ch=True)
        wire = mc.wire(surf_tr,
                       gw=False,
                       en=1.0,
                       ce=0.0,
                       li=0.0,
                       dds=(0, 50),
                       w=wire_crv,
                       n=prefix + "wire")[0]
        mc.connectAttr(main_ctrl + ".sx", wire + ".scale[0]")

        cps = param_from_length(wire_crv,
                                num_of_ctrls,
                                "open",
                                "uv",
                                normalized=False)

        for cp in cps:
            mc.select("{}.u[{}]".format(wire_crv, cp), r=True)
            mc.dropoffLocator(1.0, 1.0, wire)

        mc.select(cl=True)

        for x, ctrl in enumerate(controls):
            mc.connectAttr(ctrl + ".rx",
                           "{}.wireLocatorTwist[{}]".format(wire, x))

        wire_grp = mc.group(wire_crv,
                            wire_crv + "BaseWire",
                            n=prefix + "wire_crv_grp")
        mc.parent(wire_grp, rig_grp)
        lock_hide([wire_grp], attrs[:9])

        wire_skin_cluster = mc.skinCluster(ctrl_joints,
                                           wire_crv,
                                           dr=2,
                                           mi=2,
                                           bm=0)[0]

    else:
        #bind the surface to the joints
        nurbs_skin_cluster = mc.skinCluster(ctrl_joints,
                                            surf_tr,
                                            dr=2,
                                            mi=num_of_ctrls - 1,
                                            ns=num_of_ctrls * 5,
                                            bm=0,
                                            n=prefix + "skinCluster")[0]
        mc.skinPercent(nurbs_skin_cluster, surf_tr, pruneWeights=0.2)

    if wire == True and num_of_ctrls == 1:
        mc.warning("wire skipped. at least 2 controls needed")

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

    mc.setAttr(surf_tr + ".v", 0)
    mc.setAttr(rig_grp + ".v", 0)

    mc.connectAttr(main_ctrl + ".sx", main_ctrl + ".sy")
    mc.connectAttr(main_ctrl + ".sx", main_ctrl + ".sz")
    mc.aliasAttr("Scale", main_ctrl + ".sx")

    set_color(main_ctrl, "yellow")

    mc.connectAttr(main_ctrl_offset + ".sx", main_ctrl_offset + ".sy")
    mc.connectAttr(main_ctrl_offset + ".sx", main_ctrl_offset + ".sz")
    mc.aliasAttr("Scale", main_ctrl_offset + ".sx")

    #lock and hide attributes
    lock_hide([
        final_group, follicles_grp, ctrl_joints_grp, surf_tr, ctrl_grp, rig_grp
    ], attrs[:9])
    lock_hide([ctrl_grp, main_ctrl, main_ctrl_offset], attrs[7:])
    lock_hide(controls, attrs[7:])

    #clear selection
    mc.select(
        cl=True
    )  #if selection isn't cleared a control joint gets added to the bind joints set

    #create a set with bind joints
    bind_jnts_set = mc.sets(n=prefix + "bind_jnts_set")
    mc.sets(bind_jnts, add=bind_jnts_set)

    mc.select(cl=True)

    ik_ctrls_set = mc.sets(n=prefix + "ik_ctrls_set")
    mc.sets(controls, add=ik_ctrls_set)

    mc.select(cl=True)

    controls_set = mc.sets(n=prefix + "controls_set")
    mc.sets(main_ctrl, ik_ctrls_set, add=controls_set)

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

    if add_fk == 1 and mc.getAttr(surf + ".formU") != 2 and mc.getAttr(
            surf + ".formV") != 2:

        fk_ctrls, fk_ctrl_off_grps = make_fk_ctrls(prefix, num_of_ctrls)
        mc.parent(fk_ctrl_off_grps[0], ctrl_grp)

        #scale fk controls
        fk_ctrl_scale = ik_ctrl_scale * 2

        for fk_ctrl in fk_ctrls:
            fk_ctrl_shapes = mc.listRelatives(fk_ctrl, s=True)
            for fk_ctrl_shape in fk_ctrl_shapes:
                fk_ctrl_cvs_count = mc.getAttr(fk_ctrl_shape +
                                               ".controlPoints",
                                               size=True)
                mc.scale(fk_ctrl_scale,
                         fk_ctrl_scale,
                         fk_ctrl_scale,
                         "{}.cv[0:{}]".format(fk_ctrl_shape,
                                              fk_ctrl_cvs_count - 1),
                         r=True,
                         ocp=True)

        #add fk controls to a set
        mc.select(cl=True)
        fk_ctrls_set = mc.sets(n=prefix + "fk_ctrls_set")
        mc.sets(fk_ctrls, add=fk_ctrls_set)

        ########
        ik_ctrl_constr_grps = [
            mc.group(ctrl, n=ctrl + "_constr_grp") for ctrl in controls
        ]
        [
            mc.xform(ik_ctrl_constr_grp, piv=(0, 0, 0), os=True)
            for ik_ctrl_constr_grp in ik_ctrl_constr_grps
        ]

        for ik, fk in izip(controls[:-1], fk_ctrl_off_grps):
            mc.delete(mc.parentConstraint(ik, fk))

        for fk, ik in izip(fk_ctrls, ik_ctrl_constr_grps[:-1]):
            mc.parentConstraint(fk, ik)

        #constrain last ik ctrl
        mc.parentConstraint(fk_ctrls[-1], ik_ctrl_constr_grps[-1], mo=True)
        lock_hide(ik_ctrl_constr_grps, attrs[:9])

        ########
        set_color(fk_ctrls, "blue")
        lock_hide(fk_ctrl_off_grps, attrs[:9])

        mc.sets(fk_ctrls_set, add=controls_set)

        mc.select(cl=True)

    elif add_fk == 1 and (mc.getAttr(surf + ".formU") == 2
                          or mc.getAttr(surf + ".formV") == 2):

        mc.warning("surface is periodic. fk controls skipped")

    ################ADD MESSAGE ATTRS################

    mc.addAttr(main_ctrl, ln="joints", at="message")
    mc.addAttr(main_ctrl, ln="follicles", at="message")
    mc.addAttr(main_ctrl, ln="surface", at="message")

    if mc.attributeQuery("i_am_the_surface", node=surf, exists=True) == False:
        mc.addAttr(surf, ln="i_am_the_surface", at="message")

    mc.connectAttr(main_ctrl + ".surface", surf + ".i_am_the_surface")

    for j, f in izip(bind_jnts, fols):
        mc.addAttr(j, ln="i_am_a_joint", at="message")
        mc.addAttr(f, ln="i_am_a_follicle", at="message")
        mc.connectAttr(main_ctrl + ".joints", j + ".i_am_a_joint")
        mc.connectAttr(main_ctrl + ".follicles", f + ".i_am_a_follicle")