def buildPolyPlane():
    """
    Splitting out the part so we can choose what to convert and what not to to reduce the load on the FX scene
    Builds a polyPlane with construction history from the nurbsPlane to help collide partilces
    Note you must have a valid nurbsPlane selection for this function
    """
    for eachSel in cmds.ls(sl= True):
        name = '%s_polyCollide_geo' % eachSel.split('NurbsIntersect')[0]
        cmds.nurbsToPoly(eachSel, n = '%s_collider' % eachSel, format = 0, pt = 1, pc = 200, ch= True)
        cmds.select('%s_collider' % eachSel, r = True)
        mel.eval('makeCollideNCloth;')
        cmds.rename('nRigid1', '%s_collider_nRigid' % eachSel)
        _cleanupPolyPlane(polyPlane = '%s_collider_nRigid' % eachSel)
def get_meshFromNurbs(nurbSurface = None, mode = 'default', uNumber = 10, vNumber = 10):
    mMesh = cgmMeta.validateObjArg(nurbSurface,mayaType='nurbsSurface')
    mDup = mMesh.doDuplicate(po=False)
    
    
    #mNew = self.doCreateAt(setClass='cgmObject')
    newShapes = []
    for mShape in mDup.getShapes(asMeta=1):
        if mode == 'default':
            d_kws = {}
            _res = mc.nurbsToPoly(mShape.mNode, mnd=1,ch=0,f=3,pt =1,pc =200,
                                  chr =0.9,ft =0.01,mel =0.001,d =0.1,ut =1,un =3,
                                  vt =1,vn =3,uch =0,ucr =0,cht =0.2,es =0,ntr =0,
                                  mrt =0,uss =1)            
        elif mode == 'general':
            d_kws = {'mnd' :1,
                     'ch':0 ,
                     'f': 2,
                     'pt': 1,#quad
                     'pc':200,
                     'chr':0.9,
                     'ft':0.01,
                     'mel': 0.001,
                     'd':0.1,
                     'ut': 1,
                     'un': uNumber,
                     'vt':1,
                     'vn': vNumber,
                     'uch': 0,
                     'ucr':0,
                     'cht':0.2,
                     'es':0,
                     'ntr':0,
                     'mrt':0,
                     'uss':1}
            _res = mc.nurbsToPoly(mShape.mNode, **d_kws)
        else:
            raise ValueError,"get_meshFromNurbs | Unknown mode: {0}".format(mode)
        newShapes.append(_res[0])

    if len(newShapes)>1:
        _mesh = mc.polyUnite(newShapes,ch=False)[0]
    else:
        _mesh = newShapes[0]

    mNew = cgmMeta.asMeta(_mesh)

    #for s in newShapes:
    mDup.delete()
    
    return mNew
示例#3
0
def makePipe(circle, pipeCurve):
	pipeSweep = sweepPipe(circle, pipeCurve)
	nurbsPipe = cmds.loft(pipeSweep, degree=1, reverseSurfaceNormals=True)
	polyPipe = cmds.nurbsToPoly(nurbsPipe[0], name="fastPipe", format=3, matchNormalDir=True, polygonType=1)
	cmds.polyMergeVertex(polyPipe[0], d=0.1, alwaysMergeTwoVertices=True)
	cmds.delete(pipeSweep[0], nurbsPipe[0], circle[0], pipeCurve[0])
	cmds.select(polyPipe)
示例#4
0
def extendPoly(*args):
    """does the polyextension by grabbing the curve, offsetting it and then lofting. Then converts the nurbs surface to polys"""

    #make sure a curve is selected
    selection = cmds.ls(sl=True)
    if selection:
        sel = selection[0]
        shape = cmds.listRelatives(sel, s=True)[0]
        type = cmds.objectType(shape)
        name = cmds.textFieldGrp("name", q=True, tx=True)
        hisGrp = cmds.checkBox("history", q=True, v=True)
        hisPoly = cmds.checkBox("polyHistory", q=True, v=True)

        if type == "nurbsCurve":
            #offset the curb
            distance = cmds.floatFieldGrp("curbFFG", q=True, v1=True)
            # bump = cmds.checkBox("bumpCB", q=True, v=True)
            pos = cmds.checkBox("curbCB", q=True, v=True)
            if pos == 0:
                dist = distance * -1
            else:
                dist = distance
            U = cmds.intFieldGrp("UDivIFG", q=True, v1=True)
            V = cmds.intFieldGrp("VDivIFG", q=True, v1=True)

            origCrv = cmds.rename(sel, "%s_inner_CRV" % name)
            outCurve = cmds.offsetCurve(origCrv,
                                        d=dist,
                                        n="%s_outer_CRV" % name)
            midCurve = cmds.offsetCurve(origCrv,
                                        d=dist / 2,
                                        n="%s_mid_CRV" % name)
            # if bump:
            #     cmds.xform(midCurve, ws=True, r=True, t=(0,5,0))

            cmds.select(cl=True)

            lofted = cmds.loft(origCrv, midCurve, outCurve)[0]
            loft = cmds.rename(lofted, "%s_lofted" % name)

            polygon = cmds.nurbsToPoly(loft, pt=1, ch=hisPoly, f=2, un=U,
                                       vn=V)[0]
            poly = cmds.rename(polygon, "%s_poly" % name)

            curbGrp = cmds.group(empty=True)
            grp = cmds.rename(curbGrp, "%s_History_GRP" % name)

            # cmds.rename(poly, "polyCurb")

            cmds.parent(loft, outCurve, midCurve, origCrv, grp)

            cmds.setAttr("%s.v" % grp, 0)
            if not hisGrp:
                cmds.delete(grp)

        else:
            cmds.warning("That's not a curve! You need to select a curve!")
    else:
        cmds.warning("You haven't selected anything!")
