예제 #1
0
 def unlockNormal(self):
     cont = ''
     nodes = cmds.ls(type=('mesh', 'nurbsSurface'))
     if nodes != []:
         cmds.polyNormalPerVertex(nodes, ufn=1)
         cont = u'Unlock Normal 节点: %s\n' % len(nodes)
     return cont
예제 #2
0
def convert_edge_lock():
    sel = cmds.ls(sl=True, l=True)
    meshes = common.search_polygon_mesh(sel, serchChildeNode=False)
    if not meshes:
        return
    for mesh in meshes:
        d_mesh = cmds.duplicate(mesh, rr=True)[0]
        modeling.setSoftEdge(mesh, angle=120)
        cmds.transferAttributes(
            d_mesh,
            mesh,
            flipUVs=0,
            transferPositions=0,
            transferUVs=0,
            sourceUvSpace="map1",
            searchMethod=3,
            transferNormals=1,
            transferColors=0,
            targetUvSpace="map1",
            colorBorders=1,
            sampleSpace=5,
        )
        freeze.main(mesh)
        cmds.polyNormalPerVertex(mesh, ufn=True)
        cmds.delete(d_mesh)
    cmds.select(meshes)
예제 #3
0
def face_normal(face):
    polyface = mc.polyListComponentConversion(face, tvf=True)
    xes = mc.polyNormalPerVertex(polyface, q=True, x=True)
    yes = mc.polyNormalPerVertex(polyface, q=True, y=True)
    zes = mc.polyNormalPerVertex(polyface, q=True, z=True)
    divisor = 1.0 / len(xes)
    return sum(xes) * divisor, sum(yes) * divisor, sum(zes) * divisor
	def HardedgeNormals(self):
		henselVerArray = cmds.ls( selection=True, fl=True )
		if not henselVerArray:
			pass
			print "nothing selected"
			return
		if self.selectlive:
#			print"test: sel islive in HardedgeNormals"
			self.selectlive = False
#			print "self.selectlive", self.selectlive
			cmds.polyNormalPerVertex(ufn=True)
			cmds.select(cmds.polyListComponentConversion( henselVerArray, te=True ))
			cmds.polySoftEdge( a=self.NormalAngle.value() )
#			cmds.polyNormalPerVertex(cmds.polyListComponentConversion( selVerArray, tv=True ),ufn=True)
			cmds.select(henselVerArray)
			self.VecOriginlist = nrmedittool.BuildVecOrigin()
			self.SliderIntensity.setValue(0)
			self.selectlive = True
			return
		else:
#			print"test: sel is not live in HardedgeNormals"
			cmds.polyNormalPerVertex(ufn=True)
			cmds.select(cmds.polyListComponentConversion( henselVerArray, te=True ))
			cmds.polySoftEdge( a=self.NormalAngle.value() )
			cmds.select(henselVerArray)
			self.VecOriginlist = nrmedittool.BuildVecOrigin()
			return
예제 #5
0
def shell_border_edges_to_hard():
    """
    Sets uv border edges on a mesh has hard, and everythign else as soft.
    """
    objList = cmds.ls(sl=True, o=True)
    finalBorder = []

    for subObj in objList:
        cmds.select(subObj, r=True)
        cmds.polyNormalPerVertex(ufn=True)
        cmds.polySoftEdge(subObj, a=180, ch=1)
        cmds.select(subObj + '.map[*]', r=True)

        polySelectBorderShell(borderOnly=True)

        uvBorder = cmds.polyListComponentConversion(te=True, internal=True)
        uvBorder = cmds.ls(uvBorder, fl=True)

        for curEdge in uvBorder:
            edgeUVs = cmds.polyListComponentConversion(curEdge, tuv=True)
            edgeUVs = cmds.ls(edgeUVs, fl=True)

            if len(edgeUVs) > 2:
                finalBorder.append(curEdge)

        cmds.polySoftEdge(finalBorder, a=0, ch=1)

    cmds.select(objList)
예제 #6
0
    def alignToRef(self):
        if len(self.refVerts) == 0:
            cmds.error("Reference vertexes are not defined. Please define ref first.")
        selection = cmds.ls(sl=True, long=True)
        cmds.select(cmds.polyListComponentConversion(toVertex=True), replace=True)
        verts = cmds.filterExpand(sm=31, expand=True, fullPath=True)

        shape = str(self.refVerts[0]).split(".")[0]
        refTransform = cmds.listRelatives(shape, parent=True, path=True, fullPath=True)[0]

        shape = str(verts[0]).split(".")[0]
        objTransform = cmds.listRelatives(shape, parent=True, path=True, fullPath=True)[0]
        objTransformMatrixInverse = getTransformMatrix(objTransform).inverse()

        refRot = cmds.xform(refTransform, q=True, ws=True, ro=True)
        refAngle = om.MEulerRotation(math.radians(refRot[0]),
                                     math.radians(refRot[1]),
                                     math.radians(refRot[2]),
                                     om.MEulerRotation.kXYZ)
        for vert in verts:
            refVertIndex = self.findNearestVertIndex(vert)
            refNormal = cmds.polyNormalPerVertex(self.refVerts[refVertIndex], q=True, xyz=True)

            vec = om.MVector(refNormal[0], refNormal[1], refNormal[2])
            refNormal = vec.rotateBy(refAngle)
            normalVector = om.MVector(refNormal[0], refNormal[1], refNormal[2])
            newVector = normalVector * objTransformMatrixInverse
            # Assuming normals are equal for all triangles at this vert, and using the first triple.
            cmds.polyNormalPerVertex(vert, xyz=(newVector[0], newVector[1], newVector[2]))
        cmds.select(selection, r=True)
예제 #7
0
def allign(vtx1, vtx2, local_y_flip=False):
    """Alligns the normal of vtx1 to the normal of vtx2

    Args:
        vtx1 (str): name of the source vertex
        vtx2 (str): name of the destination vertex
        local_y_flip (bool): whether to flip source object along it's Y axis once alligned

    Returns:
        None
    """

    # Matching rotation of face normal
    obj_name = vtx1.split(".")[0]
    vec1 = cmds.polyNormalPerVertex(vtx1, query=True, xyz=True)[:3]
    vec2 = cmds.polyNormalPerVertex(vtx2, query=True, xyz=True)[:3]
    rotation_matrix = get_rotation_matrix(vec1, vec2)
    euler_radians = rotation_matrix_to_euler(rotation_matrix)
    r_x, r_y, r_z = [math.degrees(i) for i in euler_radians]
    cmds.rotate(r_x, r_y, r_z, [obj_name])

    if local_y_flip:
        cmds.scale(1, -1, 1, [obj_name], os=True, r=True)

    # Matching face position
    v1_x, v1_y, v1_z = get_position(vtx1)
    v2_x, v2_y, v2_z = get_position(vtx2)
    cmds.move(v1_x,
              v1_y,
              v1_z,
              "{}.scalePivot".format(obj_name),
              "{}.rotatePivot".format(obj_name),
              rpr=True)
    cmds.move(v2_x, v2_y, v2_z, [obj_name], rpr=True, ws=True)
예제 #8
0
파일: ui.py 프로젝트: Italic-/maya-prefs
    def initGeometry(self):
        selection = m.ls(sl=True)

        meshes = m.ls(
            selection=True,
            long=True,
            dagObjects=True,
            allPaths=True,
            type='mesh',
            noIntermediate=True
        )
        if meshes:
            for mesh in meshes:
                transform = com.getParent(mesh)
                if transform:
                    self.backupers.append(backuper.Backuper(mesh, transform))
                    m.polyNormalPerVertex(mesh, ufn=True)
                    m.polySoftEdge(transform, a=180, ch=False)

                    geomProcessor = geom_processor.GeomProcessor(mesh)
                    geomProcessor.params = Parameters
                    self.processors.append(geomProcessor)
        else:
            pm.confirmDialog(
                title='Error',
                message='Invalid selection. Select at least one mesh.',
                button=['OK'],
                defaultButton='OK',
                icon='critical'
            )
            return

        m.select(selection, r=True)
