Ejemplo n.º 1
0
def evenlyDivideCurve( curve, numDiv ):
    """ Divides a curve into numDiv.
        Assumes there are two CVs at the start and end of the curve """
    # first, move the curve to the origin
    translation = mc.xform(curve, q=True, ws=True, translation=True)
    rotation = mc.xform(curve, q=True, ws=True, rotation=True)
    mc.move(0, 0, 0, curve)
    mc.rotate(0, 0, 0, curve)

    # get the curve info node
    infoNode = getCurveInfoNode(curve)
    Knots = list( mc.getAttr( infoNode+".knots" )[0] )
    CVs = mc.getAttr( curve+".cv[*]" )
    numOrigCVs = len(CVs)
    numOrigKnots = len(Knots)

    if( not numOrigCVs == 4 ):
        print("ERROR: original curve must have exactly 4 CVs")
        return
    else:
        for p in range(0,(numDiv-numOrigCVs+4+1)):
            percent = (p-1)/float(numDiv-2)
            u = findParamAtArcPercent( curve, percent )
            if p < 2 or p >= (numDiv-numOrigCVs+3):
                CVs[p] = tuple(mc.pointOnCurve(curve, parameter=u))
            else:
                CVs.insert(p, tuple(mc.pointOnCurve(curve, parameter=u)) )
                Knots.insert(p+1, u)
    curve = mc.curve( curve,r=True, p=CVs, k=Knots)

    mc.move(translation[0], translation[1], translation[2], curve)
    mc.rotate(rotation[0], rotation[1], rotation[2], curve)
    return curve
Ejemplo n.º 2
0
def addTube(selection, tubesubdivs=8):
    dt = pm.dt

    worldUp = dt.Vector([0, 1, 0])
    selShape = mc.listRelatives(selection, shapes=1, ad=1, f=1)[0]

    curveBaseNormal = mc.pointOnCurve(sel, pr=0, nn=1, top=1)
    curveBasePosition = mc.pointOnCurve(sel, pr=0, p=1, top=1)
    curveBasePosition_UpRef = mc.pointOnCurve(sel, pr=0.1, p=1, top=1)

    # creates vector datatype so we get helper functions like cross product from pymel
    base = dt.Vector(curveBasePosition)
    normal = dt.Vector(curveBaseNormal)
    up = dt.Vector(curveBasePosition_UpRef)
    up = -(up - normal).normal()
    aim = dt.cross(up, normal)

    # locators at reference frame vectors
    referenceframe = {"normal": normal, "up": up, "aim": aim}
    [pm.spaceLocator(p=base + v, n=k) for k, v in referenceframe.items()]

    # create polycylinder
    axis = referenceframe["aim"]
    subdivisionsx = tubesubdivs
    subdivisionsy = tubesubdivs
    subdivisionsz = tubesubdivs
    cylinder = mc.polyCylinder(axis=axis, radius=1, height=1, sx=subdivisionsx, sy=subdivisionsy, sz=subdivisionsz, cuv=3)
    return cylinder
Ejemplo n.º 3
0
def nurbsCurve_reverse(*args):
    '''{'path':'Surfaces/EditNURBS/nurbsCurve_reverse( )',
'icon':':/reverse.png',
'usage':"""
#先选择曲线,再选择一个物体,这个命令根据曲线和物体的远近,对这些曲线进行reverse操作
$fun( )"""
}
'''
    if len(args):
        curvesNode = args[0]
        refPos = args[1]
    else:
        curvesNode = cmds.ls(sl=True, l=True)[:-1]
        refPos = cmds.objectCenter(cmds.ls(sl=True, l=True)[-1])
    for obj in curvesNode:
        try:
            startPos = cmds.pointOnCurve(obj, pr=0, ch=False, p=True)
            endPos = cmds.pointOnCurve(obj, pr=1, ch=False, p=True)

            startLen = math.sqrt(
                math.pow(refPos[0] - startPos[0], 2) +
                math.pow(refPos[1] - startPos[1], 2) +
                math.pow(refPos[2] - startPos[2], 2))
            endLen = math.sqrt(
                math.pow(refPos[0] - endPos[0], 2) +
                math.pow(refPos[1] - endPos[1], 2) +
                math.pow(refPos[2] - endPos[2], 2))
            if startLen > endLen:
                cmds.reverseCurve(obj, ch=False, rpo=True)
                print 'Reversed %s' % obj
        except:
            print obj, " is not nurbscurve!"
Ejemplo n.º 4
0
def pointMode():
    for p in range(1, pointsNumber):
        if p == 1:
            cmds.spaceLocator(p=cmds.pointOnCurve(curve, pr=0.0, p=True),
                              n=nameBuilder_locator + str(p))
            #joint
        cmds.spaceLocator(p=cmds.pointOnCurve(curve, pr=spacing * p, p=True),
                          n=nameBuilder_locator + str(p))
Ejemplo n.º 5
0
    def createRig(self):
        # Create a Cube for test cases
        mc.polySphere(name='mySphere')
        objCenter = mc.objectCenter('mySphere', l=True)

        # Get the bounding box for the selected ojbject
        XYZ = mc.xform('mySphere', bb=True, q=True)
        rad = XYZ[3] / 2 * self.settings.radius
        strltPos = self.settings.lightPos
        lightP = 0.0

        if strltPos == "High":
            lightP = 5.0
        elif strltPos == "Low":
            lightP = -5.0
        else:
            lightP = 0.0

        # Create a circle to place three point lights
        mc.circle(n='curveLights', nr=(0, 1, 0), c=(0, 0, 0), sections=9, radius=rad)

        # Create lights in three positions on the curve
        loc = mc.pointOnCurve('curveLights', pr=0.0, p=True)
        #_item = mc.spotLight(name='FillLight', coneAngle=45)
        _item = self.createLight(self.fillLight, "FillLight")
        mc.move(loc[0], loc[1]+lightP, loc[2], _item, ls=True)

        loc = mc.pointOnCurve('curveLights', pr=3.0, p=True)
        #_item = mc.spotLight(name='KeyLight', coneAngle=45)
        _item = self.createLight(self.keyLight, "KeyLight")
        mc.move(loc[0], loc[1]+lightP, loc[2], _item, ls=True)

        loc = mc.pointOnCurve('curveLights', pr=6.0, p=True)
        #_item = mc.spotLight(name='RimLight', coneAngle=45)
        _item = self.createLight(self.rimLight, "RimLight")
        mc.move(loc[0], loc[1]+lightP, loc[2], _item, ls=True)

        # Create space locator and aimConstraints
        mc.spaceLocator(n='fillLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.aimConstraint('fillLocator', 'FillLight', aimVector=(0.0, 0.0, -1.0))
        mc.parent('fillLocator', 'curveLights', relative=True)

        mc.spaceLocator(n='keyLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.aimConstraint('keyLocator', 'KeyLight', aimVector=(0.0, 0.0, -1.0))
        mc.parent('keyLocator', 'curveLights', relative=True)

        mc.spaceLocator(n='rimLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.aimConstraint('rimLocator', 'RimLight', aimVector=(0.0, 0.0, -1.0))
        mc.parent('rimLocator', 'curveLights', relative=True)

        # Create lights main locator
        mc.spaceLocator(n='lightsMainLocator', p=(objCenter[0], objCenter[1], objCenter[2]))
        mc.parent('FillLight', 'lightsMainLocator', relative=True)
        mc.parent('KeyLight', 'lightsMainLocator', relative=True)
        mc.parent('RimLight', 'lightsMainLocator', relative=True)

        # Create Main Group for the entire light rig
        mc.group('curveLights', 'lightsMainLocator', n='LightRigGroup')
Ejemplo n.º 6
0
 def pointOnCur(self, cur1, cur2):
     inStr = raw_input()
     f = float(inStr)
     pf = 1.0 / f
     i = 0.0
     while i < 1.0:
         cur1_p = cmd.pointOnCurve(cur1, pr=i, p=1, top=1)
         cur2_p = cmd.pointOnCurve(cur2, pr=i, p=1, top=1)
         cur_p = [(x + y) / 2.0 for x, y in zip(cur1_p, cur2_p)]
         self.point.append(cur_p)
         i = i + pf
Ejemplo n.º 7
0
    def __makeMesh(self,curva):
        scale_0 = self.ui.spin_radius.value()
        scale_1 = self.ui.spin_radius_1.value()
        scale = self.ui.spin_radius.value()
        if (scale_0 >= scale_1):
            tempMaior = scale_0
            tempMenor = scale_1
        else:
            tempMaior = scale_1
            tempMenor = scale_0

        scale_extrude = tempMenor/tempMaior

        position = cmds.pointOnCurve(curva, top=True, pr=0, position=True)
        tangent  = cmds.pointOnCurve(curva, top=True, pr=0, normalizedTangent=True)
        angle    = cmds.angleBetween(er=True, v1=(0.0, 1.0, 0.0), v2=tangent)

        circle = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), degree=3, sections=16, r = 0.5)
        cmds.scale(tempMaior,
                   tempMaior,
                   tempMaior,
                   circle[0])
        cmds.move(position[0],
                  position[1],
                  position[2],
                  circle[0])
        cmds.rotate(angle[0],
                    angle[1],
                    angle[2],
                    circle[0])


        extrude = cmds.extrude(circle[0],
                                curva,
                                constructionHistory = True,
                                range = True,
                                polygon = 0,
                                extrudeType = 2,
                                useComponentPivot = 0,
                                fixedPath = 0,
                                useProfileNormal = 1,
                                rotation = 0,
                                scale = scale_extrude,
                                reverseSurfaceIfPathReversed = 1)


        poly = cmds.nurbsToPoly(extrude[0], matchNormalDir = True, constructionHistory = False, format = 2, polygonType = 1, uType = 3, uNumber = 1, vType = 3, vNumber = 3)

        cmds.delete(circle, extrude[0])
        print poly
        return poly
Ejemplo n.º 8
0
    def __braid(self):
        steps, porcent = self.__voltas()
        increment = porcent

        eight = self.__makeEight()

        list = range(int(steps))
        offset = self.ui.spin_offset.value()
        offset_normalize = offset/360.0
        self.ui.progress_Create.setRange(0,len(list))

        scale_0 = self.ui.spin_radius.value()
        scale_1 = self.ui.spin_radius_1.value()
        if (scale_0 >= scale_1):
            scale_maior = scale_0
            scale_menor = scale_1
        else:
            scale_maior = scale_1
            scale_menor = scale_0

        diference = scale_maior-scale_menor
        percent = diference/steps
        scale = scale_maior

        if (self.ui.btn_reverse.isChecked()):
            curva = self.ui.ln_path.text()
            cmds.reverseCurve(curva,ch = False, replaceOriginal = True)


        for i in list:
            self.ui.progress_Create.setValue(i)
            self.__next(porcent,eight,scale)

            porcent += increment

            _pos_A = (i*0.0625)%1.0 + offset_normalize
            _pos_B = (i*0.0625+0.333333)%1.0 + offset_normalize
            _pos_C = (i*0.0625+0.666666666)%1.0 + offset_normalize

            self.__pt_position_A.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_A, p=True ))
            self.__pt_position_B.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_B, p=True ))
            self.__pt_position_C.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_C, p=True ))
            scale -= percent


        self.ui.progress_Create.reset()
        #cmds.delete(self.__circle[0])
        # return self.__pt_position
        self.__curve()
        cmds.delete(eight[0])
Ejemplo n.º 9
0
def MakeRailPiece(curve="", height=1.0, width=1.0):
    pos = mc.pointOnCurve(curve, pr=0, top=True)
    tan = mc.pointOnCurve(curve, pr=0, t=True, top=True)
    rot = math.degrees(math.atan2(tan[0], tan[2]))
    railPiece = mc.polyPlane(w=width, h=height, sx=1, sy=1)
    mc.move(pos[0], pos[1], pos[2])
    mc.rotate(90, rot, 0)
    mc.select(railPiece[0] + '.f[0]', leftCurve[0])
    div = distSleepers * 4
    mc.polyExtrudeFacet(railPiece[0] + '.f[0]',
                        inputCurve=curve,
                        divisions=div)
    mc.delete(railPiece[0], constructionHistory=True)

    return railPiece[0]