示例#5
0
def load_mesh():
    get_all_mesh = mc.ls(sl=True, dagObjects=False)
    if not get_all_mesh:
        mc.confirmDialog(title=u'提醒', message=u'请先选择要转换的物体或者组', button='Yes')
        return

    get_all_mesh_string = ""
    get_all_nurbs_string = ""
    get_all_string = ""

    if int(mc.checkBox("if_combine", q=True, v=True)) == 1:
        for one_check in get_all_mesh:
            get_all_mesh_string += "\"" + one_check + "\","
        if len(get_all_mesh_string) != 0:
            mc.textScrollList("the_mod_list", e=True, ra=True)
            exec("mc.textScrollList(\"the_mod_list\",e=True,append=(" +
                 get_all_mesh_string[0:-1] + "))")

    if int(mc.checkBox("if_combine", q=True, v=True)) == 0:
        mc.select(hi=True)
        get_all_mesh = mc.ls(selection=True,
                             dagObjects=True,
                             ni=True,
                             shapes=True)
        for one_check_mesh in get_all_mesh:
            if mc.nodeType(one_check_mesh) == "nurbsSurface":
                temp_name = mc.listRelatives(one_check_mesh, p=True)
                group_name = mc.listRelatives(temp_name, f=True, p=True)
                for one_name in temp_name:
                    get_all_nurbs_string += "\"" + one_name + "_nurbs" + "\","
                    mc.nurbsToPoly(one_name,
                                   polygonType=1,
                                   ch=True,
                                   name=one_name + "_nurbs")
                    mc.parent(one_name + "_nurbs", group_name)

            if mc.nodeType(one_check_mesh) == "mesh":
                temp_trans = mc.listRelatives(one_check_mesh, f=True, p=True)
                get_all_mesh_string += "\"" + temp_trans[0] + "\","
            get_all_string = get_all_nurbs_string + get_all_mesh_string
        if len(get_all_mesh_string) != 0:
            mc.textScrollList("the_mod_list", e=True, ra=True)
            exec("mc.textScrollList(\"the_mod_list\",e=True,append=(" +
                 get_all_string[0:-1] + "))")
        mc.select(cl=True, r=True)
def buildPolyPlane():
    """
    Splitting out the part so we can choose what to convert and what not to to reduce the load on the FX scene
    Builds a polyPlane with construction history from the nurbsPlane to help collide partilces
    Note you must have a valid nurbsPlane selection for this function
    """
    for eachSel in cmds.ls(sl=True):
        name = '%s_polyCollide_geo' % eachSel.split('NurbsIntersect')[0]
        cmds.nurbsToPoly(eachSel,
                         n='%s_collider' % eachSel,
                         format=0,
                         pt=1,
                         pc=200,
                         ch=True)
        cmds.select('%s_collider' % eachSel, r=True)
        mel.eval('makeCollideNCloth;')
        cmds.rename('nRigid1', '%s_collider_nRigid' % eachSel)
        _cleanupPolyPlane(polyPlane='%s_collider_nRigid' % eachSel)
示例#7
0
def funcLoftIsoparm():
	global uniformCKB
	global meshRib
	SurfaceLoftRibbon = cmds.loft( listIsoparm, u = uniformCKB , ss = resRib, rn = 0, ch  = True, \
	name = nameCurveSelect +'Loft' )
	
	# if check the option extrude Ribbon
	if thickness :
		#cmds.editDisplayLayerMembers( 'SurfaceRibLayer', v )
		meshRib = cmds.nurbsToPoly(SurfaceLoftRibbon[0], format = 3, \
			name = 'Ribbon' + nameCurveSelect, ch = True )
def extendPoly(*args):
    """does the polyextension by grabbing the curve, offsetting it and then lofting. Then converts the nurbs surface to polys"""

    #make sure a curve is selected
    selection = cmds.ls(sl=True)
    if selection:
        sel = selection[0]
        shape = cmds.listRelatives(sel, s=True)[0]
        type = cmds.objectType(shape)
        name = cmds.textFieldGrp("name", q=True, tx=True)
        hisGrp = cmds.checkBox("history", q=True, v=True)
        hisPoly = cmds.checkBox("polyHistory", q=True, v=True)

        if type== "nurbsCurve":
            #offset the curb
            distance = cmds.floatFieldGrp("curbFFG", q=True, v1=True)
            # bump = cmds.checkBox("bumpCB", q=True, v=True)
            pos = cmds.checkBox("curbCB", q=True, v=True)
            if pos == 0:
                dist = distance * -1
            else:
                dist = distance
            U = cmds.intFieldGrp("UDivIFG", q=True, v1=True)
            V = cmds.intFieldGrp("VDivIFG", q=True, v1=True)

            origCrv = cmds.rename(sel, "%s_inner_CRV"%name)
            outCurve = cmds.offsetCurve(origCrv, d=dist, n="%s_outer_CRV"%name)
            midCurve = cmds.offsetCurve(origCrv, d=dist/2, n="%s_mid_CRV"%name)
            # if bump:
            #     cmds.xform(midCurve, ws=True, r=True, t=(0,5,0))

            cmds.select(cl=True)

            lofted = cmds.loft(origCrv, midCurve, outCurve)[0]
            loft = cmds.rename(lofted, "%s_lofted"%name)

            polygon = cmds.nurbsToPoly(loft, pt=1, ch=hisPoly, f=2, un=U, vn=V)[0]
            poly = cmds.rename(polygon, "%s_poly"%name)

            curbGrp = cmds.group(empty=True)
            grp = cmds.rename(curbGrp, "%s_History_GRP"%name)

            # cmds.rename(poly, "polyCurb")

            cmds.parent(loft, outCurve, midCurve, origCrv, grp)

            cmds.setAttr("%s.v"%grp, 0)
            if not hisGrp:
                cmds.delete(grp)

        else:
            cmds.warning("That's not a curve! You need to select a curve!")
    else:
        cmds.warning("You haven't selected anything!")