예제 #9
0
파일: ui.py 프로젝트: jubeyjose/maya-prefs
    def initGeometry(self):
        selection = m.ls(sl=True)

        meshes = m.ls(selection=True,
                      long=True,
                      dagObjects=True,
                      allPaths=True,
                      type='mesh',
                      noIntermediate=True)
        if meshes:
            for mesh in meshes:
                transform = com.getParent(mesh)
                if transform:
                    self.backupers.append(backuper.Backuper(mesh, transform))
                    m.polyNormalPerVertex(mesh, ufn=True)
                    m.polySoftEdge(transform, a=180, ch=False)

                    geomProcessor = geom_processor.GeomProcessor(mesh)
                    geomProcessor.params = Parameters
                    self.processors.append(geomProcessor)
        else:
            pm.confirmDialog(
                title='Error',
                message='Invalid selection. Select at least one mesh.',
                button=['OK'],
                defaultButton='OK',
                icon='critical')
            return

        m.select(selection, r=True)
예제 #10
0
파일: helpers.py 프로젝트: shdwdln/pbTools
def uvShellHardEdges():
    '''
    Sets uv border edges on a mesh has hard, and everythign else as soft.
    '''
    objList = cmds.ls(sl=True, o=True)
    finalBorder = []

    for subObj in objList:
        cmds.select(subObj, r=True)
        cmds.polyNormalPerVertex(ufn=True)
        cmds.polySoftEdge(subObj, a=180, ch=1)
        cmds.select(subObj + '.map[*]', r=True)

        polySelectBorderShell(borderOnly=True)

        uvBorder = cmds.polyListComponentConversion(te=True, internal=True)
        uvBorder = cmds.ls(uvBorder, fl=True)

        for curEdge in uvBorder:
            edgeUVs = cmds.polyListComponentConversion(curEdge, tuv=True)
            edgeUVs = cmds.ls(edgeUVs, fl=True)

            if len(edgeUVs) > 2:
                finalBorder.append(curEdge)

        cmds.polySoftEdge(finalBorder, a=0, ch=1)

    cmds.select(objList)
예제 #11
0
def run():	
	#get selected edgeloop
	edgeLoop = cmds.ls(selection=True)
	#get verticles in the edge loop
	vertLoop = cmds.polyListComponentConversion(edgeLoop, fromEdge=True, toVertex=True)
	#sort individual verticles into a list
	vertLoop = cmds.ls(vertLoop, flatten=True)

	#open undo chunk so entire operation is a single action
	cmds.undoInfo(openChunk = True)

	#soften the mesh normals
	mesh = cmds.listRelatives(parent=1)
	cmds.polySoftEdge(mesh, angle=180)

	#run on each vertex on the edgeloop
	for vert in vertLoop:
		#unlock the normal of the vertex
		cmds.polyNormalPerVertex(vert, unFreezeNormal=True)
		#get the normals of the vertex on the loop
		vertNormals = list(cmds.polyNormalPerVertex(vert, query=True, xyz=True))
		#get only the first three vectors
		vertNormals = vertNormals[:3]

		# select the neighboring verticles using the declared function below
		vertNeighbors(vert, vertLoop)

		#set their normal angle to match the vertex on the loop
		cmds.polyNormalPerVertex(xyz=vertNormals)

	#reselect the edge loops
	cmds.select(edgeLoop)

	#close undo chunk, operation is done
	cmds.undoInfo(closeChunk = True)