Ejemplo n.º 10
0
def getPointOnCurveMatrix(curve, percent, tangentAxis="Y", normalAxis="Z", fakeNormal=None, invert=False):
	# get the point information
	pos = cmds.pointOnCurve(curve, ch=False, pr=percent, p=True)
	tan = cmds.pointOnCurve(curve, ch=False, pr=percent, nt=True)
	nor = cmds.pointOnCurve(curve, ch=False, pr=percent, nn=True) #not used

	# convert the point pos to internal unots
	pos[0] = units.unitsConvertUItoInternal(pos[0])
	pos[1] = units.unitsConvertUItoInternal(pos[1])
	pos[2] = units.unitsConvertUItoInternal(pos[2])

	# normalize the other vectors
	tan = mathext.normalize(tan)
	
	fakeNor = nor
	if fakeNormal is not None: fakeNor = fakeNormal

	# creating binormal and normal from 
	bin = mathext.normalize(mathext.cross(tan, fakeNor))
	nor = mathext.normalize(mathext.cross(bin, tan))	

	# creates the new matrix
	xVec = bin
	yVec = bin
	zVec = bin

	if tangentAxis == "X": xVec = tan
	elif tangentAxis == "Y": yVec = tan
	elif tangentAxis == "Z": zVec = tan

	if normalAxis == "X": xVec = nor
	elif normalAxis == "Y": yVec = nor
	elif normalAxis == "Z": zVec = nor

	mtx = [xVec[0], xVec[1], xVec[2], 0.0, yVec[0], yVec[1], yVec[2], 0.0, zVec[0], zVec[1], zVec[2], 0.0, pos[0], pos[1], pos[2], 1.0]

	if invert:
		for i in range(len(mtx)):
			mtx[i] = -mtx[i]

	# mtx = [[0 for x in range(4)] for x in range(4)]
	# mtx[0] = [bin[0], bin[1], bin[2], 0.0]
	# mtx[1] = [tan[0], tan[1], tan[2], 0.0]
	# mtx[2] = [nor[0], nor[1], nor[2], 0.0]
	# mtx[3] = [pos[0], pos[1], pos[2], 1.0]

	# return the new matrix
	return mtx
Ejemplo n.º 11
0
def joint_on_curve_parameter(curve, parameter, name):
    position = mc.pointOnCurve(curve, parameter=parameter)
    mc.select(clear=True)
    joint = mc.joint(name=name)
    mc.xform(joint, translation=position, worldSpace=True)

    return joint
 def extrude(self,caps=True):
     """ extrudes a tube along the NURBS curve """
     self.curve2 = mc.duplicate(self.origCurve, name=self.origCurve+"_copy")[0]
     # select the first CV of the path (curve)
     mc.select("%s.cv[0]"%self.curve2,replace=True)
     # figure out where to put the circle and which way to point it
     circleCenter = mc.xform(q=True,ws=True,t=True)
     circleNormal = mc.pointOnCurve(self.curve2, parameter=0, tangent=True)
     # create a circle to use for extrusion
     circle = mc.circle(radius=self.radius, center=circleCenter, normal=circleNormal)[0]
     # extrude!
     extrusion = mc.extrude( circle, self.curve2, n="nurbsTubeTrace", extrudeType=2, range=True )[0]
     self.traceBits = [extrusion, self.curve2, self.origCurve, circle]
     if caps:
         # select the first isoparm
         mc.select(extrusion+".v[%f]"%cu.findParamAtArcPercent( self.origCurve, 0.0))
         # create planar surface
         begCap = mc.planarSrf(n="cap1")[0]
         # select the last isoparm
         mc.select(extrusion+".v[%f]"%cu.findParamAtArcPercent( self.origCurve, 1.0))
         # create planar surface
         endCap = mc.planarSrf(n="cap2")[0]
         mc.setKeyframe( endCap+".visibility", t=self.timeSpan[1]-1, v=0.0 )
         mc.setKeyframe( endCap+".visibility", t=self.timeSpan[1], v=1.0 )
         # add the caps to the traceBits list
         self.traceBits.extend([begCap,endCap])
     return extrusion
Ejemplo n.º 13
0
def createAtParam(curve, param=0.0, objType='locator', name=None):
    '''
	Create an object at the specified point on a curve.
	@param curve: Input nurbs curve curve
	@type curve: str
	@param param: Curve parameter to create object at.
	@type param: str or tuple or list
	@param objType: Type of object to create and place along curve
	@type objType: str
	@param name: New object name
	@type name: str or None
	'''
    # Check Curve
    if not glTools.utils.curve.isCurve(curve):
        raise Exception('Object "' + curve + '" is not a valid nurbs curve!')

    # Check Name
    if not name:
        name = glTools.utils.stringUtils.stripSuffix(curve) + '_' + objType

    # Create Object
    obj = mc.createNode(objType)
    if not glTools.utils.transform.isTransform(obj):
        obj = mc.listRelatives(obj, p=True, pa=True)[0]
    obj = mc.rename(obj, name)

    # Position Object
    pos = mc.pointOnCurve(curve, pr=param)
    mc.xform(obj, t=pos, ws=True)

    # Return Result
    return obj
def processWebIntricacy(curvesForIntricacy):
    global nextWebId
    pointsPerCurve = webIntricacy + 1
    incriment = 1.0 / float(pointsPerCurve)
    ns = "Web" + str(nextWebId)

    length = len(curvesForIntricacy)

    cmds.select(curvesForIntricacy, r=True)
    webCurves = determineSelectedCurves()
    ''' loop through each web marked for extra intricacy and make list of points along those curves '''
    pointList = []

    for web in webCurves:
        distanceAlongLine = 0
        for i in range(0, pointsPerCurve):
            randomScaler = randomizeMe(2.5, 0.2, False)
            pointOnLine = cmds.pointOnCurve(web,
                                            top=True,
                                            pr=distanceAlongLine *
                                            randomScaler,
                                            p=True)
            ''' ignore first point because it is on the geometry, otherwise append the points from this curve to the pointList '''
            if (i != 0):
                pointList.append(pointOnLine)

            distanceAlongLine = distanceAlongLine + incriment
        cmds.rename(web, ns)
    ''' match points with their closest neighbor to create start/end points '''
    pairs = matchIntricacyPoints(pointList)
    return pairs
	def buildNurbsRibbon(self):
		if self.guideSpline:
			guideDeg = cmds.getAttr(self.guideSpline + '.degree' )
			guideSpan = cmds.getAttr(self.guideSpline + '.spans' )
			oneCurvePoints = []
			otherCurvePoints = []
			for i in xrange(guideDeg + guideSpan):
				cvPos = cmds.pointPosition(self.guideSpline + '.cv[' + str(i) + "]", w=True )
				newPara = cmds.closestPointOnCurve(self.guideSpline, ip=cvPos, paramU=True)  #Find the parameter Value
				newParaVal = cmds.getAttr(newPara + ".paramU")
				cmds.delete(newPara)
				infoNode = cmds.pointOnCurve(self.guideSpline, ch=True, pr=newParaVal)  #Now find the Position and tangent!
				posy = (cmds.getAttr(infoNode + ".position"))[0]  # returns the position
				posy = MVector(posy[0],posy[1],posy[2])
				normy = (cmds.getAttr(infoNode + ".tangent"))[0]
				normy = MVector(normy[0],normy[1],normy[2]) #Use MVector from maya.openMaya
				normy = normy.normal()
				vertVect = MVector(0,1,0)
				sideMove = normy^vertVect #This is the notation for a cross product. Pretty cool. Should be a normal movement
				sideMove = sideMove.normal() * 0.5
				sideMovePos = posy + sideMove 
				otherSideMovePos = posy - sideMove
				oneCurvePoints.append([sideMovePos[0],sideMovePos[1],sideMovePos[2]])
				otherCurvePoints.append([otherSideMovePos[0],otherSideMovePos[1],otherSideMovePos[2]])

			oneSideCurve = cmds.curve(editPoint = oneCurvePoints, degree=3)
			OtherSideCurve = cmds.curve(editPoint = otherCurvePoints, degree=3)
			self.tempConstructionParts.append(oneSideCurve)
			self.tempConstructionParts.append(OtherSideCurve)
			#Now we loft the surface between the two Curves!
			nameStart = nameBase(self.totalMarkerList[0].getName(), self.searchString, "loc", "nbs")
			nameStart += "ribbonSurface"
			self.guideNurbsRibbon = cmds.loft(oneSideCurve, OtherSideCurve, name = nameStart, constructionHistory = True, uniform = True, close = False, autoReverse = True, degree = 3, sectionSpans = 1, range = False, polygon = 0, reverseSurfaceNormals = True)
			self.guideNurbsRibbon = self.guideNurbsRibbon[0]
			self.ribbonParts.append(self.guideNurbsRibbon)
Ejemplo n.º 16
0
def oscillateCurve( curve, start=0.0, end=1.0, freq=1.0, ease=0.5, strength=1.0 ):
    """ Oscillates a given curve by moving each vertex in an alternating
        direction based on the normal.  This process takes place over the
        range defined by "start" and "end" as percentages of arc length.
        Oscillation eases to full strength as determined by the "ease" and
        "strength" arguments. """
    if(ease > (end-start)*0.5):
        ease = (end-start)*0.5
    if(start < end):
        CVs = mc.getAttr( curve+".cv[*]" )
        newCVs = findCVsInRange(curve, start, end)
        for (I,U,L) in newCVs:
            interp = (L-start)/(end-start)
            osc = sin(freq*interp)
            scale = pulse(start+ease, end, ease, L)  # ease must be between 0 and 0.5
## Don't use Maya's normalized normal -- it flip flops with curvature so it's not good for oscillating offset
#            normal = Vector(mc.pointOnCurve(curve, parameter=cv[1], normalizedNormal=True))
#            if(normal.mag() == 0.0):
#                print "Getting normal from up x tangent"
            normal = Vector(0,1,0)**Vector(mc.pointOnCurve(curve, parameter=U, tangent=True))
            normal = normal.norm()
            pos = Vector(CVs[I])
            pos = pos+normal*scale*strength*osc
            CVs[I] = pos.asTuple()

    for i,cv in enumerate(CVs):
        mc.setAttr(curve+".cv[%d]"%i, cv[0], cv[1], cv[2])

    return curve
Ejemplo n.º 17
0
def createAtParam(	curve,
					param	= 0.0,
					objType	= 'locator',
					name	= None	):
	'''
	Create an object at the specified point on a curve.
	@param curve: Input nurbs curve curve
	@type curve: str
	@param param: Curve parameter to create object at.
	@type param: str or tuple or list
	@param objType: Type of object to create and place along curve
	@type objType: str
	@param name: New object name
	@type name: str or None
	'''
	# Check Curve
	if not glTools.utils.curve.isCurve(curve):
		raise Exception('Object "'+curve+'" is not a valid nurbs curve!')
	
	# Check Name
	if not name: name = glTools.utils.stringUtils.stripSuffix(curve)+'_'+objType
	
	# Create Object
	obj = mc.createNode(objType)
	if not glTools.utils.transform.isTransform(obj):
		obj = mc.listRelatives(obj,p=True,pa=True)[0]
	obj = mc.rename(obj,name)
	
	# Position Object
	pos = mc.pointOnCurve(curve,pr=param)
	mc.xform(obj,t=pos,ws=True)
	
	# Return Result
	return obj