def volumeComponentSelectionList(mesh,volume):
	'''
	'''
	# Check mesh
	if not mc.objExists(mesh):
		raise Exception('Mesh object "'+mesh+'" does not exist!!')
		
	# Check volume
	if not mc.objExists(volume):
		raise Exception('Volume object "'+volume+'" does not exist!!')
	
	# Get volume type
	volumeShape = volume
	if mc.objectType(volumeShape) == 'transform':
		volumeShape = mc.listRelatives(volume,s=True,ni=True)
		if not volumeShape: raise Exception('Volume object "'+mesh+'" does not exist!!')
		else: volumeShape = volumeShape[0]
	volumeType = mc.objectType(volumeShape)
	# Convert to polygon volume if necessary
	nurbsToPolyConvert = []
	if volumeType == 'nurbsSurface':
		nurbsToPolyConvert = mc.nurbsToPoly(volumeShape,ch=0,f=1,pt=1,ft=0.01,mel=0.001,d=0.1)
		nurbsToPolyShape = mc.listRelatives(nurbsToPolyConvert,s=True,ni=True)
		volumeShape = nurbsToPolyShape[0]
	
	# Create funtion set for volume object
	volumeObj = glTools.utils.base.getMDagPath(volumeShape)
	volumeFn = OpenMaya.MFnMesh(volumeObj)
	
	# Get bounding box
	volumeBBox = OpenMaya.MFnDagNode(volumeObj).boundingBox()
	volumeBBox.transformUsing(volumeObj.inclusiveMatrix())
	
	# Get mesh vertices
	pntList = glTools.utils.base.getMPointArray(mesh)
	
	# Build selection list
	sel = []
	point = OpenMaya.MPoint()
	normal = OpenMaya.MVector()
	for i in range(pntList.length()):
		if not volumeBBox.contains(pntList[i]): continue
		volumeFn.getClosestPointAndNormal(pntList[i],point,normal)
		dotVal = normal * (point-pntList[i]).normal()
		if dotVal > 0.0: sel.append(mesh+'.vtx['+str(i)+']')
	
	# Clean up
	if nurbsToPolyConvert: mc.delete(nurbsToPolyConvert)
	
	# Return result
	return sel
示例#10
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
示例#11
0
def getCenterCurve():
    edges=mc.ls(sl=1)
    loftCurves=[]
    for i in edges:
        obj=i.split('.')[0]
        edgeID=int(i.split('.')[1].split('[')[1].split(']')[0])
        edgeLoop=mc.polySelect(obj,el=edgeID)
        loftCurves.append(mc.polyToCurve(form=2,degree=1)[0])
    mc.loft(loftCurves[0],loftCurves[1],ch=0,u=1,c=0,ar=1,d=1,ss=2,rn=0,po=0,rsn=1,n='NLoftPlane')
    loftPlane=mc.nurbsToPoly('NLoftPlane',mnd=1,ch=0,f=3,pt=0,pc=200,chr=0.1,ft=0.01,mel=0.001,d=0.1,ut=1,un=3,vt=1,vn=3,uch=0,ucr=0,cht=0.2,es=0,ntr=0,mrt=0,uss=1)[0]
    edgeLoop=mc.polySelect(loftPlane,el=2)
    centerCurve=mc.polyToCurve(form=2,degree=1)[0]
    mc.rebuildCurve(centerCurve,ch=0,rpo=1,rt=0,end=1,kr=0,kcp=1,kep=0,kt=0,s=16,d=3,tol=0.01);mc.DeleteHistory(centerCurve)
    mc.delete('NLoftPlane',loftPlane,loftCurves)
    mc.setAttr(centerCurve+'.overrideEnabled',1)
    mc.setAttr(centerCurve+'.overrideColor',16)
    loftCurves=[]
示例#12
0
def volumeComponentSelection(mesh,volume):
	'''
	Build component selection from volume.
	@param mesh: Geometry to build component selection from.
	@type mesh: str
	@param volume: Volume shape to build component selection from.
	@type volume: str
	'''
	# ==========
	# - Checks -
	# ==========
		
	# Check Mesh
	if not mc.objExists(mesh):
		raise Exception('Mesh object "'+mesh+'" does not exist!!')
		
	# Check Volume
	if not mc.objExists(volume):
		raise Exception('Volume object "'+volume+'" does not exist!!')
	
	# Get Volume Type
	volumeShape = volume
	if mc.objectType(volumeShape) == 'transform':
		volumeShape = mc.listRelatives(volume,s=True,ni=True)
		if not volumeShape: raise Exception('Volume object "'+mesh+'" does not exist!!')
		else: volumeShape = volumeShape[0]
	volumeType = mc.objectType(volumeShape)
	
	# Convert to Polygon Volume (if necessary)
	nurbsToPolyConvert = None
	if volumeType == 'nurbsSurface':
		nurbsToPolyConvert = mc.nurbsToPoly(volumeShape,ch=0,f=1,pt=1,ft=0.01,mel=0.001,d=0.1)
		nurbsToPolyShape = mc.listRelatives(nurbsToPolyConvert,s=True,ni=True)
		volumeShape = nurbsToPolyShape[0]
	
	# ==========================
	# - Build Volume Selection -
	# ==========================
	
	# Create Funtion Set for Volume Mesh
	volumeFn = glTools.utils.mesh.getMeshFn(volume)
	
	# Get Bounding Box
	volumeBBox = glTools.utils.base.getMBoundingBox(volume)
	
	# Get Vertices
	pntList = glTools.utils.base.getMPointArray(mesh)
	
	# Build Selection List
	sel = []
	point = OpenMaya.MPoint()
	normal = OpenMaya.MVector()
	for i in range(pntList.length()):
		if not volumeBBox.contains(pntList[i]): continue
		volumeFn.getClosestPointAndNormal(pntList[i],point,normal)
		dotVal = normal * (point-pntList[i]).normal()
		if dotVal > 0.0: sel.append(mesh+'.vtx['+str(i)+']')
	
	# ===========
	# - Cleanup -
	# ===========
	
	if nurbsToPolyConvert: mc.delete(nurbsToPolyConvert)
	
	# =================
	# - Return Result -
	# =================
	
	return sel