예제 #12
0
    def fix_invalid(cls, instance):
        """Unlocks all normals on the meshes in this instance."""
        from maya import cmds

        invalid = cls.get_invalid(instance)
        for mesh in invalid:
            cmds.polyNormalPerVertex(mesh, unFreezeNormal=True)
            """
예제 #13
0
def normal_lock():
    '''法线锁定
    '''
    meshs = cmds.ls(type="mesh", io=0)
    lockmesh = []
    if meshs:
        for _mesh in meshs:
            cmds.polyNormalPerVertex(_mesh, ufn=1)
예제 #14
0
def softEdgeSelection():
    """
    unlock normals and soft edge
    """
    sel = cmds.ls(sl=True)
    for node in sel:
        cmds.polyNormalPerVertex(node, ufn=True)
        cmds.polySoftEdge(node, angle=normalAngle)
    def testStaticMeshPolyNormals(self):

        # create a polygon cube
        polyName = 'polyCube'
        polyShapeName = 'polyCubeShape'
        MayaCmds.polyCube(sx=1,
                          sy=1,
                          sz=1,
                          name=polyName,
                          constructionHistory=False)

        # add the necessary props
        MayaCmds.select(polyShapeName)
        MayaCmds.addAttr(longName='SubDivisionMesh',
                         attributeType='bool',
                         defaultValue=False)
        MayaCmds.addAttr(longName='noNormals',
                         attributeType='bool',
                         defaultValue=False)
        MayaCmds.addAttr(longName='flipNormals',
                         attributeType='bool',
                         defaultValue=False)

        # tweek some normals
        MayaCmds.select(polyName + '.vtxFace[2][1]', replace=True)
        MayaCmds.polyNormalPerVertex(xyz=(0.707107, 0.707107, 0))
        MayaCmds.select(polyName + '.vtxFace[7][4]', replace=True)
        MayaCmds.polyNormalPerVertex(xyz=(-0.707107, 0.707107, 0))

        # write to file
        self.__files.append(util.expandFileName('staticPolyNormalsTest.abc'))
        MayaCmds.AbcExport(j='-root %s -f %s' % (polyName, self.__files[-1]))

        # read back from file
        MayaCmds.AbcImport(self.__files[-1], mode='import')

        self.failIf(
            MayaCmds.listAttr('polyCube1|polyCubeShape').count('noNormals') !=
            0)

        # make sure the normals are the same
        shapeObj = getObjFromName('polyCube1|polyCubeShape')
        fnMesh = OpenMaya.MFnMesh(shapeObj)
        numFaces = fnMesh.numPolygons()
        for faceIndex in range(0, numFaces):
            vertexList = OpenMaya.MIntArray()
            fnMesh.getPolygonVertices(faceIndex, vertexList)
            numVertices = vertexList.length()
            for v in range(0, numVertices):
                vertexIndex = vertexList[v]
                normal = OpenMaya.MVector()
                fnMesh.getFaceVertexNormal(faceIndex, vertexIndex, normal)
                vtxFaceAttrName = '.vtxFace[%d][%d]' % (vertexIndex, faceIndex)
                MayaCmds.select(polyName + vtxFaceAttrName, replace=True)
                oNormal = MayaCmds.polyNormalPerVertex(query=True, xyz=True)
                self.failUnlessAlmostEqual(normal[0], oNormal[0], 4)
                self.failUnlessAlmostEqual(normal[1], oNormal[1], 4)
                self.failUnlessAlmostEqual(normal[2], oNormal[2], 4)
예제 #16
0
파일: modeling.py 프로젝트: shrimo/dmptools
def unlockAndHarden():
    """
    comverts selected components to vertices, unlocks and harden
    """
    if cmds.ls(sl=True):
        newSel = cmds.polyListComponentConversion(ff=True, fe=True, fuv=True, fvf=True, tv=True)
        cmds.select(newSel)
        cmds.polyNormalPerVertex(ufn=True)
        cmds.polySoftEdge(angle=0, ch=False)
	def setvtxtoorigin(self):
		vtxFaceCountFloat = len(self.OriginVectorDic) - 1
		ovdindex = self.OriginVectorDic['index']
		if not ovdindex:
			pass
		else:
			for x in range(0,vtxFaceCountFloat):
				currentvtxFace = ovdindex[x]
				currentvtxOVal = self.OriginVectorDic[ovdindex[x]]
				cmds.polyNormalPerVertex(currentvtxFace, xyz = currentvtxOVal)
예제 #18
0
def cp_vertex_normal():
    """
    Select your source vertex normal and destination, then run the script.
    """
    vsel = cmds.ls(sl=True, fl=True)
    src = vsel[0]
    dest = vsel[1]
    srcNorm = cmds.polyNormalPerVertex(vsel[0], q=True, xyz=True)
    cmds.polyNormalPerVertex(dest,
                             xyz=(srcNorm[0], srcNorm[1], srcNorm[2]),
                             edit=True)
예제 #19
0
def toAlembic(parameters, arguments):
	"""
	Converts an Obj file to Alembic file.
	
	:param parameters: Command line parameters.
	:type parameters: object
	:param arguments: Command line arguments.
	:type arguments: object
	:return: Definition success.
	:rtype: bool
	"""

	inputFile = parameters.inputFile
	if inputFile is None:
		sys.stderr.write("!> {0} | No input file provided!\n".format(inspect.getmodulename(__file__)))
		return

	if not os.path.exists(inputFile):
		sys.stderr.write("!> {0} | '{1}' file doesn't exists'!\n".format(inspect.getmodulename(__file__), inputFile))
		return

	outputFile = os.path.abspath(parameters.outputFile if parameters.outputFile else re.sub(r"\.\w+$", ".abc", inputFile))

	exportAll = parameters.exportAll

	frameRange = parameters.frameRange
	try:
		frameIn, frameOut = frameRange.split("-")
	except ValueError:
		sys.stderr.write("!> {0} | The frame range format could not be determined!\n".format(inspect.getmodulename(__file__)))
		return
	
	not cmds.pluginInfo("AbcExport", q=True, loaded=True) and cmds.loadPlugin("AbcExport")	

	cmds.file(inputFile, o=True)

	# Processing ".obj" file normals.
	if re.search(r"\.obj$", inputFile, flags=re.IGNORECASE):
		for mesh in cmds.ls(type="mesh", long=True):
			cmds.polyNormalPerVertex(mesh, ufn=True)
			cmds.polySoftEdge(mesh, a=180, ch=False)

	if exportAll:
		jobCommand = "-frameRange {0} {1} -uvWrite -file {2}".format(frameIn, frameOut, outputFile)
	else:
		rootNodes = list(set([getRoot(mesh) for mesh in cmds.ls(type="mesh", long=True)]))
		rootFlags = " ".join(["-root {0}".format(rootNode) for rootNode in rootNodes])
		jobCommand = "-frameRange {0} {1} -uvWrite {2} -file {3}".format(frameIn, frameOut, rootFlags, outputFile)
	
	sys.stderr.write("{0} | Exporting to 'Alembic' with following job command: '{1}'\n".format(inspect.getmodulename(__file__), jobCommand))
	cmds.AbcExport(j=jobCommand)
	return True
예제 #20
0
파일: cleanup.py 프로젝트: jonntd/glTools
def unlockNormals(meshList=[]):
    '''
	'''
    # Check meshList
    meshList = getMeshList(meshList)
    if not meshList: return []

    # Unlock Normals
    for mesh in meshList:
        mc.polyNormalPerVertex(mesh, ufn=True)

    # Return result
    return meshList
    def testStaticMeshPolyNormals(self):

        # create a polygon cube
        polyName = 'polyCube'
        polyShapeName = 'polyCubeShape'
        MayaCmds.polyCube( sx=1, sy=1, sz=1, name=polyName,
            constructionHistory=False)

        # add the necessary props
        MayaCmds.select(polyShapeName)
        MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool',
            defaultValue=False)
        MayaCmds.addAttr(longName='noNormals', attributeType='bool',
            defaultValue=False)
        MayaCmds.addAttr(longName='flipNormals', attributeType='bool',
            defaultValue=False)

        # tweek some normals
        MayaCmds.select(polyName+'.vtxFace[2][1]', replace=True)
        MayaCmds.polyNormalPerVertex(xyz=(0.707107, 0.707107, 0))
        MayaCmds.select(polyName+'.vtxFace[7][4]', replace=True)
        MayaCmds.polyNormalPerVertex(xyz=(-0.707107, 0.707107, 0))

        # write to file
        self.__files.append(util.expandFileName('staticPolyNormalsTest.abc'))
        MayaCmds.AbcExport(j='-root %s -f %s' % (polyName, self.__files[-1]))

        # read back from file
        MayaCmds.AbcImport(self.__files[-1], mode='import')


        self.failIf(MayaCmds.listAttr('polyCube1|polyCubeShape').count('noNormals') != 0)

        # make sure the normals are the same
        shapeObj = getObjFromName('polyCube1|polyCubeShape')
        fnMesh = OpenMaya.MFnMesh(shapeObj)
        numFaces = fnMesh.numPolygons()
        for faceIndex in range(0, numFaces):
            vertexList = OpenMaya.MIntArray()
            fnMesh.getPolygonVertices(faceIndex, vertexList)
            numVertices = vertexList.length()
            for v in range(0, numVertices):
                vertexIndex = vertexList[v]
                normal = OpenMaya.MVector()
                fnMesh.getFaceVertexNormal(faceIndex, vertexIndex, normal)
                vtxFaceAttrName = '.vtxFace[%d][%d]' % (vertexIndex, faceIndex)
                MayaCmds.select(polyName+vtxFaceAttrName, replace=True)
                oNormal = MayaCmds.polyNormalPerVertex( query=True, xyz=True)
                self.failUnlessAlmostEqual(normal[0], oNormal[0], 4)
                self.failUnlessAlmostEqual(normal[1], oNormal[1], 4)
                self.failUnlessAlmostEqual(normal[2], oNormal[2], 4)
예제 #22
0
def smartNormals(reverse=0):
    '''Changes the vertex normals on a edge by edge basis to that of the larger faces vertex normals'''
    #We start a new undo chunk to capture all the work
    cmds.undoInfo( ock=1 )
    try:
        sel = selection()
        edgeLengthList = getEdgeLengths(sel.selection.keys())
        for key in sorted(edgeLengthList, reverse=1):
            key = key[-1]
            #Find the dag node name to be used in the polyNormalPerVertex command
            dagName = key.split('.')[0]
            cmds.select(dagName)
            vertices = cmds.ls(cmds.polyListComponentConversion(key,tv=1),fl=1)

            #Get the edges faces and check to make sure it finds two otherwise skip it because its a boarder edge
            faces = cmds.ls(cmds.polyListComponentConversion(key,tf=1),fl=1)
            if len(faces) == 2 :
                #Get the area of the two faces to compare their size
                face1Num = int(faces[0].split('[')[-1].split(']')[0])
                area1 = getFaceArea(face1Num)

                face2Num = int(faces[1].split('[')[-1].split(']')[0])
                area2 = getFaceArea(face2Num)
                if area1 > area2 :
                    if reverse:
                        largerFace , smallerFace = face2Num , face1Num
                    else:
                        largerFace , smallerFace = face1Num , face2Num
                else:
                    if reverse:
                        largerFace , smallerFace = face1Num , face2Num
                    else:
                        largerFace , smallerFace = face2Num , face1Num

                print "larger face - " + str(largerFace) + "  || smaller face - " + str(smallerFace)
                #For the two verts attached to the edge set the smaller faces vertex normals to the cooresponding larger faces vertex normals
                #This command is run on the vertex per face so that we can set each one independantly
                #EXAMPLE: We run it on pCube1.vtxFace [0] [1]  which only sets the vertex 0 attached to face 1
                #instead of all the faces vertex 0 is attached to if we used pCube1.vtx[0] as the compoenent
                for vert in vertices :
                    vertNum = int(vert.split('[')[-1].split(']')[0])
                    #Get the larger faces cooresponding vertex normal
                    normal = cmds.polyNormalPerVertex((dagName + '.vtxFace[' + str(vertNum) + '][' + str(largerFace) + ']'),q=1,xyz=1)
                    #Set the smaller faces cooresponding vertex normal
                    cmds.polyNormalPerVertex((dagName + '.vtxFace[' + str(vertNum) + '][' + str(smallerFace) + ']'),xyz=normal)
                    print "cmds.polyNormalPerVertex((" + dagName + '.vtxFace[' + str(vertNum) + '][' + str(smallerFace) + ']),xyz=' + str(normal) + ')'
        sel.restoreSelection()
    except Exception, e:
        traceback.print_exc()
예제 #23
0
def GetVertexNormal(vtx):
    cmds.select(vtx)
    count = len(cmds.polyNormalPerVertex(q=True, x=True))
    x = cmds.polyNormalPerVertex(q=True, x=True)
    y = cmds.polyNormalPerVertex(q=True, y=True)
    z = cmds.polyNormalPerVertex(q=True, z=True)
    avg = [0, 0, 0]
    dif = 1.0 / count
    for cnt in range(count):
        avg[0] += x[cnt]
        avg[1] += y[cnt]
        avg[2] += z[cnt]
    for cnt in range(3):
        avg[cnt] *= dif
    return avg
예제 #24
0
def averageVertexNormal(verts):
    for v in verts:
        faces = cmds.polyInfo(v, vertexToFace=True)[0].strip()
        faces = re.findall(r'\d+', faces)[1:]
        vn = [0, 0, 0]
        for f in faces:
            fn = cmds.polyInfo('%s.f[%s]' % (v.split('.', 1)[0], f),
                               faceNormals=True)[0].strip()
            fn = fn.split(' ')[-3:]
            fn = [float(n) for n in fn]
            vn = map(lambda x, y: x + y, vn, fn)
        vn = om.MVector(vn[0], vn[1], vn[2])
        vn.normalize()
        vn = (vn.x, vn.y, vn.z)
        cmds.polyNormalPerVertex(v, xyz=vn)
예제 #25
0
def unlockVertexNormals(meshList=[]):
    """
    Unlocked vertex normals
    @param meshList: List of meshes to unlocked normals on. If empty, check all mesh objects in the scene.
    @type meshList: list
    """
    # Check meshList
    if not meshList: meshList = getMeshList(meshList)
    if not meshList: return []

    # Unlock Normals
    for mesh in meshList: cmds.polyNormalPerVertex(mesh, ufn=True)

    # Return Result
    return meshList
예제 #26
0
def unlockVertexNormals(meshList=[]):
	'''
	Unlocked vertex normals
	@param meshList: List of meshes to unlocked normals on. If empty, check all mesh objects in the scene.
	@type meshList: list
	'''
	# Check meshList
	if not meshList: meshList = getMeshList(meshList)
	if not meshList: return []
	
	# Unlock Normals
	for mesh in meshList: mc.polyNormalPerVertex(mesh,ufn=True)
	
	# Return Result
	return meshList
예제 #27
0
def facetoVertNRM():  # FIXME fix usage for faces bordering hard edges.
    '''
    sets the vertex normals of the verts contained in a face to that of the face.
    '''
    fs = cmds.filterExpand(sm=34)
    cmds.select(cl=True)
    for f in fs:
        cmds.select(f, r=True)
        normals = cmds.polyInfo(faceNormals=True)
        buf = str(normals).split()
        plane = range(3)
        plane[0] = float(buf[2])
        plane[1] = float(buf[3])
        plane[2] = float(buf[4].rstrip('\\n\']'))
        vtx = cmds.polyListComponentConversion(f, ff=True, tv=True)
        cmds.polyNormalPerVertex(vtx, xyz=[plane[0], plane[1], plane[2]])
예제 #28
0
def getMeshVertexData( mesh ):
  returnData = []
  exportObject = 'bwExportObject'
  cmds.duplicate( mesh, n=exportObject )
  cmds.polyTriangulate(exportObject)
  numOfFaces = cmds.polyEvaluate(exportObject,  f=True )
  for i in xrange(0, numOfFaces):
    faceSelect = exportObject + '.f[' + str(i) + ']'
    fVertices = [] 
    fVertices = cmds.polyListComponentConversion(faceSelect, ff = True, tvf = True)
    fVertices = cmds.filterExpand(fVertices, sm = 70, ex = True)
    print fVertices
    for vertex in fVertices:
      faceDict = {}
      vName = cmds.polyListComponentConversion(vertex, fvf = True, tv = True)
      xyz = []
      xyz = cmds.xform(vName, q = True, os = True, t = True)
      faceDict['x'] = round(xyz[0], 2)
      faceDict['y'] = round(xyz[1], 2)
      faceDict['z'] = round(xyz[2], 2)
      normal = []
      normal = cmds.polyNormalPerVertex(vertex, q = True, xyz = True)
      faceDict['xN'] = round(normal[0], 2)
      faceDict['yN'] = round(normal[1], 2)
      faceDict['zN'] = round(normal[2], 2)
      # vuv = []
      # vuv = cmds.polyListComponentConversion(vertex, fvf = True, tuv = True)
      # uvCoords = []
      # uvCoords = cmds.polyEditUV(vuv[0], q = True, u = True, v = True)
      # faceDict['u'] = round(uvCoords[0], 2)
      # faceDict['v'] = round(uvCoords[0], 2)
      returnData.append(faceDict)
  cmds.delete(exportObject)
  return json.dumps(returnData)
예제 #29
0
def averageNormals():
    try:
        cmds.polyNormalPerVertex(ufn=True)
        cmds.polyAverageNormal(
                                prenormalize=False,
                                allowZeroNormal=False,
                                postnormalize=True,
                                distance=0.1,
                                replaceNormalXYZ=(1,0,0))
    except:
        cmds.polyAverageNormal(
                                prenormalize=False,
                                allowZeroNormal=False,
                                postnormalize=True,
                                distance=0.1,
                                replaceNormalXYZ=(1,0,0))
예제 #30
0
파일: cleanup.py 프로젝트: auqeyjf/glTools
def checkLockedVertexNormals(meshList=[]):
    """
	Check for locked vertex normals
	@param meshList: List of meshes to check for locked normals. If empty, check all mesh objects in the scene.
	@type meshList: list
	"""
    # Check meshList
    meshList = getMeshList(meshList)
    if not meshList:
        return []

    # Check Locked Normals
    lockedNormalList = []
    for mesh in meshList:

        # Shapes
        meshShapes = mc.listRelatives(mesh, s=True, ni=True, pa=True)
        if not meshShapes:
            continue
        for meshShape in meshShapes:

            # Check Normals
            if True in mc.polyNormalPerVertex(meshShape + ".vtx[*]", q=True, fn=True):
                lockedNormalList.append(mesh)
                continue

                # Return Result
    return lockedNormalList
예제 #31
0
def checkLockedVertexNormals(meshList=[]):
    """
    Check for locked vertex normals
    @param meshList: List of meshes to check for locked normals. If empty, check all mesh objects in the scene.
    @type meshList: list
    """
    # Check meshList
    meshList = getMeshList(meshList)
    if not meshList: return []

    # Check Locked Normals
    lockedNormalList = []
    for mesh in meshList:

        # Shapes
        meshShapes = cmds.listRelatives(mesh, s=True, ni=True, pa=True)
        if not meshShapes: continue
        for meshShape in meshShapes:

            # Check Normals
            if True in cmds.polyNormalPerVertex(meshShape + '.vtx[*]',
                                                q=True,
                                                fn=True):
                lockedNormalList.append(mesh)
                continue

    # Return Result
    return lockedNormalList
예제 #32
0
def setOrigNormalSoft( target ):
    
    ioMeshs = sgModelDag.getIntermediateObjects( target )
    
    for ioMesh in ioMeshs:
        mesh = cmds.createNode( 'mesh' )
        meshObj = sgModelDag.getTransform( mesh )
        cmds.connectAttr( ioMesh+'.outMesh', mesh+'.inMesh' )
        cmds.refresh()
        cmds.disconnectAttr( ioMesh+'.outMesh', mesh+'.inMesh' )
        cmds.polyNormalPerVertex( mesh, ufn=1 )
        cmds.polySoftEdge( mesh, a=180, ch=1 )
        cmds.connectAttr( mesh+'.outMesh', ioMesh+'.inMesh' )
        cmds.refresh()
        cmds.disconnectAttr( mesh+'.outMesh', ioMesh+'.inMesh' )
        cmds.delete( meshObj )
	def getFaceNormals( vertex ):
		# vertex normal name
		fvtx = cmds.polyListComponentConversion( vertex, fv=True, tvf=True )
		allFvtx = cmds.filterExpand( fvtx, expand=True, sm=70 )	
		
		# Face index
		# vtxFaces = Vertex.getFaceVertexIndex(allFvtx)
		'''
		# There could be duplicate tags, so the dictionary will over write data!
		tempNormals = {}
		
		for i, curFvtx in enumerate(allFvtx):
			normalCoords = cmds.polyNormalPerVertex( curFvtx, q=True, xyz=True )
			curFace = vtxFaces[i]
			tempNormals[curFvtx] = normalCoords
		return tempNormals
		'''
		# normals = []
		normals = {}
		for i, curFvtx in enumerate(allFvtx):
			normalCoords = cmds.polyNormalPerVertex( curFvtx, q=True, xyz=True )
			# curFace = vtxFaces[i]
			
			normals[curFvtx] = normalCoords
			# normals.append( normalCoords )		
		return allFvtx, normals
예제 #34
0
    def getFaceNormals(vertex):
        # vertex normal name
        fvtx = cmds.polyListComponentConversion(vertex, fv=True, tvf=True)
        allFvtx = cmds.filterExpand(fvtx, expand=True, sm=70)

        # Face index
        # vtxFaces = Vertex.getFaceVertexIndex(allFvtx)
        '''
		# There could be duplicate tags, so the dictionary will over write data!
		tempNormals = {}
		
		for i, curFvtx in enumerate(allFvtx):
			normalCoords = cmds.polyNormalPerVertex( curFvtx, q=True, xyz=True )
			curFace = vtxFaces[i]
			tempNormals[curFvtx] = normalCoords
		return tempNormals
		'''
        # normals = []
        normals = {}
        for i, curFvtx in enumerate(allFvtx):
            normalCoords = cmds.polyNormalPerVertex(curFvtx, q=True, xyz=True)
            # curFace = vtxFaces[i]

            normals[curFvtx] = normalCoords
            # normals.append( normalCoords )
        return allFvtx, normals
예제 #35
0
파일: helpers.py 프로젝트: shdwdln/pbTools
def facetoVertNRM():  # FIXME fix usage for faces bordering hard edges.
    '''
    sets the vertex normals of the verts contained in a face to that of the face.
    '''
    fs = cmds.filterExpand(sm=34)
    cmds.select(cl=True)
    for f in fs:
        cmds.select(f, r=True)
        normals = cmds.polyInfo(faceNormals=True)
        buf = str(normals).split()
        plane = range(3)
        plane[0] = float(buf[2])
        plane[1] = float(buf[3])
        plane[2] = float(buf[4].rstrip('\\n\']'))
        vtx = cmds.polyListComponentConversion(f, ff=True, tv=True)
        cmds.polyNormalPerVertex(vtx, xyz=[plane[0], plane[1], plane[2]])
예제 #36
0
def setOrigNormalSoft(target):

    ioMeshs = sgModelDag.getIntermediateObjects(target)

    for ioMesh in ioMeshs:
        mesh = cmds.createNode('mesh')
        meshObj = sgModelDag.getTransform(mesh)
        cmds.connectAttr(ioMesh + '.outMesh', mesh + '.inMesh')
        cmds.refresh()
        cmds.disconnectAttr(ioMesh + '.outMesh', mesh + '.inMesh')
        cmds.polyNormalPerVertex(mesh, ufn=1)
        cmds.polySoftEdge(mesh, a=180, ch=1)
        cmds.connectAttr(mesh + '.outMesh', ioMesh + '.inMesh')
        cmds.refresh()
        cmds.disconnectAttr(mesh + '.outMesh', ioMesh + '.inMesh')
        cmds.delete(meshObj)
예제 #37
0
    def has_locked_normals(mesh):
        """Return whether a mesh node has locked normals"""
        from maya import cmds

        return any(
            cmds.polyNormalPerVertex("{}.vtxFace[*][*]".format(mesh),
                                     query=True,
                                     freezeNormal=True))
    def has_locked_normals(self, mesh):

        mesh_vertexface = cmds.polyListComponentConversion(mesh, toVertexFace=True)
        locked_normals = cmds.polyNormalPerVertex(mesh_vertexface, q=1, freezeNormal=True)
        if any(locked_normals):
            return True
        else:
            return False
예제 #39
0
def NormalAction(fs):
    for f in fs:
        node = f.split('.')[0]
        pi = cmds.polyInfo(f, fn=True)
        vss = cmds.polyInfo(f, fv=True)
        fn = re.findall(r"[\w.-]+", pi[0])
        # convert the string to array with regular expression
        vssre = re.findall(r"[\w]+", vss[0])

        vs = []

        for index in range(2, len(vssre)):
            vs.append("{0}.vtx[{1}]".format(node, vssre[index]))

        cmds.select(vs, r=True)
        cmds.polyNormalPerVertex(xyz=(float(fn[2]), float(fn[3]),
                                      float(fn[4])))
예제 #40
0
def setmesh(nodename):
    cmds.select(nodename)

    exts = getnames()
    va, na, pa, uva = exts
    nva, nna, npa, nuva = [nodename+"."+ext for ext in exts]

    # Vertices first.
    vl = cmds.xform(nodename+'.vtx[:]', q=True, os=True, t=True)
    cmds.addAttr(longName=va, dt="string")
    cmds.setAttr(nva, str(vl), type="string")

    # Polygons (called faces in Maya).
    pcnt = cmds.polyEvaluate(f=True)
    cmds.addAttr(longName=pa, dt="string")
    pll = []
    for x in range(pcnt):
        fvl = cmds.polyInfo(nodename+".f[%i]" % x, faceToVertex=True)
        p = fvl[0].split()[2:]
        pll += ["[" + ",".join(p) + "]"]
    pll = "[" + ",".join(pll) + "]"
    cmds.setAttr(npa, pll, type="string")
    pl = eval(pll)

    # Normals and UVs (needs polygons).
    nll = []
    # UVs are only used if user has set a non-default UV-set
    # name (use right-click menu).
    cmds.select(nodename)
    hasUv = (cmds.polyUVSet(q=True, allUVSets=True) != ['map1'])
    uvcnt = 0
    #print("Set is: "+str(cmds.polyUVSet(q=True, allUVSets=True)))
    cmds.addAttr(longName=na, dt="string")
    if hasUv:
        cmds.addAttr(longName=uva, dt="string")
        uvll = []
    for polyidx in range(pcnt):
        poly = pl[polyidx]
        for vtxidx in poly:
            sel = nodename+".vtxFace["+str(vtxidx)+"]["+str(polyidx)+"]"
            cmds.select(sel)
            n = cmds.polyNormalPerVertex(q=True, xyz=True);
            nll += n
            if hasUv:
                uv_names = cmds.polyListComponentConversion(fromVertexFace=True, toUV=True)
                if uv_names:
                    uv_name = uv_names[0]
                    cmds.select(uv_name)
                    uv = cmds.polyEditUV(q=True)
                    uvll += uv
                    uvcnt += 1
    #print "Normals: "+str(nll)
    cmds.setAttr(nna, str(nll), type='string')
    if hasUv:
        #print "UVs: "+str(uvll)
        cmds.setAttr(nuva, str(uvll), type='string')

    return (1, len(vl)/3+len(pl)+len(nll)/3+uvcnt)
예제 #41
0
def createPatchMesh(vertices, normals):
  width = len(vertices)
  height = len(vertices[0])
  
  cmds.polyPlane(n="tp", sx=width-1, sy=height-1, ax=[0, 0, 1])
  
  for j in range(height):
    for i in range(width):
      cmds.select("tp.vtx[%s]" % (j*width+i), r=True)
      cmds.move(vertices[i][j][0], vertices[i][j][1], vertices[i][j][2], a=True)
      cmds.polyNormalPerVertex(xyz=normals[i][j].tolist())

  normalZ = cmds.polyInfo("tp.f[0]", fn=True)[0].split()[-1]
  if normalZ[0]=="-":
    cmds.polyNormal("tp", normalMode=0, userNormalMode=0, ch=1);
  
  cmds.rename("tp", "patch1")
  cmds.select(cl=True)
예제 #42
0
    def build(self):
        """
        Build the osm file
        """
        print 'Building'

        # first get a group to put everything in
        bld_group = '_buildings'

        if not cmds.ls(bld_group):
            cmds.group(empty=True, n=bld_group)

        # create a something to store the number of the building we are on
        num_buildings = 0

        # go through our ways and find the buildings
        for way in self.ways:
            if 'building' in way.tags:

                positions = []

                for node_id in way.nodes:
                    node = self.nodes[node_id]
                    pos_xy = self.get_relative_coordinates(
                        [float(node.lat), float(node.lon)])
                    positions.append((pos_xy[0], pos_xy[1], 0))

                building = cmds.polyCreateFacet(p=positions)

                centre_pos = self.get_centre_pos(positions)
                cmds.xform(building[0], ws=True, piv=centre_pos)

                # make sure all the vertices have the correct normals
                for i in range(cmds.polyEvaluate(building[0], vertex=True)):
                    cmds.select('{}.vtx[{}]'.format(building[0], i))
                    cmds.polyNormalPerVertex(xyz=(0, 0, 1))

                new_building = cmds.rename(
                    building[0], 'building_{0:03d}'.format(num_buildings + 1))
                cmds.parent(new_building, bld_group)

                num_buildings += 1

        print 'Build {} buildings!'.format(num_buildings)
예제 #43
0
def extrude_building(building=None, height=None):
    """
    Given an object will extrude it upwards
    """

    building_face = '{}.f[0]'.format(building)

    if not height:
        building_scale = math.ceil(
            cmds.polyEvaluate(building_face, worldArea=True) / 1000000)
        if building_scale > 12:
            building_scale = 12

        num_stories = math.floor(random.uniform(1, 3)) * building_scale

        height = 450 * num_stories

    cmds.polyExtrudeFacet(building_face, kft=True, ltz=height, sma=0)
    cmds.polyNormalPerVertex(building, ufn=True)
    def has_locked_normals(self, mesh):

        mesh_vertexface = cmds.polyListComponentConversion(mesh,
                                                           toVertexFace=True)
        locked_normals = cmds.polyNormalPerVertex(mesh_vertexface,
                                                  q=1,
                                                  freezeNormal=True)
        if any(locked_normals):
            return True
        else:
            return False
예제 #45
0
def fixNormals(*arg):
    ''' Fix normal for every selected objects'''
    if commonTools.testSelection() == None:
        cmds.warning('Nothing is selected')
    else:
        sel = commonTools.testSelection()
        selAD = cmds.listRelatives(sel, ad=True)
        selShapes = cmds.listRelatives(sel, shapes=True,
                                       fullPath=True)  # List selected shapes
        for i in selAD:  # Fix normal angles
            cmds.polyNormalPerVertex(i, ufn=True)  # Unlock normals
            cmds.polySetToFaceNormal(i)  # Set to face
            cmds.polySoftEdge(i, a=60)  # Set normal angle to 60
        for i in selShapes:  # Disable opposite normals
            cmds.setAttr('%s.doubleSided' % i, 0)
            cmds.setAttr('%s.opposite' % i, 0)
            cmds.setAttr('%s.doubleSided' % i, 1)
        cmds.select(clear=True)
        cmds.select(sel, r=True)
        cmds.inViewMessage(amg='Done ! Remember to delete history.',
                           pos='midCenter',
                           fade=True)
예제 #46
0
def run():
    #get selected edgeloop
    edgeLoop = cmds.ls(selection=True)
    #get verticles in the edge loop
    vertLoop = cmds.polyListComponentConversion(edgeLoop,
                                                fromEdge=True,
                                                toVertex=True)
    #sort individual verticles into a list
    vertLoop = cmds.ls(vertLoop, flatten=True)

    #open undo chunk so entire operation is a single action
    cmds.undoInfo(openChunk=True)

    #soften the mesh normals
    mesh = cmds.listRelatives(parent=1)
    cmds.polySoftEdge(mesh, angle=180)

    #run on each vertex on the edgeloop
    for vert in vertLoop:
        #unlock the normal of the vertex
        cmds.polyNormalPerVertex(vert, unFreezeNormal=True)
        #get the normals of the vertex on the loop
        vertNormals = list(cmds.polyNormalPerVertex(vert, query=True,
                                                    xyz=True))
        #get only the first three vectors
        vertNormals = vertNormals[:3]

        # select the neighboring verticles using the declared function below
        vertNeighbors(vert, vertLoop)

        #set their normal angle to match the vertex on the loop
        cmds.polyNormalPerVertex(xyz=vertNormals)

    #reselect the edge loops
    cmds.select(edgeLoop)

    #close undo chunk, operation is done
    cmds.undoInfo(closeChunk=True)
예제 #47
0
    def LsUVMap(self):
        Locator_nodes = mc.ls(sl=True, o=True)
        if len(Locator_nodes) != 1:
            mc.confirmDialog(m=u"请选择一个物体!")
            return
        mc.select(Locator_nodes[0], r=True)
        #当前值没有冻结的冻结
        mc.polyNormalPerVertex(ufn=True)
        #选择所有的UV点
        mc.select((Locator_nodes[0] + '.map[*]'), r=True)
        #显示所有修改的部件转变成线
        uvBorder = mc.polyListComponentConversion(te=True, internal=True)
        #查找uvBorder中的线
        uvBorder = mc.ls(uvBorder, fl=True)
        for curEdge in uvBorder:
            edgeUVs = mc.polyListComponentConversion(curEdge, tuv=True)
            edgeUVs = mc.ls(edgeUVs, fl=True)
            if len(edgeUVs) > 2:
                self.finalBorder.append(curEdge)
        mc.select(self.finalBorder, r=True)


#selectUVEdges().LsUVMap()
예제 #48
0
def getVertexNormals(vertex):
    """Returns a list of MVector objects for each normal associated with the
	specified vertex (one per attached face)
	"""

    mc.select(vertex, replace=True)
    n = mc.polyNormalPerVertex(query=True, xyz=True)
    normalLs = []
    for i in range(0, len(n),
                   3):  # Pack returned values into a list of MVector objects
        normal = MVector(n[i], n[i + 1], n[i + 2])
        normalLs.append(normal)

    return normalLs
예제 #49
0
	def getFaceNormals( vertex ):
		# vertex normal name
		fvtx = cmds.polyListComponentConversion( vertex, fv=True, tvf=True )
		allFvtx = cmds.filterExpand( fvtx, expand=True, sm=70 )	
		
		# Face index
		vtxFaces = Vertex.getFaceVertexIndex(allFvtx)
		
		tempNormals = {}
		for i, curFvtx in enumerate(allFvtx):
			normalCoords = cmds.polyNormalPerVertex( curFvtx, q=True, xyz=True )
			curFace = vtxFaces[i]
			tempNormals[curFace] = normalCoords
		return tempNormals
		'''
예제 #50
0
def solidifyObject(object, height=1, divisions=2, history=True):
	"""
	Solidifies given object.

	:param object: Object.
	:type object: str
	:param height: Extrusion height.
	:type height: float
	:param division: Extrusion divisions.
	:type division: float
	:param history: Keep construction history.
	:type history: bool
	"""

	if hasBorderEdges(object):
		transform = getTransform(object)
		vertices = cmds.ls(cmds.polyListComponentConversion(object, toVertex=True), fl=True)

		barycenters = cmds.xform(vertices, q=True, t=True, ws=True)
		barycenter = getAverageVector([(barycenters[i], barycenters[i + 1], barycenters[i + 2]) for i in range(0, len(barycenters), 3)])

		normals = cmds.polyNormalPerVertex(cmds.polyListComponentConversion(object, toVertexFace=True), q=True, xyz=True)
		normals = [(normals[i], normals[i + 1], normals[i + 2]) for i in range(0, len(normals), 3)]
		averageNormal = vectorMatrixMultiplication(normalize(getAverageVector(normals)), cmds.xform(transform, query=True, matrix=True, worldSpace=True))

		facesCount = cmds.polyEvaluate(object, face=True)
		faces = object + ".f[0:" + str(facesCount - 1) + "]"
		extrude = cmds.polyExtrudeFacet(faces, constructionHistory=1, keepFacesTogether=1, divisions=divisions)
		cmds.setAttr(extrude[0] + ".localTranslateZ", height)
		borderEdges = cmds.polyListComponentConversion(faces, te=True, bo=True)
		cmds.polyMapCut(borderEdges)
		uvs = cmds.polyListComponentConversion(object + ".f[0:" + str(facesCount - 1) + "]", toUV=1)
		cmds.polyEditUV(uvs, u=0, v=-5)

		extendedFaces = cmds.ls(faces, fl=True)
		for i in range(divisions):
			adjacentEdges = cmds.polyListComponentConversion(extendedFaces, ff=True, te=True)
			extendedFaces.extend(cmds.ls(cmds.polyListComponentConversion(adjacentEdges, fe=True, tf=True), fl=True))

		borderFaces = list(set(extendedFaces).difference(set(cmds.ls(faces, fl=True))))
		cmds.select(borderFaces)
		cmds.polyAutoProjection(borderFaces, t=barycenter, ry=getAngle((0, 0, 1), averageNormal), rz=getAngle((1, 0, 0), averageNormal))
		uvs = cmds.polyListComponentConversion(borderFaces, toUV=1)
		cmds.polyEditUV(uvs, u=0, v=-5)

		not history and cmds.delete(object, ch=True)
예제 #51
0
 def getNormal(_vtx):
     vertName = _obj + '.vtx[' + str(_vtx) + ']'
     normTemp = cmds.polyNormalPerVertex(vertName, query=True, xyz=True)
     norms = zip(*[iter(normTemp)]*3)
     #values for averages
     xAve=0
     yAve=0
     zAve=0
     #get average vertex normal
     for i in range (len(norms)):
         xAve += norms[i][0]
         yAve += norms[i][1]
         zAve += norms[i][2]
     leng = len(norms) 
     xAve = xAve/leng
     yAve = yAve/leng
     zAve = zAve/leng
     aveList = [xAve, yAve, zAve]
     return aveList
예제 #52
0
파일: mayaFuncs.py 프로젝트: JFDesigner/MTG
def get_vertex_normals(pObject):
    '''Gathers all the normal directions for all the vertices of a poly object.
    
    Parameters:
        pObject [str] : The name of a polygonal object from the scene.
    
    On Exit:
        Returns a list of all the vertex normals, averaged from each adjacent
        face normal.
    
    '''
    lsVtxNormals = []
    nVtx = cmds.polyEvaluate(pObject, vertex=True)
    for i in range(nVtx):
        xyzNorm = cmds.polyNormalPerVertex('%s.vtx[%d]' % (pObject, i), q=True, xyz=True)
        vtxNormal = [sum([xyzNorm[i] for i in range(0+x, len(xyzNorm), 3)]) / \
                     (len(xyzNorm)/3) for x in range(3)]
        lsVtxNormals.append(vtxNormal)
    return lsVtxNormals
예제 #53
0
    def process(self, instance):

        invalid = list()
        for mesh in cmds.ls(type="mesh", long=True):
            faces = cmds.polyListComponentConversion(mesh, toVertexFace=True)
            if faces:
                locked = cmds.polyNormalPerVertex(faces,
                                                  query=True,
                                                  freezeNormal=True)

                invalid.append(mesh) if any(locked) else None

        # On locked normals, indicate that validation has failed
        # with a friendly message for the user.
        #assert not invalid, (
        #    "Meshes found with locked normals: %s" % invalid)
        if len(invalid) > 0:
            self.log.warning("Meshes found with locked normals: %s" % invalid)
        else:
            self.log.info("The normals of \"%s\" are correct." % instance.data['model'])
예제 #54
0
def getVertexNormal(P):
    '''
    For a given vertex of a polygon mesh, queries the normal for each vertex-face combination and calculates the average vertex normal.
    
    P: input vertex
    '''
    cmds.select(P)
    # query x,y and z-values of the normals of all faces around the vertex
    n = cmds.polyNormalPerVertex( query=True, xyz=True )
    num = len(n)/3
    x = 0
    y = 0
    z = 0
    # calculate average 
    for j in range (0,num):
        x += n[0+3*j]
        y += n[1+3*j]
        z += n[2+3*j]
        vn = numpy.array([[x/num, y/num, z/num]])
        # normalize
        length = numpy.linalg.norm(vn)
        vn = vn/length
    return vn
예제 #55
0
def export():
    get_ui_values()
    selection = cmds.ls(sl=True)
    
    if export_animation:
        frame_range = range(start_frame, end_frame+1)
    else:
        frame_range = cmds.currentTime(query=True),
    
    for frame in frame_range:
        
        #####FRAME SETTINGS OVERRIDE GENERAL SETTINGS
        seed = frame
        
        
        
        cmds.currentTime(frame,edit=True)
        
        scene_code = ''
        
        scene_code += '{\n'#begin
        scene_code += '    "resolution": [' + str(resolution_x) + ', ' + str(resolution_y) + '],\n'
        scene_code += '    "viewport":  [0, 0, ' + str(resolution_x) + ', ' + str(resolution_y) + '],\n'
        scene_code += '    "exposure": ' + str(exposure) + ',\n'
        scene_code += '    "gamma": ' + str(gamma) + ',\n'
        scene_code += '    "rays": ' + str(ray_number) + ',\n'
        if time != 0:
            scene_code += '    "timelimit": ' + str(time) + ',\n'
        scene_code += '    "seed": ' + str(int(seed)) + ',\n'
        
        
        #### LIGHTS
        
        scene_code += '    "lights": [\n'
        
        for obj in cmds.ls(sl=True):
            shape = cmds.listRelatives(obj, shapes=True)
            if (cmds.objectType(shape, isType='pointLight') or cmds.objectType(shape, isType='spotLight')) and cmds.getAttr(obj + '.visibility'):
                wav = HSV2wavelength([cmds.getAttr(shape[0]+'.colorR'), cmds.getAttr(shape[0]+'.colorG'), cmds.getAttr(shape[0]+'.colorB')])
                use_spectral = cmds.getAttr(shape[0]+'.hqzSpectralLight')
                spectral_start = cmds.getAttr(shape[0]+'.hqzSpectralStart')
                spectral_end = cmds.getAttr(shape[0]+'.hqzSpectralEnd')
                x, y = get_loc(obj)
                y = resolution_y-y
                rot = get_rot(obj)
                
                scene_code += '        [ '
                scene_code += str(cmds.getAttr(shape[0]+'.intensity')) + ', '                 #LIGHT POWER
                scene_code += str(x) + ', '                                                   #XPOS
                scene_code += str(y)                                                          #YPOS
                scene_code += ', [0, 360], ['                                                 #POLAR ANGLE
                scene_code += str(cmds.getAttr(shape[0]+'.hqzLightStart')) + ', '             #POLAR DISTANCE MIN
                scene_code += str(cmds.getAttr(shape[0]+'.hqzLightEnd')) + '], ['             #POLAR DISTANCE MIN
                #scene_code += '0' + ', ' #POLAR DISTANCE MIN
                #scene_code += '0' + '], [' #POLAR DISTANCE MAX
                
                if cmds.objectType(shape, isType='spotLight'):
                    scene_code += str(-rot-cmds.getAttr(shape[0]+'.coneAngle')*0.5) + ', '               #ANGLE
                    scene_code += str(-rot+cmds.getAttr(shape[0]+'.coneAngle')*0.5) + '], '
                else:
                    scene_code += '0, 360], '
                    
                if use_spectral:
                    scene_code += '[' + str(spectral_start) + ', ' + str(spectral_end) + '] ],\n'                                         #WAVELENGTH
                else:
                    scene_code += str(int(wav))  +' ],\n'                                         #WAVELENGTH
                
        scene_code = scene_code[:-2]#remove last comma
        scene_code += '\n    ],\n'
        
        
        
        scene_code += '    "objects": [\n'
        
        
        #### GET MAYA EDGE LIST
        edge_list = []
        for obj in cmds.ls(sl=True):
            shape = cmds.listRelatives(obj, shapes=True)
            if cmds.objectType(shape, isType='mesh') and (cmds.getAttr(obj + '.v')):                
                cmds.select(obj)
                edge_info = cmds.polyInfo(edgeToVertex=True)#get vertices connected to edge
                #print(edge_info)
                edges=[]
                for edge in edge_info:
                    #print(edge)
                    edge = edge.split(':')[1]
                    edge = [int(edge[:7]),int(edge[8:15])]
                    #print(edge.split(' '))#get vertices connected to edge
                    edges.append(edge)
                #print(edges)
                
                
                for edge in edges:
                    edgev = []
        #                vertices = list(edge.vertices)
                    #material = obj.split('_')[1]
                    material = str(cmds.getAttr(shape[0]+'.hqzMaterial'))
                    edgev.append(material)
                    edgev.append(cmds.xform(obj+'.vtx[%i]' % edge[0], translation=True, absolute=True, worldSpace=True, query=True))
                    edgev.append(cmds.xform(obj+'.vtx[%i]' % edge[1], translation=True, absolute=True, worldSpace=True, query=True))
                    if export_normals:
                        #print(vertices[0])
                        for v_ix in range(2):
                            cmds.select(obj+'.vtx[%i]' % edge[v_ix])
                            vectors = cmds.polyNormalPerVertex(query=True, xyz=True)
                            edgev.append(cmds.xform(obj, rotation=True, query=True)[2] + vector2rotation([vectors[0],vectors[1]]))
                        #edgev.append((obj.rotation_euler[2] * 180/pi) + vector2rotation(obj.data.vertices[vertices[0]].normal))
                        #edgev.append((obj.rotation_euler[2] * 180/pi) + vector2rotation(obj.data.vertices[vertices[1]].normal))
                    
                    #print(edgev)
                    if check_Z:
                        #print(fabs(cmds.xform(obj+'.vtx[%i]' % edge[0], translation=True, absolute=True, worldSpace=True, query = True)[2]))
                        if fabs(cmds.xform(obj+'.vtx[%i]' % edge[0], translation=True, absolute=True, worldSpace=True, query=True)[2]) < 0.0001 \
                        and fabs( cmds.xform(obj+'.vtx[%i]' % edge[1], translation=True, absolute=True, worldSpace=True, query=True)[2]) < 0.0001:
                            edge_list.append(edgev)
                    else:
                        edge_list.append(edgev)
                    #print(edgev)
        #print(edge_list)
        
        ####OBJECTS
        for edge in edge_list:
            #print(edge)
            scene_code += '        [ '    
            scene_code += str(edge[0]) + ', '                                                    #MATERIAL
            scene_code += str(edge[1][0]*resolution_x) + ', '                                    #VERT1 XPOS
            scene_code += str(resolution_y - (edge[1][1]*resolution_x)) + ', '                   #VERT1 YPOS
            if export_normals:
                scene_code += str(edge[3]) + ', '                                                #VERT1 NORMAL
            
            scene_code += str(edge[2][0]*resolution_x - (edge[1][0]*resolution_x)) + ', '        #VERT2 DELTA XPOS 
            scene_code += str(-1 * (edge[2][1]*resolution_x - (edge[1][1]*resolution_x))) + '],' #VERT2 DELTA YPOS 
            if export_normals:
                scene_code = scene_code[:-2]#remove last comma and bracket
                normal = (edge[4]) - (edge[3])
                if normal < -180:
                    normal += 360
                if normal > 180:
                    normal -= 360
                scene_code += ',' + str(normal) + '],'                           #VERT2 NORMAL
            scene_code += '\n'
                
        scene_code = scene_code[:-2]#remove last comma
        
        scene_code += '\n    ],\n'
        scene_code += '    "materials": [\n'
        
        
        cmds.select(selection, replace=True)
        ###mats
        for mat in materials:
            scene_code += '        [ [ ' + str(mat[0]) + ', "d" ],[ ' + str(mat[1]) + ', "t" ],[ ' + str(mat[2]) + ', "r" ] ],\n'
                
        scene_code = scene_code[:-2]#remove last comma
        scene_code += '\n    ]\n'
        
        
        scene_code += '}'
        #print(scene_code)
        
        
        if debug:
            scene_code = scene_code.replace('\n', '')
            print(scene_code)
            
        
        #folder = folder
        save_path = folder + '\\' + file_name + '_' + str(int(frame)).zfill(4) + '.json'
        save_path.replace('/', '\\')
        print(save_path)
        d = os.path.dirname((folder+'\\').replace('/', '\\'))
        if not os.path.exists(d):
            os.makedirs(d)
            
        file = open(save_path, 'w')
        file.write(scene_code)
        file.close()
        
        
    ###DIRTY LOOP FOR BASH SCRIPT. I SHOULD LEARN THINGS
    if export_batch:
        shell_path = (folder+'\\').replace('/', '\\')+'batch.bat'
        shell_script = ''
        for frame in frame_range:
            shell_script +=  engine_path.replace('/', '\\') + ' ' + (folder+'\\').replace('/', '\\') + file_name + '_' + str(int(frame)).zfill(4) +".json "  + folder + '\\' + file_name + '_' + str(int(frame)).zfill(4) +".png\n"
        file = open(shell_path, 'w')
        file.write(shell_script)
        file.close()
 def repair(cls, instance):
     """Unlocks all normals on the meshes in this instance."""
     invalid = cls.get_invalid(instance)
     for mesh in invalid:
         cmds.polyNormalPerVertex(mesh, unFreezeNormal=True)
 def has_locked_normals(mesh):
     """Return whether a mesh node has locked normals"""
     return any(cmds.polyNormalPerVertex(mesh + ".vtxFace[*][*]",
                                         query=True,
                                         freezeNormal=True))
예제 #58
0
 def get_vnormal(shape, vert_itx, face_idx):
     vec = om.MVector()
     attr = '%s.vtxFace[%d][%d]' % (shape, vert_itx, face_idx)
     vec = mc.polyNormalPerVertex(attr, q=True, xyz=True)
     return vec
예제 #59
0
def normUn(*args):
	cmds.polyNormalPerVertex(ufn=True)