Ejemplo n.º 18
0
    def _build_fk_chain(self):
        """
        Based on defined parameter list, creates joint chain using a curve for position.
        :return:
        """
        for n, parameter in enumerate(self.parameter_list):
            position = mc.pointOnCurve(self.curve, parameter=parameter)
            mc.select(clear=True)
            joint = mc.joint(radius=self.joint_radius,
                             name=self.tp_name.build(name=self.module_name,
                                                     side=self.module_side,
                                                     index=n + 1,
                                                     node_type='joint'))
            mc.xform(joint, translation=position, worldSpace=True)
            self.fk_joint_list.append(joint)

        tpu.parent_in_list_order(self.fk_joint_list)

        # orient joints
        for joint in self.fk_joint_list:
            mc.joint(joint,
                     edit=True,
                     orientJoint="xyz",
                     secondaryAxisOrient="yup",
                     children=True,
                     zeroScaleOrient=True)

        self.module_group_dict['joint'].append(self.fk_joint_list[0])
Ejemplo n.º 19
0
    def buildNurbsRibbon(self):
        if self.guideSpline:
            guideDeg = cmds.getAttr(self.guideSpline + '.degree')
            guideSpan = cmds.getAttr(self.guideSpline + '.spans')
            oneCurvePoints = []
            otherCurvePoints = []
            for i in xrange(guideDeg + guideSpan):
                cvPos = cmds.pointPosition(self.guideSpline + '.cv[' + str(i) +
                                           "]",
                                           w=True)
                newPara = cmds.closestPointOnCurve(
                    self.guideSpline, ip=cvPos,
                    paramU=True)  #Find the parameter Value
                newParaVal = cmds.getAttr(newPara + ".paramU")
                cmds.delete(newPara)
                infoNode = cmds.pointOnCurve(
                    self.guideSpline, ch=True,
                    pr=newParaVal)  #Now find the Position and tangent!
                posy = (cmds.getAttr(infoNode +
                                     ".position"))[0]  # returns the position
                posy = MVector(posy[0], posy[1], posy[2])
                normy = (cmds.getAttr(infoNode + ".tangent"))[0]
                normy = MVector(normy[0], normy[1],
                                normy[2])  #Use MVector from maya.openMaya
                normy = normy.normal()
                vertVect = MVector(0, 1, 0)
                sideMove = normy ^ vertVect  #This is the notation for a cross product. Pretty cool. Should be a normal movement
                sideMove = sideMove.normal() * 0.5
                sideMovePos = posy + sideMove
                otherSideMovePos = posy - sideMove
                oneCurvePoints.append(
                    [sideMovePos[0], sideMovePos[1], sideMovePos[2]])
                otherCurvePoints.append([
                    otherSideMovePos[0], otherSideMovePos[1],
                    otherSideMovePos[2]
                ])

            oneSideCurve = cmds.curve(editPoint=oneCurvePoints, degree=3)
            OtherSideCurve = cmds.curve(editPoint=otherCurvePoints, degree=3)
            self.tempConstructionParts.append(oneSideCurve)
            self.tempConstructionParts.append(OtherSideCurve)
            #Now we loft the surface between the two Curves!
            nameStart = nameBase(self.totalMarkerList[0].getName(),
                                 self.searchString, "loc", "nbs")
            nameStart += "ribbonSurface"
            self.guideNurbsRibbon = cmds.loft(oneSideCurve,
                                              OtherSideCurve,
                                              name=nameStart,
                                              constructionHistory=True,
                                              uniform=True,
                                              close=False,
                                              autoReverse=True,
                                              degree=3,
                                              sectionSpans=1,
                                              range=False,
                                              polygon=0,
                                              reverseSurfaceNormals=True)
            self.guideNurbsRibbon = self.guideNurbsRibbon[0]
            self.ribbonParts.append(self.guideNurbsRibbon)
Ejemplo n.º 20
0
def create(curve,objType,objCount=0,parent=False,useDistance=False,minPercent=0.0,maxPercent=1.0,prefix='',suffix=''):
	'''
	Create objects along a curve
	@param curve: Input nurbs curve curve
	@type curve: str
	@param objType: Type of objects to create and place along curve
	@type objType: str
	@param objCount: Number of objects to create along curve. If objCount=0, number of edit points will be used.
	@type objCount: int
	@param parent: Parent each new object to the previously created object. eg. Joint chain
	@type parent: bool
	@param useDistance: Use distance along curve instead of parametric length for sample distribution
	@type useDistance: bool
	@param minPercent: Percent along the curve to start placing objects
	@type minPercent: float
	@param maxPercent: Percent along the curve to stop placing objects
	@type maxPercent: float
	@param prefix: Name prefix for builder created nodes. If left at default ("") prefix will be derived from curve name.
	@type prefix: str
	'''
	
	# Check Path
	if not glTools.utils.curve.isCurve(curve):
		raise Exception('Object "'+curve+'" is not a valid nurbs curve!')
	
	# Check prefix
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(curve)
	# Check suffix
	if not suffix: suffix = objType
	
	# Check object count
	if not objCount: objCount = mc.getAttr(curve+'.spans') + 1
	
	# Get curve sample points
	paramList = glTools.utils.curve.sampleParam(curve,objCount,useDistance,minPercent,maxPercent)
	
	# Create object along curve
	objList = []
	for i in range(objCount):
		
		# Create object
		obj = mc.createNode(objType)
		if not glTools.utils.transform.isTransform(obj):
			obj = mc.listRelatives(obj,p=True,pa=True)[0]
		ind = glTools.utils.stringUtils.stringIndex(i+1)
		obj = mc.rename(obj,prefix+ind+'_'+suffix)
		
		# Position object
		pos = mc.pointOnCurve(curve,pr=paramList[i])
		mc.xform(obj,t=pos,ws=True)
		
		# Parent
		if parent and i: obj = mc.parent(obj,objList[-1])[0]
		
		# Append result
		objList.append(str(obj))
	
	# Return result
	return objList
Ejemplo n.º 21
0
def expression():
    grps = cmds.listRelatives(root,
                              children=True,
                              type='transform',
                              fullPath=True)
    random.seed(cmds.currentTime(q=True))
    length = cmds.getAttr(root + '.length')
    for g in grps:
        #print(g)
        children = cmds.listRelatives(g,
                                      children=True,
                                      type='transform',
                                      fullPath=True)
        lightning = None
        for c in children:
            if cmds.attributeQuery('isLightning', n=c, ex=True):
                lightning = c
        if not lightning:
            print('lightning not found for %s. something is wrong' % g)
            continue
        #print(lightning)
        lifespan = cmds.getAttr(lightning + '.lifespan')
        age = cmds.getAttr(lightning + '.age')
        lsrc = cmds.listConnections(g + '.srcLocator')
        ldst = cmds.listConnections(g + '.dstLocator')
        if age >= lifespan:
            lifespan = random.uniform(0, 3)
            age = 0
            #print(lsrc,ldst)
            rpos = random.uniform(0.0, 1.0)
            curve = cmds.listConnections(lightning + '.curve')[0]
            maxVal = cmds.getAttr(curve + '.maxValue')
            spos = cmds.pointOnCurve(curve, pr=rpos * maxVal, p=True)
            rlen = random.uniform(0.0, length)
            drpos = rpos * maxVal + rlen
            if drpos > maxVal:
                drpos = maxVal
            dpos = cmds.pointOnCurve(curve, pr=drpos, p=True)
            cmds.xform(lsrc, translation=spos)
            cmds.xform(ldst, translation=dpos)
        else:
            age += 1
            cmds.xform(lsrc, r=True, translation=[0.001, 0.001, 0.001])
            cmds.xform(ldst, r=True, translation=[0.001, 0.001, 0.001])
        cmds.setAttr(lightning + '.age', age)
        cmds.setAttr(lightning + '.lifespan', lifespan)
Ejemplo n.º 22
0
def getPosCurvePoint(curve, pCurve):
    """Get the position of a point on the curve
    
    pCurve is the parameter of the curve
    """
    infoNode = cmds.pointOnCurve(curve, ch=True, pr=pCurve)
    pPos = np.array(cmds.getAttr(infoNode + ".position")[0])  # returns the position    
    return pPos
Ejemplo n.º 23
0
def getAngleCurvePoint(curve, pCurve):
    """Get the tangent angle of a point on the curve
        
    pCurve is the parameter of the curve
    """    
    infoNode = cmds.pointOnCurve(curve, ch=True, pr=pCurve)
    tang = list(cmds.getAttr(infoNode + ".normalizedTangent")[0])  # returns the tangent vector
    xzAngle = getAngle(tang)
    return xzAngle 
Ejemplo n.º 24
0
    def __next(self, porcentagem, circle):
        position = cmds.pointOnCurve(self.ui.ln_path.text(),
                                     top=True,
                                     pr=porcentagem,
                                     position=True)
        tangent = cmds.pointOnCurve(self.ui.ln_path.text(),
                                    top=True,
                                    pr=porcentagem,
                                    tangent=True)
        angle = cmds.angleBetween(er=True, v1=(0.0, 1.0, 0.0), v2=tangent)

        cmds.scale((self.ui.spin_radius.value() * random.uniform(
            (1 - self.ui.spin_random.value()), 1.0)),
                   (self.ui.spin_radius.value() * random.uniform(
                       (1 - self.ui.spin_random.value()), 1.0)),
                   (self.ui.spin_radius.value() * random.uniform(
                       (1 - self.ui.spin_random.value()), 1.0)), circle[0])
        cmds.move(position[0], position[1], position[2], circle[0])
        cmds.rotate(angle[0], angle[1], angle[2], circle[0])
Ejemplo n.º 25
0
def getTanCurvePoint(curve, pCurve):
    """Get the noramlised tangent vector of a point on the curve
        
    pCurve is the parameter of the curve
    """    
    # infoNode = cmds.pointOnCurve(curve, ch=True, pr=pCurve, nt=True)
    # tan = list(cmds.getAttr(infoNode + ".normalizedTangent")[0])  # returns the tangent vector    
    tan = np.array(cmds.pointOnCurve(curve, pr=pCurve, nt=True))
    ntan = np.linalg.norm(tan)
    return tan/ntan
Ejemplo n.º 26
0
 def ok(self, obj, *args):
     n = cmds.intSlider(obj, value=True, query=True)  #Query slider
     z = cmds.ls(selection=True)  #Line Selection
     for i in range(0, n):  #From i to N
         x = cmds.pointOnCurve(z,
                               pr=float(i) / float(n),
                               turnOnPercentage=True)
         y = cmds.duplicate(self.f)  #place Group
         cmds.move(x[0], x[1], x[2], y[0],
                   absolute=True)  #Move Group to point
Ejemplo n.º 27
0
def orientToCurve(curve,
                  obj,
                  uValue=0.0,
                  useClosestPoint=False,
                  upVector=(0, 1, 0),
                  tangentAxis='x',
                  upAxis='y'):
    '''
	Orient object to a specified point on a curve.
	@param curve: Curve to orient object to
	@type curve: str
	@param obj: Object to orient
	@type obj: str
	@param uValue: Paramater value of the curve to orient to
	@type uValue: float
	@param useClosestPoint: Use the closest point on the curve instead of the specified uv parameter
	@type useClosestPoint: bool
	@param upVector: upVector needed to calculate rotation matrix
	@type upVector: tuple
	@param tangentAxis: Basis axis that will be derived from the tangent of the curve point
	@type tangentAxis: str
	@param upAxis: Basis axis that will be derived from the upVector
	@type upAxis: str
	'''
    # Check curve
    if not isCurve(curve):
        raise Exception('Object ' + curve + ' is not a valid curve!!')
    # Check uValue
    minu = mc.getAttr(curve + '.minValue')
    maxu = mc.getAttr(curve + '.maxValue')
    # Closest Point
    if useClosestPoint:
        pos = mc.xform(obj, q=True, ws=True, rp=True)
        uValue = closestPoint(curve, pos)
    # Verify surface parameter
    if uValue < minu or uValue > maxu:
        raise Exception('U paramater ' + str(uValue) +
                        ' is not within the parameter range for ' + curve +
                        '!!')

    # Check object
    if not mc.objExists(obj):
        raise Exception('Object ' + obj + ' does not exist!!')
    rotateOrder = mc.getAttr(obj + '.ro')

    # Get tangent at curve point
    tan = mc.pointOnCurve(curve, pr=uValue, nt=True)

    # Build rotation matrix
    mat = glTools.utils.matrix.buildRotation(tan, upVector, tangentAxis,
                                             upAxis)
    rot = glTools.utils.matrix.getRotation(mat, rotateOrder)

    # Orient object to curve
    mc.rotate(rot[0], rot[1], rot[2], obj, a=True, ws=True)