示例#13
0
def createConveyerBeltSet(meshName, firstEdgeIndex, secondEdgeIndex):

    firstEdges = cmds.polySelectSp(meshName + '.e[%d]' % firstEdgeIndex,
                                   loop=1)
    secondEdges = cmds.polySelectSp(meshName + '.e[%d]' % secondEdgeIndex,
                                    loop=1)

    cmds.select(firstEdges)
    firstCurve = cmds.polyToCurve(form=2,
                                  degree=3,
                                  n=meshName + '_loopCurve_First')[0]
    cmds.select(secondEdges)
    secondCurve = cmds.polyToCurve(form=2,
                                   degree=3,
                                   n=meshName + '_loopCurve_Second')[0]

    firstCurveShape = sgModelDag.getShape(firstCurve)
    secondCurveShape = sgModelDag.getShape(secondCurve)

    firstSpans = cmds.getAttr(firstCurveShape + '.spans')
    secondSpans = cmds.getAttr(secondCurveShape + '.spans')

    firstTangent = sgModelCurve.getTangentAtParam(firstCurveShape, 0.0)
    firstParamPoint = sgModelCurve.getPointAtParam(firstCurveShape, 0.0)
    secondParam = sgModelCurve.getParamAtPoint(secondCurveShape,
                                               firstParamPoint)
    secondTangent = sgModelCurve.getTangentAtParam(secondCurveShape,
                                                   secondParam)

    if firstTangent * secondTangent < 0:
        cmds.reverseCurve(secondCurve, ch=1, rpo=1)

    firstPointers = sgRigCurve.createRoofPointers(firstCurve, firstSpans)
    secondPointers = sgRigCurve.createRoofPointers(secondCurve, secondSpans)

    fPos = cmds.xform(firstPointers[0], q=1, ws=1, t=1)

    minDistPointer = secondPointers[0]
    minDist = 1000000000.0
    for secondPointer in secondPointers:
        sPos = cmds.xform(secondPointer, q=1, ws=1, t=1)
        dist = (fPos[0] - sPos[0])**2 + (fPos[1] - sPos[1])**2 + (fPos[2] -
                                                                  sPos[2])**2
        if dist < minDist:
            minDistPointer = secondPointer
            minDist = dist

    offset = int(minDistPointer.split('_')[-1])

    crvs = []
    for i in range(len(firstPointers)):
        firstPointer = firstPointers[i]
        secondPointer = '_'.join(secondPointers[i].split('_')[:-1]) + '_%d' % (
            (i + offset) % firstSpans)

        crv = sgRigCurve.createCurveOnTargetPoints(
            [firstPointer, secondPointer])
        crv = cmds.rename(crv, meshName + '_line_%d' % i)
        crvs.append(crv)

    cmds.select(crvs)
    loftSurf = cmds.loft(n=meshName + '_loft')[0]
    resultObject = cmds.nurbsToPoly(loftSurf,
                                    mnd=1,
                                    ch=1,
                                    f=3,
                                    pt=0,
                                    pc=200,
                                    chr=0.9,
                                    ft=0.01,
                                    mel=0.001,
                                    d=0.1,
                                    ut=1,
                                    un=3,
                                    vt=1,
                                    vn=3,
                                    uch=0,
                                    ucr=0,
                                    cht=0.2,
                                    es=0,
                                    ntr=0,
                                    mrt=0,
                                    uss=1,
                                    n=meshName + '_conveyorBelt')
    crvGrp = cmds.group(crvs, n=meshName + '_lines')
    conveyorRig = cmds.group(firstCurve,
                             secondCurve,
                             crvGrp,
                             loftSurf,
                             resultObject,
                             meshName,
                             n=meshName + '_conveyorRig')

    import sgRigAttribute
    sgRigAttribute.addAttr(conveyorRig, ln='offset', k=1)
    cmds.connectAttr(conveyorRig + '.offset', firstCurve + '.roofValue')
    cmds.connectAttr(conveyorRig + '.offset', secondCurve + '.roofValue')

    cmds.setAttr(conveyorRig + '.v', 0)
示例#14
0
def create_follicles_on_surf():

    nrb_patch = ""
    jnt_sel = []

    if not cmds.ls(selection=True):
        raise Exception(
            "Nothing selected! Select a NURBS Curve, or NURBS Curve and NURBS Surface."
        )

    selected = cmds.ls(selection=True)

    jnt_sel = cmds.ls(selection=True, type="joint")
    nrb_patch_surf = cmds.listRelatives(selected,
                                        type="nurbsSurface",
                                        children=1)[0]
    nrb_patch = cmds.listRelatives(nrb_patch_surf, parent=1)[0]

    # Set up groups for ribbon rig
    parent_grp = cmds.group(name="RibbonRig", empty=True)
    for group_name in ["Joints", "Follicle"]:
        cmds.group(name="{}_GRP".format(group_name),
                   empty=True,
                   parent=parent_grp)

    # Convert nrb_patch to poly mesh
    nrb_poly_patch = cmds.nurbsToPoly(nrb_patch, constructionHistory=False)[0]

    # Get the NURBS Max V Range, so that follicles can be placed directly in the centre of it along the surface
    nrb_v_max = cmds.getAttr("{}.minMaxRangeV".format(
        cmds.listRelatives(nrb_patch, shapes=True)[0]))[0][1]
    nrb_v_mid = nrb_v_max / 2

    countup = 0
    for jnt in jnt_sel:
        flc_name = jnt.replace("_JNT", "_FLC")

        new_follicle = create_follicle(nrb_patch, 0, .5)
        cmds.rename(cmds.listRelatives(new_follicle, parent=1)[0], flc_name)
        cmds.parent(flc_name, "Follicle_GRP")

        # Create nearestPointOnPoly node
        nearest_point_node = cmds.createNode("nearestPointOnMesh")

        # Attach new poly mesh and temp locator into nearestPointOnMesh node
        cmds.connectAttr("{}.worldMesh".format(nrb_poly_patch),
                         "{}.inMesh".format(nearest_point_node))
        cmds.connectAttr("{}.t".format(jnt),
                         "{}.inPosition".format(nearest_point_node))

        paramu = cmds.getAttr("{}.parameterU".format(nearest_point_node))

        # Make sure that paramu is never 0 or 1, as this can result in weird rotations
        if paramu == 0:
            paramu = 0.002
        if paramu == 1:
            paramu = 0.998

        # Set the follicles' u position
        cmds.setAttr("{}.parameterU".format(flc_name), paramu)

        # Cleanup
        cmds.delete(nearest_point_node)

        cmds.parentConstraint(flc_name, jnt, maintainOffset=True)

        cmds.parent(jnt, "Joints_GRP")

    cmds.delete(nrb_poly_patch)
    cmds.parent(nrb_patch, parent_grp)
示例#15
0
def createConveyerBeltSet( meshName, firstEdgeIndex, secondEdgeIndex ):
    
    firstEdges = cmds.polySelectSp( meshName+'.e[%d]' % firstEdgeIndex,  loop=1 )
    secondEdges = cmds.polySelectSp( meshName+'.e[%d]' % secondEdgeIndex, loop=1 )
    
    cmds.select( firstEdges )
    firstCurve  = cmds.polyToCurve( form=2, degree=3, n=meshName+'_loopCurve_First' )[0]
    cmds.select( secondEdges )
    secondCurve = cmds.polyToCurve( form=2, degree=3, n=meshName+'_loopCurve_Second' )[0]
    
    firstCurveShape = sgModelDag.getShape( firstCurve )
    secondCurveShape = sgModelDag.getShape( secondCurve )
    
    firstSpans  = cmds.getAttr( firstCurveShape +'.spans' )
    secondSpans = cmds.getAttr( secondCurveShape+'.spans' )
    
    firstTangent = sgModelCurve.getTangentAtParam( firstCurveShape, 0.0 )
    firstParamPoint = sgModelCurve.getPointAtParam( firstCurveShape, 0.0 )
    secondParam = sgModelCurve.getParamAtPoint( secondCurveShape, firstParamPoint )
    secondTangent = sgModelCurve.getTangentAtParam( secondCurveShape, secondParam )
    
    if firstTangent * secondTangent < 0:
        cmds.reverseCurve( secondCurve, ch = 1, rpo = 1 )
    
    firstPointers = sgRigCurve.createRoofPointers( firstCurve, firstSpans )
    secondPointers = sgRigCurve.createRoofPointers( secondCurve, secondSpans )
    
    fPos = cmds.xform( firstPointers[0], q=1, ws=1, t=1 )
    
    minDistPointer = secondPointers[0]
    minDist = 1000000000.0
    for secondPointer in secondPointers:
        sPos = cmds.xform( secondPointer, q=1, ws=1, t=1 )
        dist = (fPos[0]-sPos[0])**2+(fPos[1]-sPos[1])**2+(fPos[2]-sPos[2])**2
        if dist < minDist:
            minDistPointer = secondPointer
            minDist = dist
    
    offset = int( minDistPointer.split( '_' )[-1] )
    
    crvs = []
    for i in range( len( firstPointers ) ):
        firstPointer = firstPointers[i]
        secondPointer = '_'.join( secondPointers[i].split( '_' )[:-1] ) + '_%d' %( (i + offset)%firstSpans )
        
        crv = sgRigCurve.createCurveOnTargetPoints( [firstPointer, secondPointer] )
        crv = cmds.rename( crv, meshName+'_line_%d' % i )
        crvs.append( crv )
        
    cmds.select( crvs )
    loftSurf = cmds.loft( n=meshName+'_loft' )[0]
    resultObject = cmds.nurbsToPoly( loftSurf ,mnd=1 ,ch=1,f=3,pt=0,pc=200,chr=0.9,ft=0.01,mel=0.001, d=0.1, 
                                    ut=1, un=3, vt=1, vn=3, uch=0, ucr=0, cht=0.2, es=0,ntr=0,mrt=0, uss=1, n=meshName+'_conveyorBelt' )
    crvGrp = cmds.group( crvs, n=meshName+'_lines' )
    conveyorRig = cmds.group( firstCurve, secondCurve, crvGrp, loftSurf, resultObject, meshName, n=meshName+'_conveyorRig' )
    
    import sgRigAttribute
    sgRigAttribute.addAttr( conveyorRig, ln='offset', k=1 )
    cmds.connectAttr( conveyorRig+'.offset', firstCurve+'.roofValue' )
    cmds.connectAttr( conveyorRig+'.offset', secondCurve+'.roofValue' )

    cmds.setAttr( conveyorRig+'.v', 0 )