Ejemplo n.º 28
0
def getCurvatureCurvePoint(curve, pCurve):
    """Get the curvature of a point on the curve
        
    pCurve is the parameter of the curve
    """       
    infoNode = cmds.pointOnCurve(curve, ch=True, pr=pCurve)
    radius = np.array(cmds.getAttr(infoNode + ".curvatureRadius"))  # returns the curvature 
    if radius == 0:
        return 0
    else:
        return 1/radius
Ejemplo n.º 29
0
    def __next(self, porcentagem,eight,scale):
        #print porcentagem
        curva = self.ui.ln_path.text()

        position = cmds.pointOnCurve(curva, top=True, pr=porcentagem, position=True)
        tangent  = cmds.pointOnCurve(curva, top=True, pr=porcentagem, tangent=True)
        angle    = cmds.angleBetween(er=True, v1=(0.0, 1.0, 0.0), v2=tangent)

        cmds.scale((scale * random.uniform((1-self.ui.spin_random.value()), 1.0)),
                   (scale * random.uniform((1-self.ui.spin_random.value()), 1.0)),
                   (scale * random.uniform((1-self.ui.spin_random.value()), 1.0)),
                   eight[0])
        cmds.move(position[0],
                  position[1],
                  position[2],
                  eight[0])
        cmds.rotate(angle[0],
                    angle[1],
                    angle[2],
                    eight[0])
Ejemplo n.º 30
0
def duplicateAlongCurve(density):
    selection = cmds.ls(sl=True)
    if len(selection)!=2:
        print("Please select the object, then the curve")
        return
    obj=selection[0]
    myCurve=selection[1]
    #print selection[0]
    infoNode = cmds.pointOnCurve(myCurve, ch=True, pr=0.0)
    #pos = cmds.getAttr(infoNode + ".position")
    #cmds.move(pos[0][0], pos[0][1], pos[0][2], 'pPlane1', absolute=True)
    cmds.connectAttr( infoNode+'.position', 'pPlane1.translate')
    step = 0.1
    min = cmds.getAttr(myCurve+'.minValue')
    max = cmds.getAttr(myCurve+'.maxValue')
    for i in fRange(min+step, max, density):
        cmds.select(obj)
        infoNode = cmds.pointOnCurve(myCurve, ch=True, pr=i)
        dup = cmds.duplicate();
        cmds.connectAttr( infoNode+'.position', dup[0]+'.translate')
Ejemplo n.º 31
0
def polyAttach(sel):
    edgeInfo=mc.polyInfo(sel,ve=1)[0]
    edge=sel.split('.')[0]+'.e[%s]'%(edgeInfo.split()[3])
    parameter=2
    if sel.find(mc.polyInfo(edge,ev=1)[0].split()[2])!=-1:
        parameter=1
    curveInfo=mc.pointOnCurve(edge,ch=1,pr=parameter,p=1)
    attachLoc=mc.spaceLocator(n=sel.split('.')[0]+'_Loc#')[0]
    mc.connectAttr(curveInfo+'.position',attachLoc+'.t')
    normalCstrt=mc.normalConstraint(sel.split('.')[0],attachLoc,weight=1,aimVector=[0,0,1],upVector=[1,0,0],worldUpType='vector',worldUpVector=[1,0,0])[0]
    mc.connectAttr(curveInfo+'.tangent',normalCstrt+'.worldUpVector')
    return attachLoc
Ejemplo n.º 32
0
 def creatPointOnCurve(self, curve, nodeName):
     print "im in  creatPointOnCurve"
     cmds.undoInfo(openChunk=True)
     print "poc"
     try:
         poc = cmds.pointOnCurve(curve, ch=True)
         poc = cmds.rename(poc, nodeName)
         cmds.setAttr(poc + ".turnOnPercentage", 1)
         print poc
         return poc
     except Exception as e:
         print 'creatPointOnCurve something wrong...'
         cmds.undoInfo(closeChunk=True)
Ejemplo n.º 33
0
def fromRefCurve(curve,refCurve,rebuildToRef=True):
	'''
	'''
	# Get start and end reference points
	stRef = mc.pointOnCurve(refCurve,top=True,pr=0.0,p=True)
	enRef = mc.pointOnCurve(refCurve,top=True,pr=1.0,p=True)
	
	# Get boundary parameters
	stParam = glTools.utils.curve.closestPoint(curve,stRef)
	enParam = glTools.utils.curve.closestPoint(curve,enRef)
	
	# SubCurve
	subCurve = mc.detachCurve(curve,p=[stParam,enParam],replaceOriginal=False,ch=False)
	mc.delete(subCurve[0],subCurve[2])
	subCurve = mc.rename(subCurve[1],curve+'_subCurve')
	
	if rebuildToRef:
		degree = mc.getAttr(refCurve+'.degree')
		spans = mc.getAttr(refCurve+'.spans')
		mc.rebuildCurve(subCurve,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=0,kep=1,kt=0,s=spans,d=degree,tol=0)
	
	# Return result
	return subCurve
Ejemplo n.º 34
0
def getPercentOfCurvePoint(curve, curvePoint, curveSteps=1000, tolerance=0.01):
	percentage = None
	
	for i in range(curveSteps + 1):
		currPercent = (1.0/curveSteps)*i
		currPoint = cmds.pointOnCurve(curve, ch=False, pr=currPercent, p=True)

		dist = abs(sqrt((curvePoint[0]-currPoint[0])^2 + (curvePoint[1]-currPoint[1])^2 + (curvePoint[2]-currPoint[2])^2))

		if dist <= tolerance:
			percentage = currPercent
			break

	return percentage
Ejemplo n.º 35
0
def fromRefCurve(curve, refCurve, rebuildToRef=True):
    """
    """
    # Get start and end reference points
    stRef = cmds.pointOnCurve(refCurve, top=True, pr=0.0, p=True)
    enRef = cmds.pointOnCurve(refCurve, top=True, pr=1.0, p=True)

    # Get boundary parameters
    stParam = glTools.utils.curve.closestPoint(curve, stRef)
    enParam = glTools.utils.curve.closestPoint(curve, enRef)

    # SubCurve
    subCurve = cmds.detachCurve(curve,
                                p=[stParam, enParam],
                                replaceOriginal=False,
                                ch=False)
    cmds.delete(subCurve[0], subCurve[2])
    subCurve = cmds.rename(subCurve[1], curve + '_subCurve')

    if rebuildToRef:
        degree = cmds.getAttr(refCurve + '.degree')
        spans = cmds.getAttr(refCurve + '.spans')
        cmds.rebuildCurve(subCurve,
                          ch=0,
                          rpo=1,
                          rt=0,
                          end=1,
                          kr=0,
                          kcp=0,
                          kep=1,
                          kt=0,
                          s=spans,
                          d=degree,
                          tol=0)

    # Return result
    return subCurve
Ejemplo n.º 36
0
def eqDistanceCurveDivide(curvename, segmentcurveLength):
    uValeStart = 0.0

    curveLength = mc.arclen(curvename)
    kk = (int(curveLength / segmentcurveLength))

    intCL = int(curveLength)
    accur = 100 * intCL

    uVale = 1.0 / accur

    for t in range(kk):
        for i in range(accur):

            pointA = mc.pointOnCurve(curvename,
                                     top=True,
                                     pr=uValeStart,
                                     p=True)
            vecA = om.MVector(pointA[0], pointA[1], pointA[2])
            pointB = mc.pointOnCurve(curvename, top=True, pr=uVale, p=True)
            vecB = om.MVector(pointB[0], pointB[1], pointB[2])

            vecC = om.MVector()
            vecC = (vecB - vecA)
            distance = vecC.length()

            if distance < segmentcurveLength:
                uVale += 1.0 / accur
            else:
                uValeStart = uVale
                break

        mc.spaceLocator(p=(pointB[0], pointB[1], pointB[2]))

        if uValeStart >= 0.99:
            break
Ejemplo n.º 37
0
def movePivot(side, *args):

    check = False
    sel = cmds.ls(sl=True, exactType="transform")

    if sel:
        for x in sel:
            check = curveCheck(x)
            if check:
                # get curve info
                pos = cmds.pointOnCurve(x, parameter=side, position=True)
                cmds.xform(x, ws=True, rp=pos)
            else:
                cmds.warning(
                    "{} is not a nurbsCurve object. Skipping!".format(x))
Ejemplo n.º 38
0
def getNormalizedTangent(crv):
    """
	gets normalized tan of selected cv
	"""

    cvs = cmds.ls("{0}.cv[*]".format(crv), fl=True)
    denom = len(cvs)

    sel = cmds.ls(sl=True, fl=True)[0]

    num = float(sel.partition("[")[2].rpartition("]")[0])

    pr = num / denom

    tan = cmds.pointOnCurve(crv, pr=pr, nt=True)

    return tan
Ejemplo n.º 39
0
def getNormalizedTangent(pt = ""):
    """
    gets normalized tan of selected (or given) list of cvs
    """

    if cmds.objectType(pt) != "nurbsCurve":
        return

    crv = pt.partition(".")[0]
    print pt, crv
    cvs = cmds.ls("{0}.cv[*]".format(crv), fl=True)
    denom = len(cvs)
    num = float(pt.partition("[")[2].rpartition("]")[0])
    pr = num/denom
    tan = cmds.pointOnCurve(crv, pr=pr, nt=True)

    return(tan)
Ejemplo n.º 40
0
def curve_to_joint(spans, *args):
    '''main function to create joint chain from NurbsCurve'''
    try:
        objlist = cmds.ls(sl=True)
        curve = objlist[0]
        #cmds.objectType(curve, isType='nurbsCurve')):
        d_curve = cmds.duplicate()
        if not isinstance(spans, int):
            spans = int(cmds.intField(spans, q=True, v=True))
        print "span is " + str(spans)
        cmds.rebuildCurve(d_curve, rt=0, kr=2, s=spans - 1)
        for i in range(spans):
            position = cmds.pointOnCurve(d_curve, pr=i, p=True)
            cmds.joint(p=position)
        cmds.delete(d_curve)
    except:
        print "No curve Selected"
Ejemplo n.º 41
0
def getCHNormAtT(chI, chJ, tparam):
  global csNum
  global cs
  global chNum
  global ch

  origN =  ch[chI][chJ].nor
  origT1 = ch[chI][chJ].tan
  origT2 = ch[chJ][chI].tan
  targetT = cmds.pointOnCurve(cs[chI].name, pr=tparam, nt=True)   # z comp incorrect
  targetT[2] = -(origT2[0]*targetT[0]+origT2[1]*targetT[1])/origT2[2]   # solve t_z, t2 dot t = 0
    
  crossProd = np.cross(origT1, targetT)
  axis = normalize(crossProd)
  angle = np.arcsin( np.linalg.norm(crossProd) / (np.linalg.norm(origT1)*np.linalg.norm(targetT)) )
  rot = rotation(angle,axis)
  
  return normalize(np.dot(rot, origN))