示例#16
0
def m_polyretopo():

    selected = mc.ls(sl=True)
    pRlist = []
    #create set or add into existing one original flatten mesh
    if mc.objExists('OrigFlatMeshes_set'):
        mc.sets(selected, forceElement='OrigFlatMeshes_set')
    else:
        newSet1 = cmds.sets(name='OrigFlatMeshes_set')
        mc.sets(selected, forceElement='OrigFlatMeshes_set')
    for u in selected:
        mc.select(u)
        mc.ConvertSelectionToEdgePerimeter(u)
        mc.planarSrf(n='Surface' +
                     str(u))  # reikia variable pavadinima ivesti jog sukurtu
        mc.nurbsToPoly(ch=True,
                       f=0,
                       pt=1,
                       pc=1000,
                       chr=0.9,
                       ft=0.01,
                       mel=0.001,
                       d=0.1,
                       n='nurbsToPoly' + str(u))
        chpoly = mc.polyEvaluate(shell=True)
        #check if mesh has several pieces
        if chpoly > 1:
            mc.SeparatePolygon()
        mc.DeleteHistory()
        chlist = mc.ls(sl=True)
        #check if mesh is in the group
        if len(chlist) > 1:
            mc.pickWalk(direction='up')
            mc.Ungroup()
        o = mc.ls(sl=True)
        if len(o) == 1:
            mc.polyRetopo('nurbsToPoly' + str(u))
            mc.rename('Retopo_mesh_01')
            #add new polyRetopo mesh to list
            pRsl = mc.ls(sl=True)
            pRlist.append(pRsl)
        else:
            for y in o:
                mc.select(y, r=True)
                mc.polyRetopo(y)
                mc.sets(fe='initialShadingGroup')
                mc.rename('Retopo_mesh_01')
                #add new polyRetopo mesh to list
                pRsl = mc.ls(sl=True)
                pRlist.append(pRsl)

        sfrlist = mc.select('Surface' + str(u))
        mc.Delete(sfrlist)
        #hide Original mesh accordingly if check box is on or off
        mc.select('OrigFlatMeshes_set')
        listObjectsInSet = mc.ls(sl=True)
        for objOnSet in listObjectsInSet:
            visValue = mc.getAttr(str(objOnSet) + '.visibility')
            checkBoxStatus = mc.checkBox('fMOrigCheckBox', q=True, v=True)
            if visValue is False or checkBoxStatus is True:
                mc.setAttr((objOnSet + '.visibility'), 0)
def GetNurbsVertexCount(surfaceName):
    TempGeo = mc.nurbsToPoly(surfaceName, f=3, ch=False)
    geoVertCont = mc.polyEvaluate(TempGeo, v=True)
    mc.delete(TempGeo)
    return geoVertCont
示例#18
0
def fMImport_Retopo(arg):

    path = mc.textField(
        'fMtextField',
        q=True,
        fi=True,
    )
    if path.find('.obj') < 0:
        mc.error('select OBJ mesh')
    else:
        belist = mc.ls(type="transform")
        test = mc.file(path,
                       i=True,
                       type="OBJ",
                       ra=True,
                       mergeNamespacesOnClash=True,
                       namespace="OrigFlatten",
                       options="mo=1,lo=0")
        aflist = mc.ls(type="transform")
        #seperate pieces
        origFMlist_root = list(set(aflist) - set(belist))
        origFMlist_temp = []
        origFMlist = []
        for fm in origFMlist_root:
            mc.select(fm)
            mc.SeparatePolygon()
            mc.DeleteHistory()
            sep_list = []
            sep_templist = mc.ls(sl=True)
            for sep in sep_templist:
                mc.select(sep)
                sep_list.append(mc.rename('OrigFlatten_01'))
            mc.pickWalk(direction='up')
            mc.Ungroup()
            origFMlist_temp.append(sep_list)
        for x in origFMlist_temp:
            for y in x:
                origFMlist.append(y)

        #create set or add into existing one original flatten mesh
        if mc.objExists('OrigFlatMeshes_set'):
            mc.sets(origFMlist, forceElement='OrigFlatMeshes_set')
        else:
            newSet1 = cmds.sets(name='OrigFlatMeshes_set')
            mc.sets(origFMlist, forceElement='OrigFlatMeshes_set')
        #polyRetopo imported meshes
        pRlist = []
        for u in origFMlist:
            mc.select(u)
            mc.ConvertSelectionToEdgePerimeter(u)
            mc.planarSrf(
                n='Surface' +
                str(u))  # reikia variable pavadinima ivesti jog sukurtu
            mc.nurbsToPoly(ch=True,
                           f=0,
                           pt=1,
                           pc=1000,
                           chr=0.9,
                           ft=0.01,
                           mel=0.001,
                           d=0.1,
                           n='nurbsToPoly' + str(u))
            chpoly = mc.polyEvaluate(shell=True)
            #check if mesh has several pieces
            if chpoly > 1:
                mc.SeparatePolygon()
            mc.DeleteHistory()
            chlist = mc.ls(sl=True)
            #check if mesh is in the group
            if len(chlist) > 1:
                mc.pickWalk(direction='up')
                mc.Ungroup()
            o = mc.ls(sl=True)
            if len(o) == 1:
                mc.polyRetopo('nurbsToPoly' + str(u))
                mc.rename('Retopo_mesh_01')
                #add new polyRetopo mesh to list
                pRsl = mc.ls(sl=True)
                pRlist.append(pRsl)
            else:
                for y in o:
                    mc.select(y, r=True)
                    mc.polyRetopo(y)
                    mc.sets(fe='initialShadingGroup')
                    mc.rename('Retopo_mesh_01')
                    #add new polyRetopo mesh to list
                    pRsl = mc.ls(sl=True)
                    pRlist.append(pRsl)

            sfrlist = mc.select('Surface' + str(u))
            mc.Delete(sfrlist)
            #hide Original mesh accordingly if check box is on or off
            mc.select('OrigFlatMeshes_set')
            listObjectsInSet = mc.ls(sl=True)
            for objOnSet in listObjectsInSet:
                visValue = mc.getAttr(str(objOnSet) + '.visibility')
                checkBoxStatus = mc.checkBox('fMOrigCheckBox', q=True, v=True)
                if visValue is False or checkBoxStatus is True:
                    mc.setAttr((objOnSet + '.visibility'), 0)
        #transfer uvs from Marvelous mesh to new polyRetopo meshes
        iterpRlist = iter(pRlist)
        for fm in origFMlist:
            mc.select(fm)
            mc.select(next(iterpRlist), add=True)
            mc.transferAttributes(transferPositions=0,
                                  transferNormals=0,
                                  transferUVs=2,
                                  transferColors=0,
                                  sampleSpace=0,
                                  sourceUvSpace="map1",
                                  targetUvSpace="map1",
                                  searchMethod=3,
                                  flipUVs=0,
                                  colorBorders=1)
        #adapt faceCount of new created polyRetopo meshes
        mc.select(d=True)
        for pRmesh in pRlist:
            mc.select(pRmesh, add=True)
        adaptPoly()