Ejemplo n.º 42
0
def orientToCurve(curve,obj,uValue=0.0,useClosestPoint=False,upVector=(0,1,0),tangentAxis='x',upAxis='y'):
	'''
	Orient object to a specified point on a curve.
	@param curve: Curve to orient object to
	@type curve: str
	@param obj: Object to orient
	@type obj: str
	@param uValue: Paramater value of the curve to orient to
	@type uValue: float
	@param useClosestPoint: Use the closest point on the curve instead of the specified uv parameter
	@type useClosestPoint: bool
	@param upVector: upVector needed to calculate rotation matrix
	@type upVector: tuple
	@param tangentAxis: Basis axis that will be derived from the tangent of the curve point
	@type tangentAxis: str
	@param upAxis: Basis axis that will be derived from the upVector
	@type upAxis: str
	'''
	# Check curve
	if not isCurve(curve): raise Exception('Object '+curve+' is not a valid curve!!')
	# Check uValue
	minu = mc.getAttr(curve+'.minValue')
	maxu = mc.getAttr(curve+'.maxValue')
	# Closest Point
	if useClosestPoint:
		pos = mc.xform(obj,q=True,ws=True,rp=True)
		uValue = closestPoint(curve,pos)
	# Verify surface parameter
	if uValue < minu or uValue > maxu:
		raise Exception('U paramater '+str(uValue)+' is not within the parameter range for '+curve+'!!')
	
	# Check object
	if not mc.objExists(obj): raise Exception('Object '+obj+' does not exist!!')
	rotateOrder = mc.getAttr(obj+'.ro')
	
	# Get tangent at curve point
	tan = mc.pointOnCurve(curve,pr=uValue,nt=True)
	
	# Build rotation matrix
	mat = glTools.utils.matrix.buildRotation(tan,upVector,tangentAxis,upAxis)
	rot = glTools.utils.matrix.getRotation(mat,rotateOrder)
	
	# Orient object to curve
	mc.rotate(rot[0],rot[1],rot[2],obj,a=True,ws=True)
Ejemplo n.º 43
0
def move_pivot(end, *args):
    """

    Args:
        end (int): parameter value (0 or 1 from buttons) the point on curve will return, start or end
        *args:
    """

    check = False	
    sel = cmds.ls(sl=True, exactType = "transform")

    if sel:
        for x in sel:
            check = rig.isType(x, "nurbsCurve")
            if check:
                # get curve info
                pos = cmds.pointOnCurve(x, parameter = end, position = True)
                cmds.xform(x, ws=True, piv=pos)
            else:
                cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))
Ejemplo n.º 44
0
def AlignVer(verts, crv, axes=[False, False, False]):
    numPositions = len(verts) - 1
    for i in range(len(verts)):
        #top=turnOnPercentage
        coord = cmds.pointOnCurve(crv,
                                  top=True,
                                  pr=float(i) / float(numPositions))

        print(coord[1])
        print(cmds.pointPosition(verts[i], w=True))
        cmds.move(coord[0],
                  coord[1],
                  coord[2],
                  verts[i],
                  absolute=True,
                  x=axes[0],
                  y=axes[1],
                  z=axes[2],
                  worldSpace=True)
        print(cmds.pointPosition(verts[i], w=True))
Ejemplo n.º 45
0
    def __orientControl(self, offset):
        # get position
        pos = cmds.xform(offset, q=True, ws=True, t=True)

        # get closest parameter on curve
        parameter, _ = curve.nearestPointOnCurve(self.curveShape, pos)

        # get tangent
        forward = cmds.pointOnCurve(self.curveShape,
                                    pr=parameter,
                                    normalizedTangent=True)

        # get up
        forward = OpenMaya.MVector(*forward)
        up = OpenMaya.MVector(*self.upVector)

        right = up ^ forward
        right.normalize()

        up = right ^ forward
        up.normalize()

        orient = up * OpenMaya.MVector(*self.upVector)
        if orient <= 0:
            up = up * -1

        # construct quaternion
        quaternion = math.lookRotation(up, forward)

        # convert to euler
        euler = quaternion.asEulerRotation()

        rot = [
            math.degrees(euler.x),
            math.degrees(euler.y),
            math.degrees(euler.z),
        ]

        # set euler
        cmds.xform(offset, ws=True, ro=rot)
    def postPositions(self):
        oldPost = None
        XZ = 0, 0

        for num in range(self.postNum):
            pos = cmds.pointOnCurve(FindPositions.nurbsCurve,
                                    p=True,
                                    pr=float(num) /
                                    (float(self.postNum) / float(self.points)))
            post = cmds.duplicate(FindPositions.post)
            cmds.move(pos[0], pos[1], pos[2], post)

            if num > 0:
                yRot = findYRot(XZ, (pos[0], pos[2]))
                cmds.rotate(0, yRot, 0, oldPost, relative=True)
                if num != self.postNum:
                    crossBeams = CrossBeams().addBeams(
                        width=distance(XZ[0], pos[0], XZ[1], pos[2]))
                    pickets = Pickets().create(
                        totalSpace=(distance(XZ[0], pos[0], XZ[1], pos[2]) -
                                    findWidth(FindPositions.post)))
                    cmds.move(XZ[0], 0, XZ[1], crossBeams)
                    cmds.rotate(0,
                                yRot,
                                0,
                                crossBeams,
                                relative=True,
                                p=[XZ[0], 0, XZ[1]])
                    cmds.move(XZ[0], 0, XZ[1], pickets)
                    cmds.rotate(0,
                                yRot,
                                0,
                                pickets,
                                relative=True,
                                p=[XZ[0], 0, XZ[1]])

            oldPost = post
            XZ = pos[0], pos[2]
Ejemplo n.º 47
0
def noiseCurve( curve, start=0.0, end=1.0, freq=1.0, ease=0.5, strength=1.0 ):
    """ Adds noise to a given curve by moving each vertex with Perlin
        noise based on the normal.  This process takes place over the
        range defined by "start" and "end" as percentages of arc length.
        Noise eases to full strength as determined by the "ease" and
        "strength" arguments. """
    if(ease > (end-start)*0.5):         # ease must be between 0 and 0.5
        ease = (end-start)*0.5
    if(start < end):
        CVs = mc.getAttr( curve+".cv[*]" )
        newCVs = findCVsInRange(curve, start, end)
        for (I,U,L) in newCVs:
            interp = (L-start)/(end-start)
            noiz = noise(freq*interp)
            scale = pulse(start+ease, end, ease, L)  
            normal = Vector(0,1,0)**Vector(mc.pointOnCurve(curve, parameter=U, tangent=True))
            normal = normal.norm()
            pos = Vector(CVs[I])
            pos = pos+normal*scale*strength*noiz
            CVs[I] = pos.asTuple()
    for i,cv in enumerate(CVs):
        print(curve+".cv[%d]"%cv[0], cv[0], cv[1], cv[2])
        mc.setAttr(curve+".cv[%d]"%i, cv[0], cv[1], cv[2])
Ejemplo n.º 48
0
def neighbour(vertexList,referenceObject,meshRelax):
	'''
	'''
	# Get meshRelax object and target plug
	sel = OpenMaya.MSelectionList()
	OpenMaya.MGlobal.getSelectionListByName(meshRelax,sel)
	meshRelaxObj = OpenMaya.MObject()
	sel.getDependNode(0,meshRelaxObj)
	meshRelaxNode = OpenMaya.MFnDependencyNode(meshRelaxObj)
	neighbourDataPlug = meshRelaxNode.findPlug('neighbourData')
	neighbourDataArrayPlug = neighbourDataPlug.elementByLogicalIndex(0)
	
	# Check reference object
	isCurve = True
	if not glTools.utils.curve.isCurve(referenceObject):
		isCurve = False
	elif not glTools.utils.curve.isSurface(referenceObject):
		raise UserInputError('Reference object must be a valid nurbs curve or surface!!')
	
	# Create neighbourData object
	neighbourData = OpenMaya.MVectorArray()
	
	# Get mesh and vertex list
	compUtil = glTools.common.componentUtilities.ComponentUtilities()
	mesh = compUtil.getComponentIndexList(vertexList).keys()[0]
	
	# Get vertexIterator for mesh
	sel = OpenMaya.MSelectionList()
	OpenMaya.MGlobal.getSelectionListByName(mesh,sel)
	meshObj = OpenMaya.MObject()
	sel.getDependNode(0,meshObj)
	meshIt = OpenMaya.MItMeshVertex(meshObj)
	
	# Get neighbour data
	for i in range(len(vertexList)):
		
		# Get current point
		pnt = mc.pointPosition(vertexList[i])
		pntId = compUtil.getComponentIndexList([vertexList[i]])[mesh][0]
		
		# Get closest U tangent
		if isCurve:
			u = glTools.utils.curve.closestPoint(referenceObject,pnt)
			tan = mc.pointOnCurve(referenceObject,pr=u,nt=True)
		else:
			uv = glTools.utils.surface.closestPoint(referenceObject,pnt)
			tan = mc.pointOnSurface(referenceObject,u=uv[0],v=uv[1],ntu=True)
		tangent = OpenMaya.MVector(tan[0],tan[1],tan[2])
		
		# Get neighbouring points
		n1 = mc.pickWalk(vertexList[i],d='up')[0]
		n1Id = compUtil.getComponentIndexList([n1])[mesh][0]
		n1Pt = mc.pointPosition(n1)
		n1Dist = glTools.utils.mathUtils.distanceBetween(pnt,n1Pt)
		
		n2 = mc.pickWalk(vertexList[i],d='down')[0]
		n2Id = compUtil.getComponentIndexList([n2])[mesh][0]
		n2Pt = mc.pointPosition(n2)
		n2Dist = glTools.utils.mathUtils.distanceBetween(pnt,n2Pt)
		
		# Build neighbour data vector
		tDist = n1Dist + n2Dist
		neighbourData.append(OpenMaya.MVector(float(pntId),n1Id+(n1Dist/tDist),n2Id+(n2Dist/tDist)))
	
	# Set value
	neighbourDataArrayPlug.setMObject(OpenMaya.MFnVectorArrayData().create(neighbourData))
Ejemplo n.º 49
0
import maya.cmds as mc
import math

wid = 2
dist = 0.1
hig = 1

crv = "curve1"

for i in range(0, 20):
    dist = 0 + 0.01 * (i % 2)
    while dist < 1:
        tan = mc.pointOnCurve(crv, t=1, top=1, pr=dist)
        mag = math.sqrt(tan[0] * tan[0] + tan[1] * tan[1] + tan[2] * tan[2])
        rot = math.atan2(tan[0], tan[2])
        p = mc.pointOnCurve(crv, top=1, pr=dist)
        #print(p)
        c = mc.polyCube(w=wid, h=hig)
        mc.rotate(0, math.degrees(rot) + 90, 0)
        mc.move(p[0], i * 1.05 + p[1], p[2])
        dist = dist + 0.3 / mag
Ejemplo n.º 50
0
def create(	path,
			objectType,
			num=0,
			parent=False,
			useDist=False,
			min=0.0,
			max=1.0,
			prefix=''	):
	'''
	Create objects along a curve
	
	# INPUTS:
	@input path: Input nurbs curve path
	@inputType path: str
	@input objectType: Type of objects to create and place along path
	@inputType objectType: str
	@input num: Number of objects to create along path. If num=0, number of edit points will be used.
	@inputType num: int
	@input parent: Parent each new object to the previously created object. eg. Joint chain
	@inputType parent: bool
	@input useDist: Use distance along curve instead of parametric length for sample distribution
	@inputType useDist: bool
	@input min: Percent along the path to start placing objects
	@inputType min: float
	@input max: Percent along the path to stop placing objects
	@inputType max: float
	@input prefix: Name prefix for builder created nodes. If left at default ("") prefix will be derived from path name.
	@inputType prefix: str
	
	# OUTPUTS:
	@output outObjectList: List of objects placed along path
	@outputType outObjectList: list
	'''
	
	# Check Path
	if not glTools.utils.curve.isCurve(path):
		raise Exception('Path object '+path+' is not a valid nurbs curve!')
	
	# Check prefix
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(path)
	
	# Check object count
	if not num: num = mc.getAttr(path+'.spans') + 1
	
	# Get curve sample points
	paramList = glTools.utils.curve.sampleParam(path,num,useDist,min,max)
	
	# Create object along path
	objList = []
	for i in range(num):
		
		# Get string index
		ind = glTools.utils.stringUtils.stringIndex(i+1)
		
		# Create object
		obj = mc.createNode(objectType,n=prefix+ind+'_'+objectType)
		if not glTools.utils.base.isTransform(obj): obj = mc.listRelatives(obj,p=True,pa=True)[0]
		
		# Position
		pos = mc.pointOnCurve(path,pr=paramList[i])
		mc.xform(obj,t=pos,ws=True)
		
		# Parent
		if parent and i: obj = mc.parent(obj,objList[-1])[0]
		
		# Orient Joint
		if objectType == 'joint' and i: mc.joint(objList[-1],e=True,zso=True,oj='xyz',sao='yup')
		
		# Append result
		objList.append( str(obj) )
	
	# Return result
	return objList