示例#19
0
def drawBranch(iteration, cX, cY, cZ, nrX, nrY, nrZ, radius, length,old_circle,ShereBool):
	if(iteration < branches):
		iteration = iteration + 1
		print("iteration= "+str(iteration))
		#Draw circle and extrude based on parameters
		R=radius*math.fabs(math.sin(iteration))
		R=radius+iteration-math.fabs(iteration)
		R=10-iteration
		circle( nr=(nrX, nrY, nrZ), c=(cX, cY, cZ), r=radius)
		shape = cmds.ls(sl=True)[0]
		circleReffArr.append(shape)
		cmds.select( clear=True )
		cmds.select( old_circle, add=True )
		cmds.select( shape, add=True )
		cmds.loft( c=0, ch=1, d=3, ss=1, rsn=True, ar=1, u=1, rn=0, po=0)
		extrudedSurface = cmds.ls(sl=True)[0]
		print("nrX= "+str(nrX)+" nrY= "+str(nrY)+" nrZ= "+str(nrZ))
		if(0==True):
			cmds.polySphere(createUVs=2, sy=20, ch=1, sx=20, r=radius*10)
			SpherePoly = cmds.ls(sl=True)[0]
			cmds.move( cX, cY, cZ, SpherePoly, absolute=True )
		#extrudedSurface=extrude (shape, et=0, d= (nrX, nrY, nrZ), l= length)
		#extrudedSurface=extrude (shape, extrudeType=0, d= (nrX, nrY, nrZ), l= length,polygon=1)
		#extrudedSurface=extrude (shape, extrudeType=0, d= (nrX, nrY, nrZ), l= length)
		
		cmds.nurbsToPoly(extrudedSurface, uss=1, ch=1, ft=0.01, d=0.1, pt=0, f=0, mrt=0, mel=0.001, ntr=0, vn=3, pc=1000, chr=0.9, un=3, vt=1, ut=1, ucr=0, cht=0.01, mnd=1, es=0, uch=0)
		delete(extrudedSurface)
		#print("extrudedSurface= "+str(extrudedSurface))
		extrudedPoly = cmds.ls(sl=True)[0]
		print("extrudedPoly= "+str(extrudedPoly))
		cmds.polyCloseBorder(extrudedPoly, ch=1)# Close Holl
		hollface = cmds.ls(sl=True)[0]
		print("hollface= "+str(hollface))
		cmds.polyTriangulate(hollface, ch=1)
		cmds.select(extrudedPoly)
		#cmds.polyClean(extrudedPoly)
		#cmds.eval('polyCleanupArgList 4 { "0","1","1","1","1","1","1","1","0","1e-05","0","1e-05","0","1e-05","0","1","1","0" };')
		#Delete the base circle, keep the cylinder
		#delete(shape)
		
		#Define direction vector and normalize
		vector = MVector(nrX, nrY, nrZ)
		vector.normalize()
		
		cX = cX + (length*vector.x)
		cY = cY + (length*vector.y)
		cZ = cZ + (length*vector.z)
		
		randX = random.randint(0, 1)*2 -1
		randY = random.randint(0, 1)*2 -1
		randZ = random.randint(0, 1)*2 -1
		
		#Random direction vector
		#For X, Y, Z, ( -1 or 1 )*angle + (randint from -angleVariance to +angleVariance)
		nrX = nrX + ((angle*randX) + random.randint(0, angleVariance*2) - angleVariance)/100.0
		nrY = nrY + ((angle*randY) + random.randint(0, angleVariance*2) - angleVariance)/100.0
		nrZ = nrZ + ((angle*randZ) + random.randint(0, angleVariance*2) - angleVariance)/100.0
		
		#Length and Radius based on factor + (randint from -variance to +variance)
		length = length * (lengthFactor + (random.randint(0, lengthVariance*2*100)/100.0) - lengthVariance)
		radius = radius * (radiusFactor + (random.randint(0, radiusVariance*2*100)/100.0) - radiusVariance)
		
		#Draw first branch
		drawBranch(iteration, cX, cY, cZ, nrX, nrY, nrZ, radius, length,shape,False)
		#drawBranch(iteration, cX, cY, cZ, 0, 1, 0, radius, length,shape,False)
		#--------------------
		#Use opposite base angle from previous branch
		nrX = nrX + ((angle*randX*-1) + random.randint(0, angleVariance*2) - angleVariance)/100.0
		nrY = nrY + ((angle*randY*-1) + random.randint(0, angleVariance*2) - angleVariance)/100.0
		nrZ = nrZ + ((angle*randZ*-1) + random.randint(0, angleVariance*2) - angleVariance)/100.0

		length = length * (lengthFactor + (random.randint(0, lengthVariance*2*100)/100.0) - lengthVariance)
		radius = radius * (radiusFactor + (random.randint(0, radiusVariance*2*100)/100.0) - radiusVariance)
		
		#Draw second branch
		drawBranch(iteration, cX, cY, cZ, nrX, nrY, nrZ, radius, length,shape,True)
示例#20
0
def volumeComponentSelectionList(mesh, volume):
    '''
	'''
    # Check mesh
    if not mc.objExists(mesh):
        raise Exception('Mesh object "' + mesh + '" does not exist!!')

    # Check volume
    if not mc.objExists(volume):
        raise Exception('Volume object "' + volume + '" does not exist!!')

    # Get volume type
    volumeShape = volume
    if mc.objectType(volumeShape) == 'transform':
        volumeShape = mc.listRelatives(volume, s=True, ni=True)
        if not volumeShape:
            raise Exception('Volume object "' + mesh + '" does not exist!!')
        else:
            volumeShape = volumeShape[0]
    volumeType = mc.objectType(volumeShape)
    # Convert to polygon volume if necessary
    nurbsToPolyConvert = []
    if volumeType == 'nurbsSurface':
        nurbsToPolyConvert = mc.nurbsToPoly(volumeShape,
                                            ch=0,
                                            f=1,
                                            pt=1,
                                            ft=0.01,
                                            mel=0.001,
                                            d=0.1)
        nurbsToPolyShape = mc.listRelatives(nurbsToPolyConvert,
                                            s=True,
                                            ni=True)
        volumeShape = nurbsToPolyShape[0]

    # Create funtion set for volume object
    volumeObj = glTools.utils.base.getMDagPath(volumeShape)
    volumeFn = OpenMaya.MFnMesh(volumeObj)

    # Get bounding box
    volumeBBox = OpenMaya.MFnDagNode(volumeObj).boundingBox()
    volumeBBox.transformUsing(volumeObj.inclusiveMatrix())

    # Get mesh vertices
    pntList = glTools.utils.base.getMPointArray(mesh)

    # Build selection list
    sel = []
    point = OpenMaya.MPoint()
    normal = OpenMaya.MVector()
    for i in range(pntList.length()):
        if not volumeBBox.contains(pntList[i]): continue
        volumeFn.getClosestPointAndNormal(pntList[i], point, normal)
        dotVal = normal * (point - pntList[i]).normal()
        if dotVal > 0.0: sel.append(mesh + '.vtx[' + str(i) + ']')

    # Clean up
    if nurbsToPolyConvert: mc.delete(nurbsToPolyConvert)

    # Return result
    return sel
示例#21
0
def volumeComponentSelection(mesh, volume):
    '''
	Build component selection from volume.
	@param mesh: Geometry to build component selection from.
	@type mesh: str
	@param volume: Volume shape to build component selection from.
	@type volume: str
	'''
    # ==========
    # - Checks -
    # ==========

    # Check Mesh
    if not mc.objExists(mesh):
        raise Exception('Mesh object "' + mesh + '" does not exist!!')

    # Check Volume
    if not mc.objExists(volume):
        raise Exception('Volume object "' + volume + '" does not exist!!')

    # Get Volume Type
    volumeShape = volume
    if mc.objectType(volumeShape) == 'transform':
        volumeShape = mc.listRelatives(volume, s=True, ni=True)
        if not volumeShape:
            raise Exception('Volume object "' + mesh + '" does not exist!!')
        else:
            volumeShape = volumeShape[0]
    volumeType = mc.objectType(volumeShape)

    # Convert to Polygon Volume (if necessary)
    nurbsToPolyConvert = None
    if volumeType == 'nurbsSurface':
        nurbsToPolyConvert = mc.nurbsToPoly(volumeShape,
                                            ch=0,
                                            f=1,
                                            pt=1,
                                            ft=0.01,
                                            mel=0.001,
                                            d=0.1)
        nurbsToPolyShape = mc.listRelatives(nurbsToPolyConvert,
                                            s=True,
                                            ni=True)
        volumeShape = nurbsToPolyShape[0]

    # ==========================
    # - Build Volume Selection -
    # ==========================

    # Create Funtion Set for Volume Mesh
    volumeFn = glTools.utils.mesh.getMeshFn(volume)

    # Get Bounding Box
    volumeBBox = glTools.utils.base.getMBoundingBox(volume)

    # Get Vertices
    pntList = glTools.utils.base.getMPointArray(mesh)

    # Build Selection List
    sel = []
    point = OpenMaya.MPoint()
    normal = OpenMaya.MVector()
    for i in range(pntList.length()):
        if not volumeBBox.contains(pntList[i]): continue
        volumeFn.getClosestPointAndNormal(pntList[i], point, normal)
        dotVal = normal * (point - pntList[i]).normal()
        if dotVal > 0.0: sel.append(mesh + '.vtx[' + str(i) + ']')

    # ===========
    # - Cleanup -
    # ===========

    if nurbsToPolyConvert: mc.delete(nurbsToPolyConvert)

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

    return sel