Ejemplo n.º 51
0
def Rig(nameSpace):

    # - get guides -
    guides = ["%s:link_start_gui" % nameSpace, "%s:link_end_gui" % nameSpace, "%s:link_up_gui" % nameSpace]

    # - make curve -
    pathCurve = buildeCurve(guides[0], guides[1])

    # - make up curve -
    upvectorCurve = buidleUpCurve(*guides)

    # - make Joints and locators-
    Joints = []
    locators = []
    multiNodes = []
    counts = mc.getAttr("%s.jointCount" % guides[0])
    for i in range(counts):
        # - 1 create
        Joints.append(mc.createNode("joint"))
        locators.append(mc.spaceLocator(p=(0, 0, 0))[0])

        # - 2
        parameter = (((float(i + 1) - 0) / (counts + 1 - 0)) * (1 - 0)) + 0

        # - 3 attact to curve
        multiNodes.append(attachToCurve(Joints[-1], pathCurve, parameter))
        attachToCurve(locators[-1], upvectorCurve, parameter)

        # - 4 connect object up
        addUpObject(Joints[-1], locators[-1])

    # - add rig Joins -
    rigJoints = []
    for i in range(4):
        rigJoints.append(mc.createNode("joint"))
        # - move
        position = mc.pointOnCurve(pathCurve, pr=1.0 / 3 * i)
        mc.move(position[0], position[1], position[2], rigJoints[-1], a=True)
        # - orient
        mc.delete(mc.orientConstraint(Joints[0], rigJoints[-1]))

    # - bind Curve
    mc.skinCluster(rigJoints, pathCurve)
    mc.skinCluster(rigJoints, upvectorCurve)

    # - rig rigJoints -
    controlLst = []
    for jnt in rigJoints:

        # - make control
        controls = [mc.createNode("transform") for i in range(4)]
        for i in range(len(controls) - 1):
            mc.parent(controls[i], controls[i + 1])
        controlLst.append(controls)

        # - match positions, parent Joint
        mc.delete(mc.parentConstraint(jnt, controls[-1]))
        mc.parent(jnt, controls[0])

        # -add Shape
        circle = mc.circle(nr=(1, 0, 0), ch=0)
        mc.parent(mc.listRelatives(circle, s=True, path=True), controls[0], r=True, s=True)
        mc.delete(circle)

    # - Constraint control
    appLocators = []
    for controls in controlLst:
        appLocators.append(mc.spaceLocator(p=(0, 0, 0))[0])
        mc.delete(mc.parentConstraint(controls[0], appLocators[-1]))
        mc.parentConstraint(appLocators[-1], controls[-2])
        mc.scaleConstraint(appLocators[-1], controls[-2])

    # - add def
    mc.addAttr(appLocators[-1], sn="IKFKSwitch", min=0, max=1, dv=0, k=True)
    mc.addAttr(appLocators[-1], sn="fkRotate", dv=0, k=True)
    mc.addAttr(appLocators[-1], sn="ikRotate", dv=0, k=True)

    blendNode = mc.createNode("blendTwoAttr")
    mc.connectAttr("%s.IKFKSwitch" % appLocators[-1], "%s.ab" % blendNode)
    mc.connectAttr("%s.fkRotate" % appLocators[-1], "%s.input[0]" % blendNode)
    mc.connectAttr("%s.ikRotate" % appLocators[-1], "%s.input[1]" % blendNode)

    for md in multiNodes:
        mc.connectAttr("%s.output" % blendNode, "%s.input1" % md)

    # -- comp hery --
    curveGrp = mc.group(pathCurve, upvectorCurve)
    jointGrp = mc.group(Joints)
    locatorGrp = mc.group(locators)
    controlGrp = mc.group([L[-1] for L in controlLst])
    RootGrp = mc.group(curveGrp, jointGrp, locatorGrp, controlGrp)

    # -- clean scene --
    mc.hide(curveGrp, locatorGrp, rigJoints)

    # -* rename *-

    # - groups -
    curveGrp = mc.rename(curveGrp, "%s_cusg_0" % nameSpace)
    jointGrp = mc.rename(jointGrp, "%s_jntg_0" % nameSpace)
    locatorGrp = mc.rename(locatorGrp, "%s_locg_0" % nameSpace)
    controlGrp = mc.rename(controlGrp, "%s_ctlg_0" % nameSpace)
    RootGrp = mc.rename(RootGrp, "%s_setg_0" % nameSpace)

    # - joints -
    for i, jnt in enumerate(Joints):
        Joints[i] = mc.rename(jnt, "%s_bnd%s_0" % (nameSpace, string.uppercase[i]))

    # - locators -
    for i, loc in enumerate(locators):
        locators[i] = mc.rename(loc, "%s_loc%s_0" % (nameSpace, string.uppercase[i]))

    # - aooLocators -
    for i, loc in enumerate(appLocators):
        appLocators[i] = mc.rename(loc, "%s_apploc%s_0" % (nameSpace, string.uppercase[i]))

    # - rig Joints -
    for i, jnt in enumerate(rigJoints):
        rigJoints[i] = mc.rename(jnt, "%s_ctj%s_0" % (nameSpace, string.uppercase[i]))

    # - control -
    ctlType = ("ctl", "ctu", "cth", "ctg")
    for i, ctls in enumerate(controlLst):
        for d, ctl in enumerate(ctls):
            controlLst[i][d] = mc.rename(ctl, "%s%s_%s_0" % (nameSpace, string.uppercase[i], ctlType[d]))

    # - curve -
    pathCurve = mc.rename(pathCurve, "%s_TWbaseCus_0" % nameSpace)
    upvectorCurve = mc.rename(upvectorCurve, "%s_TWupperCus_0" % nameSpace)
Ejemplo n.º 52
0
for lx_i in lx_eyeLidPtion :
    lx_endPtion = mc.xform (lx_i,q=True ,ws=True ,t=True );
    lx_sj = mc.joint (p=(lx_cption[0],lx_cption[1],lx_cption[2]));
    lx_ee = mc.joint (p=(lx_endPtion [0],lx_endPtion [1],lx_endPtion [2],));
    mc.ikHandle (sj =lx_sj,ee = lx_ee ,sol ="ikSCsolver" );
    mc.select (cl=1);
    

import maya.cmds as mc
lx_curve = mc.ls(sl=1);

import maya.cmds as mc
lx_jnt = mc.ls(sl=1);
lx_node=[];
for lx_temp in lx_jnt :
    nd=mc.pointOnCurve (lx_curve,ch=True );
    lx_node.insert(1,nd);
    mc.rename(nd,"cueNd_"+lx_temp);
    mc.group(empty=1,n=("nl_"+lx_temp));
    mc.connectAttr(("cueNd_"+lx_temp +".position"),("nl_"+lx_temp+".translate"));
    mc.toggle (("nl_"+lx_temp),localAxis=1);
    
    
    
    
import maya.cmds as mc
infoNd = mc.ls(sl=1)
mc.select(cl=1)
for i in infoNd:
    mc.print(i)
    grp = mc.group(em =1)
Ejemplo n.º 53
0
def curveIntersectJoints(curve,
                         intersectCurveList,
                         jointAtBase=True,
                         jointAtTip=True,
                         useDirection=False,
                         intersectDirection=(0, 0, 1),
                         prefix=''):
    """
    Create joints along a curve at the points of intersection with a list of secondary curves
    @param curve: Curve to create joints along
    @type curve: list
    @param intersectCurveList: List of intersection curves
    @type intersectCurveList: list
    @param jointAtBase: Create a joint at the base of the curve
    @type jointAtBase: bool
    @param jointAtTip: Create a joint at the tip of the curve
    @type jointAtTip: bool
    @param useDirection: Project the curves in a specified direction before intersecting
    @type useDirection: bool
    @param intersectDirection: The direction to project the curves before intersecting
    @type intersectDirection: tuple or list
    @param prefix: Name prefix for newly created nodes
    @type prefix: str
    """
    # Check curve
    if not cmds.objExists(curve):
        raise Exception('Curve object ' + curve + ' does not exist!')

    # Check intersect curve list
    for i in range(len(intersectCurveList)):
        if not cmds.objExists(intersectCurveList[i]):
            raise Exception('Object ' + intersectCurveList[i] + ' is not a valid curve!')

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

    # Get curve Range
    minU = cmds.getAttr(curve + '.minValue')
    maxU = cmds.getAttr(curve + '.maxValue')

    # Initialize return list
    cmds.select(cl=True)
    jointList = []

    # Create Base Joint
    if jointAtBase:
        # Get curve point position
        pos = cmds.pointOnCurve(curve, pr=minU, p=True)
        # Create joint
        ind = '01'
        jnt = prefix + nameUtil.delineator + nameUtil.subPart['joint'] + ind + nameUtil.delineator + nameUtil.node[
            'joint']
        jnt = cmds.joint(p=pos, n=jnt)
        jointList.append(jnt)

    # Create joints at curve intersections
    for n in range(len(intersectCurveList)):
        # Get string index
        ind = str(n + 1 + int(jointAtBase))
        if i < (9 - int(jointAtBase)): ind = '0' + ind
        # Get curve intersections
        uList = cmds.curveIntersect(curve, intersectCurveList[n], ud=useDirection, d=intersectDirection)
        if not uList: continue
        uList = uList.split(' ')

        # Create joints
        for u in range(len(uList) / 2):
            # Get curve point position
            pos = cmds.pointOnCurve(curve, pr=float(uList[u * 2]), p=True)
            # Create joint
            jnt = prefix + nameUtil.delineator + nameUtil.subPart['joint'] + ind + nameUtil.delineator + nameUtil.node[
                'joint']
            jnt = cmds.joint(p=pos, n=jnt)
            jointList.append(jnt)

    # Create Tip Joint
    if jointAtTip:
        # Get string index
        ind = str(len(intersectCurveList) + int(jointAtBase) + 1)
        if len(intersectCurveList) < (9 - int(jointAtBase)): ind = '0' + ind
        # Get curve point position
        pos = cmds.pointOnCurve(curve, pr=maxU, p=True)
        # Create joint
        jnt = prefix + nameUtil.delineator + nameUtil.subPart['joint'] + ind + nameUtil.delineator + nameUtil.node[
            'joint']
        jnt = cmds.joint(p=pos, n=jnt)
        jointList.append(jnt)

    # Return result
    return jointList
Ejemplo n.º 54
0
def createCoonsPatch(cpairs):
  global csNum
  global cs
  global chNum
  global ch
  
  global vertices
  global normals

  # square patch dimension T_STEP by T_STEP
  T_STEPS = 10  
  
  vertices = [[None]*(T_STEPS) for x in range(T_STEPS)]
  normals = [[None]*(T_STEPS) for x in range(T_STEPS)]
  
  # ALONG CURVE
  
  # go from each ch to ch
  for p in range(4):
    cStart = ch[ cpairs[p][1] ][ cpairs[p][0] ]
    cEnd = None
    if p<3:
      cEnd = ch[ cpairs[p+1][0] ][ cpairs[p+1][1] ]
    else:      
      cEnd = ch[ cpairs[0][0] ][ cpairs[0][1] ]
    tStep = (cEnd.t-cStart.t)/(T_STEPS-1)
    
    # print "%s to %s : %s" % (cStart.t, cEnd.t, tStep)
    
    # go down curve
    
    t = cStart.t
    for step in range(T_STEPS-1):
      
      if step == 0:
        pos = cStart.pos
        nor = cStart.nor
      else:
        # get position
        pos = np.array(cmds.pointOnCurve(cs[cStart.i].name, pr=t, p=True))
        
        # get normal
        nor1 = getCHNormAtT(cStart.i, cStart.j, t)
        nor2 = getCHNormAtT(cEnd.i, cEnd.j, t)      
        blendT = (t-cStart.t) / (cEnd.t-cStart.t)
        nor = blendT*nor2+(1-blendT)*nor1
      
      if p == 0:
        coord = (step,0)
      elif p == 1:
        coord = (T_STEPS-1,step)
      elif p == 2:
        coord = (T_STEPS-1-step,T_STEPS-1)
      elif p == 3:
        coord = (0, T_STEPS-1-step)
      
      #print "(%s,%s)" % (coord[0], coord[1])
      vertices[coord[0]][coord[1]] = pos
      normals[coord[0]][coord[1]] = nor
      
      #cmds.spaceLocator( p=(pos+nor).tolist() )
      
      t = t + tStep
      
  
  # ALONG PATCH
  
  n = T_STEPS-1
  
  for i in range(1, T_STEPS-1):
    for j in range(1, T_STEPS-1):      
      
      vertices[i][j] = np.array([0.0,0.0,0.0])
      normals[i][j] = np.array([0.0,0.0,0.0])
      
      fi = float(i)
      fj = float(j)
      
      for k in range(3):
          
        vertices[i][j][k] = (
          (1.0-fi/n)*vertices[0][j][k] + fi/n*vertices[n][j][k] +
          (1.0-fj/n)*vertices[i][0][k] + fj/n*vertices[i][n][k] -
          (
            vertices[0][0][k]+(vertices[n][0][k]-vertices[0][0][k])*(fi/n) + 
            (
              (vertices[0][n][k]+(vertices[n][n][k]-vertices[0][n][k])*(fi/n)) - 
              (vertices[0][0][k]+(vertices[n][0][k]-vertices[0][0][k])*(fi/n))
            ) * (fj/n)
          )
        )
        
        normals[i][j][k] = (
          (1.0-fi/n)*normals[0][j][k] + fi/n*normals[n][j][k] +
          (1.0-fj/n)*normals[i][0][k] + fj/n*normals[i][n][k] -
          (
            normals[0][0][k]+(normals[n][0][k]-normals[0][0][k])*(fi/n) + 
            (
              (normals[0][n][k]+(normals[n][n][k]-normals[0][n][k])*(fi/n)) - 
              (normals[0][0][k]+(normals[n][0][k]-normals[0][0][k])*(fi/n))
            ) * (fj/n)
          )
        )

      # cmds.spaceLocator( p=(vertices[i][j]+normals[i][j]).tolist() )
    
  createPatchMesh(vertices, normals)
Ejemplo n.º 55
0
def multiCurveAicmdsonstraint(transform, curve1, curve2, toggleAttr, aimAxis='y', tangentAxis='x', prefix=''):
    """
    @param transform: Transforms to aim at point on curve
    @type transform: list
    @param curve1: First curve aim target
    @type curve1: str
    @param curve2: Second curve aim target
    @type curve2: str
    @param toggleAttr: Attribute to toggle between the constraint targets
    @type toggleAttr: str
    @param aimAxis: Transform axis to aim at the point on curve
    @type aimAxis: float
    @param tangentAxis: Transform axis to align to the curve tangent
    @type tangentAxis: str
    @param prefix: Name prefix for newly created nodes
    @type prefix: str
    """
    # Build axis dictionary
    axisDict = {'x': (1, 0, 0), 'y': (0, 1, 0), 'z': (0, 0, 1), '-x': (-1, 0, 0), '-y': (0, -1, 0), '-z': (0, 0, -1)}

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

    # Transform worldSpace position
    pmm = prefix + '_pointMatrixMult'
    pmm = cmds.createNode('pointMatrixMult', n=pmm)
    cmds.connectAttr(transform + '.translate', pmm + '.inPoint', f=True)
    cmds.connectAttr(transform + '.parentMatrix[0]', pmm + '.inMatrix', f=True)
    cmds.setAttr(pmm + '.vectorMultiply', 1)

    # PointOnCurveInfo
    poc1 = prefix + '_pc01_pointOnCurveInfo'
    poc1 = cmds.createNode('pointOnCurveInfo', n=poc1)
    cmds.connectAttr(curve1 + '.worldSpace[0]', poc1 + '.inputCurve', f=True)
    poc2 = prefix + '_pc02_pointOnCurveInfo'
    poc2 = cmds.createNode('pointOnCurveInfo', n=poc2)
    cmds.connectAttr(curve2 + '.worldSpace[0]', poc2 + '.inputCurve', f=True)

    pos = cmds.xform(transform, q=True, ws=True, rp=True)
    param = glTools.utils.curve.closestPoint(curve1, pos)
    cmds.setAttr(poc1 + '.parameter', param)
    pos = cmds.pointOnCurve(curve1, pr=param, p=True)
    param = glTools.utils.curve.closestPoint(curve2, pos)
    cmds.setAttr(poc2 + '.parameter', param)

    # Offset
    pma1 = prefix + '_pc01_plusMinusAverage'
    pma1 = cmds.createNode('plusMinusAverage', n=pma1)
    cmds.connectAttr(poc1 + '.position', pma1 + '.input3D[0]', f=True)
    cmds.connectAttr(pmm + '.output', pma1 + '.input3D[1]', f=True)
    cmds.setAttr(pma1 + '.operation', 2)  # Subtract

    pma2 = prefix + '_pc02_plusMinusAverage'
    pma2 = cmds.createNode('plusMinusAverage', n=pma2)
    cmds.connectAttr(poc2 + '.position', pma2 + '.input3D[0]', f=True)
    cmds.connectAttr(pmm + '.output', pma2 + '.input3D[1]', f=True)
    cmds.setAttr(pma2 + '.operation', 2)  # Subtract

    # Blend Offset
    pos_bcn = prefix + '_ps01_blendColors'
    pos_bcn = cmds.createNode('blendColors', n=pos_bcn)
    cmds.connectAttr(pma1 + '.output3D', pos_bcn + '.color1', f=True)
    cmds.connectAttr(pma2 + '.output3D', pos_bcn + '.color2', f=True)
    cmds.connectAttr(toggleAttr, pos_bcn + '.blender', f=True)

    # Blend Tangent
    tan_bcn = prefix + '_rt01_blendColors'
    tan_bcn = cmds.createNode('blendColors', n=tan_bcn)
    cmds.connectAttr(poc1 + '.tangent', tan_bcn + '.color1', f=True)
    cmds.connectAttr(poc2 + '.tangent', tan_bcn + '.color2', f=True)
    cmds.connectAttr(toggleAttr, tan_bcn + '.blender', f=True)

    # Aim Constraint
    aicmdson = prefix + '_aicmdsonstraint'
    aicmdson = cmds.createNode('aicmdsonstraint', n=aicmdson)
    cmds.connectAttr(pos_bcn + '.output', aicmdson + '.target[0].targetTranslate', f=True)
    cmds.connectAttr(tan_bcn + '.output', aicmdson + '.worldUpVector', f=True)
    cmds.setAttr(aicmdson + '.worldUpType', 3)  # Vector
    cmds.connectAttr(transform + '.parentInverseMatrix[0]', aicmdson + '.constraintParentInverseMatrix', f=True)
    cmds.connectAttr(aicmdson + '.constraintRotateX', transform + '.rotateX', f=True)
    cmds.connectAttr(aicmdson + '.constraintRotateY', transform + '.rotateY', f=True)
    cmds.connectAttr(aicmdson + '.constraintRotateZ', transform + '.rotateZ', f=True)
    aimVec = axisDict[aimAxis]
    tanVec = axisDict[tangentAxis]
    cmds.setAttr(aicmdson + '.aimVector', aimVec[0], aimVec[1], aimVec[2])
    cmds.setAttr(aicmdson + '.upVector', tanVec[0], tanVec[1], tanVec[2])
    cmds.parent(aicmdson, transform)

    # Add parameter attribute
    minU = cmds.getAttr(curve1 + '.minValue')
    maxU = cmds.getAttr(curve1 + '.maxValue')
    if not cmds.objExists(transform + '.param1'):
        cmds.addAttr(transform, ln='param1', at='float', min=minU, max=maxU, k=True)
    cmds.setAttr(transform + '.param1', cmds.getAttr(poc1 + '.parameter'))
    cmds.connectAttr(transform + '.param1', poc1 + '.parameter', f=True)

    minU = cmds.getAttr(curve2 + '.minValue')
    maxU = cmds.getAttr(curve2 + '.maxValue')
    if not cmds.objExists(transform + '.param2'):
        cmds.addAttr(transform, ln='param2', at='float', min=minU, max=maxU, k=True)
    cmds.setAttr(transform + '.param2', cmds.getAttr(poc2 + '.parameter'))
    cmds.connectAttr(transform + '.param2', poc2 + '.parameter', f=True)

    # Return result
    return (aicmdson, poc1, poc2)
Ejemplo n.º 56
0
def readCrossSections():
  global csNum
  global cs
  global chNum
  global ch

  #mel.eval("layerEditorSelectObjects layerCross;")
  curveNames = mel.eval("ls -sl -type transform")

  # no curve drawn
  if not curveNames:
    return
  
  # init globals
  
  csNum = len(curveNames)
  cs = [None for x in range(csNum)]
  for i in range(csNum):
    cs[i] = CrossSection(i)
    cs[i].name = curveNames[i]
  
  chNum = 0
  ch = [[None]*csNum for x in range(csNum)]
  
  
  # process intersections
  
  for i in range(csNum):
    for j in range(i+1, csNum):

      rawIntersects = cmds.curveIntersect(cs[i].name, cs[j].name, useDirection=True, direction=(0,0,1))
      
      if rawIntersects:
        ch[i][j] = CrossHair(i,j)
        ch[j][i] = CrossHair(j,i)
      
        intersects = [float(k) for k in rawIntersects.split()]
        ch[i][j].t = intersects[0]
        ch[j][i].t = intersects[1]
        
        pi = cmds.pointOnCurve(cs[i].name, pr=ch[i][j].t, p=True)        
        ch[i][j].pos = np.array(pi)  # save
        ch[j][i].pos = np.array(pi)
        #cmds.spaceLocator(p=pi)   # place locator        
        
        t_ij = cmds.pointOnCurve(cs[i].name, pr=ch[i][j].t, nt=True)
        ch[i][j].tan = np.array(t_ij)
        
        t_ji = cmds.pointOnCurve(cs[j].name, pr=ch[j][i].t, nt=True)
        ch[j][i].tan = np.array(t_ji)
        
        
        print "(%s,%s) processed" % (i, j)
        
        chNum += 1
        
      else:
        print "(%s,%s) no intersect" % (i, j)
  
  # clear all selection
  mel.eval("select -cl")

  # store sorted list of ch for each cs
  for i in range(csNum):
    for j in range(csNum):
      if ch[i][j] is not None:
        cs[i].ch.append(ch[i][j])
        
    cs[i].ch = sorted(cs[i].ch, key=lambda ch: ch.t)
Ejemplo n.º 57
0
import maya.cmds as cmds
import random
#from ObjectScatter import *
import ObjectScatter
reload(ObjectScatter)


import maya.cmds as cmds
import random

points = [ cmds.pointPosition('curve1.cv[%i]'%i) for i in range(cmds.getAttr('curve1.spans') + cmds.getAttr('curve1.degree')) ]
tangent = [ cmds.pointOnCurve('curve1', pr=(1.0/23)*i, t=True) for i in range(23) ]

for pos in points:
	cmds.select(cmds.polyCone(r=0.2, h=0.2)[0])
	cmds.move(pos[0], pos[1], pos[2])
	cmds.select(['curve1', cmds.ls(sl=True)[0]]) 
	cmds.tangentConstraint(aimVector=(0,1,0), upVector=(1,0,1), worldUpType="vector",worldUpVector=(0,1,0))


new = cmds.polyCube()[0]
cmds.rotate(0, random.uniform(0, 360), 0)
cmds.move(random.uniform(0,8), 0, 0, os=True)


# UI
winName = "Object Scatter"
if(cmds.window(winName, exists=True)):
        cmds.deleteUI(winName)

window = cmds.window( title=winName, iconName=winName, widthHeight=(512, 512), maximizeButton=False )
Ejemplo n.º 58
0
def showtimeOnCurve(numFireworks, duration, variation, loop):
	
	selectedCurve = cmds.ls(sl=True)[0]
	
	#if (cmds.objectType(cmds.ls(sl=True)[0], isType = 'nurbsCurve') != 1):
	#	cmds.error('You didn\'t select a curve yo!')
	
	#Checks for correct naming format for script to work
	if cmds.objExists(selectedCurve+'Shape'):
		curveLen = cmds.getAttr(selectedCurve+'Shape.max')
	else:
		cmds.error('Please select/rename your curve cuz')
	
	d = curveLen / duration
	locOnCurve = 0
	t1 = 0
	print "curveLen: " + str(curveLen)
	
	total = numFireworks
	initializeProgressWindow('Firworks Along Cuve', total)
	
	while locOnCurve < curveLen:
		print "locOnCurve: " + str(locOnCurve)
		ifCreate = random.randint(0,1)
		if ifCreate == 1 and numFireworks > 0: #you can now create a firework
			loc = cmds.pointOnCurve(pr=locOnCurve, p=True)
			print "loc: " + str(loc)
			cmds.select(cl=True)
			
			newFirework = firework(0, 0)
			numFireworks -= 1
			
			fname = "firework"+"%03d"%numFireworks
			emname = fname+"EM"
			pname = fname+"P"
			
			#create emitters for firework effect and set certain attributes that don't need to be keyed
			newFirework.makeMe(emname, pname)
			cmds.xform(emname, t=(loc[0] + random.random()*variation - variation/2, loc[1] + random.random()*variation - variation/2, loc[2] + random.random()*variation - variation/2), ro=(newFirework.anglex, 0, newFirework.anglez))
			cmds.setAttr(pname+'Shape.startFrame', t1)

			#Shade and Key newly created firework.
			newFirework.shadeMe(fname, pname)
			newFirework.keyMe(emname, pname, t1)
			
			#group emitter and particle together in firework###
			cmds.group(emname, pname, n=fname)
			
			#deselect particle so that next iteration's emitters aren't created in each particle
			cmds.select(cl=True)
			
		locOnCurve += d
		
		if numFireworks > 0 and  locOnCurve >= curveLen:
			if loop == True:
				t1 = 0
			locOnCurve = 0
		if numFireworks < 0:
			break
		
		t1 +=1
		
		updateProgressWindow(total-numFireworks, total)
		cmds.select(selectedCurve)
		
	#selects all fireworks and groups them together
	cmds.select([node for node in cmds.ls() if 'firework' in node and 'EM' not in node and 'P' not in node and 'Shape' not in node])
	cmds.group(name='fireworkShow')
	
	#kills progress window
	killProgressWindow()
Ejemplo n.º 59
0
def Rig(nameSpace='arm'):
    
    #- get guides -
    guides = ['%s:link_start_gui'%nameSpace, '%s:link_end_gui'%nameSpace, '%s:link_up_gui'%nameSpace]
    
    #- make curve -
    pathCurve = buildeCurve(guides[0], guides[1])
    
    #- make up curve -
    upvectorCurve = buidleUpCurve(*guides)
    
    #- make Joints and locators-
    Joints = []
    locators = []
    counts = mc.getAttr('%s.jointCount'%guides[0])
    for i in range(counts):
        #- 1 create 
        Joints.append(mc.createNode('joint'))
        locators.append(mc.spaceLocator(p=(0,0,0))[0])
        
        #- 2 
        parameter = (((float(i + 1) - 0) / (counts + 1 - 0)) * (1 - 0)) + 0
        
        #- 3 attact to curve
        attachToCurve(Joints[-1], pathCurve, parameter)
        attachToCurve(locators[-1], upvectorCurve, parameter)
    
        #- 4 connect object up
        addUpObject(Joints[-1], locators[-1])
    
    
    #- add rig Joins -
    rigJoints = []
    for i in range(4):
        rigJoints.append(mc.createNode('joint'))
        #- move
        position = mc.pointOnCurve(pathCurve, pr= 1.0 / 3 * i)
        mc.move(position[0], position[1], position[2], rigJoints[-1], a=True)
        #- orient
        mc.delete(mc.orientConstraint(Joints[0], rigJoints[-1]))
    
    #- bind Curve
    mc.skinCluster(rigJoints, pathCurve)    
    mc.skinCluster(rigJoints, upvectorCurve)

    #- rig rigJoints -
    controlLst = []
    for jnt in rigJoints:
        
        #- make control
        controls = [mc.createNode('transform')  for i in range(4)]
        for i in range(len(controls) - 1):
            mc.parent(controls[i], controls[i+1])
        controlLst.append(controls)
        
        #- match positions, parent Joint
        mc.delete(mc.parentConstraint(jnt, controls[-1]))
        mc.parent(jnt, controls[0])
        
        #-add Shape
        circle = mc.circle(nr=(1,0,0), ch=0)
        mc.parent(mc.listRelatives(circle, s=True, path=True), controls[0], r=True, s=True)
        mc.delete(circle)
        
        
        
    #-- comp hery --
    curveGrp   = mc.group(pathCurve, upvectorCurve)
    jointGrp   = mc.group(Joints) 
    locatorGrp = mc.group(locators)    
    controlGrp = mc.group([L[-1] for L in controlLst])
    RootGrp    = mc.group(curveGrp, jointGrp, locatorGrp, controlGrp)
    
    #-- clean scene --
    mc.hide(curveGrp, locatorGrp, rigJoints)
    
    #-* rename *-
    
    #- groups -
    curveGrp   = mc.rename(curveGrp,   '%s_cusg_0'%nameSpace)
    jointGrp   = mc.rename(jointGrp,   '%s_jntg_0'%nameSpace)
    locatorGrp = mc.rename(locatorGrp, '%s_locg_0'%nameSpace)
    controlGrp = mc.rename(controlGrp, '%s_ctlg_0'%nameSpace)
    RootGrp    = mc.rename(RootGrp,    '%s_setg_0'%nameSpace)
    
    #- joints -
    for i,jnt in enumerate(Joints):
        Joints[i] = mc.rename(jnt, '%s_bnd%s_0'%(nameSpace, string.uppercase[i]))
    
    #- locators -
    for i,loc in enumerate(locators):
        locators[i] = mc.rename(loc, '%s_loc%s_0'%(nameSpace, string.uppercase[i]))    
    
    #- rig Joints -
    for i,jnt in enumerate(rigJoints):
        rigJoints[i] = mc.rename(jnt, '%s_ctj%s_0'%(nameSpace, string.uppercase[i]))   

    #- control -
    ctlType = ('ctl', 'ctu', 'cth', 'ctg') 
    for i, ctls in enumerate(controlLst):
        for d, ctl in enumerate(ctls):
            controlLst[i][d] = mc.rename(ctl, '%s%s_%s_0'%(nameSpace, string.uppercase[i], ctlType[d]))   
    #- curve -
    pathCurve = mc.rename(pathCurve, '%s_TWbaseCus_0'%nameSpace)    
    upvectorCurve = mc.rename(upvectorCurve , '%s_TWupperCus_0'%nameSpace)    
Ejemplo n.º 60
0
def setNeighbour(vertexList=[],referenceObject='',dnDirectionalSmoothNode='',direction='u'):
	'''
	'''
	# Flatten vertex list
	vertexList = mc.ls(vertexList,fl=True)
	
	# Get dnDirectionalSmoothNode object and target plug
	sel = OpenMaya.MSelectionList()
	OpenMaya.MGlobal.getSelectionListByName(dnDirectionalSmoothNode,sel)
	dnDirectionalSmoothNodeObj = OpenMaya.MObject()
	sel.getDependNode(0,dnDirectionalSmoothNodeObj)
	dnDirectionalSmoothNodeNode = OpenMaya.MFnDependencyNode(dnDirectionalSmoothNodeObj)
	neighbourDataPlug = dnDirectionalSmoothNodeNode.findPlug('neighbourData')
	neighbourDataArrayPlug = neighbourDataPlug.elementByLogicalIndex(0)
	
	# Check reference object
	isCurve = True
	if not glTools.utils.curve.isCurve(referenceObject):
		isCurve = False
	elif not glTools.utils.curve.isSurface(referenceObject):
		raise UserInputError('Reference object must be a valid nurbs curve or surface!!')
	
	# Create neighbourData object
	neighbourData = OpenMaya.MVectorArray()
	
	# Get mesh and vertex list
	mesh = glTools.utils.component.getComponentIndexList(vertexList).keys()[0]
	
	# Get vertexIterator for mesh
	sel = OpenMaya.MSelectionList()
	OpenMaya.MGlobal.getSelectionListByName(mesh,sel)
	meshObj = OpenMaya.MObject()
	sel.getDependNode(0,meshObj)
	meshIt = OpenMaya.MItMeshVertex(meshObj)
	
	# Get neighbour data
	neighbourIndexList = OpenMaya.MIntArray()
	for i in range(len(vertexList)):
		
		# Get current point
		pnt = mc.pointPosition(vertexList[i])
		pntId = glTools.utils.component.getComponentIndexList([vertexList[i]])[mesh][0]
		
		# Get closest U tangent
		if isCurve:
			u = glTools.utils.curve.closestPoint(referenceObject,pnt)
			tan = mc.pointOnCurve(referenceObject,pr=u,nt=True)
		else:
			uv = glTools.utils.surface.closestPoint(referenceObject,pnt)
			tan = [0,0,0]
			if direction == 'u':
				tan = mc.pointOnSurface(referenceObject,u=uv[0],v=uv[1],ntu=True)
			elif direction == 'v':
				tan = mc.pointOnSurface(referenceObject,u=uv[0],v=uv[1],ntv=True)
			else:
				raise Exception('Invalid direction value!')
		tan = glTools.utils.mathUtils.normalizeVector(tan)
		
		# Get neighbouring points
		conFaces = mc.ls(mc.polyListComponentConversion(vertexList[i],fv=True,tf=True),fl=True)
		conVerts = mc.ls(mc.polyListComponentConversion(conFaces,ff=True,tv=True),fl=True)
		conVertList = glTools.utils.component.getComponentIndexList(conVerts)[mesh]
		
		# Determine neighbours
		n1Id = -1
		n2Id = -1
		n1Dist = 0.5
		n2Dist = 0.5
		minDot = 0.0
		maxDot = 0.0
		# Iterate through connected verts
		for n in range(len(conVertList)):
			nPnt = mc.pointPosition(mesh+'.vtx['+str(conVertList[n])+']')
			dist = glTools.utils.mathUtils.offsetVector(pnt,nPnt)
			nDist = glTools.utils.mathUtils.normalizeVector(dist)
			dot = glTools.utils.mathUtils.dotProduct(tan,nDist)
			if dot > maxDot:
				n1Id = conVertList[n]
				n1Dist = glTools.utils.mathUtils.mag(dist)
				maxDot = dot
			if dot < minDot:
				n2Id = conVertList[n]
				n2Dist = glTools.utils.mathUtils.mag(dist)
				minDot = dot
		
		# Build neighbour data vector
		tDist = n1Dist + n2Dist
		n1Dist = 1.0 - (n1Dist/tDist)
		n2Dist = 1.0 - (n2Dist/tDist)
		neighbourData.append(OpenMaya.MVector(float(pntId),n1Id+n1Dist,n2Id+n2Dist))
	
	# Set value
	neighbourDataArrayPlug.setMObject(OpenMaya.MFnVectorArrayData().create(neighbourData))
	
	# Return result
	return neighbourData