Ejemplo n.º 1
0
        private MIntArray GetMinTime()
        {
            MIntArray minTime = new MIntArray();

            MGlobal.executeCommand("playbackOptions -q -animationStartTime", minTime);
            return(minTime);
        }
Ejemplo n.º 2
0
        private static List <Material> GetMaterialsMesh(ref MFnMesh Mesh, ref MDagPath Path)
        {
            // Get materials for this mesh
            var Result = new List <Material>();

            // Fetch data
            var Shaders       = new MObjectArray();
            var ShaderIndices = new MIntArray();

            Mesh.getConnectedShaders(Path.instanceNumber, Shaders, ShaderIndices);

            // Iterate and add
            for (int i = 0; i < (int)Shaders.length; i++)
            {
                // Find plug
                var ShaderNode = new MFnDependencyNode(Shaders[i]);
                var ShaderPlug = ShaderNode.findPlug("surfaceShader");
                var MatPlug    = new MPlugArray();
                ShaderPlug.connectedTo(MatPlug, true, false);

                if (MatPlug.length > 0)
                {
                    Result.Add(new Material(CleanNodeName(new MFnDependencyNode(MatPlug[0].node).name)));
                }
            }

            return(Result);
        }
Ejemplo n.º 3
0
        public static List <List <Point> > getFaceVerticies(MFnMesh mayaMesh)
        {
            List <List <Point> > faces = new List <List <Point> >(mayaMesh.numVertices);
            PointList            verts;
            MPointArray          mayaVerts = new MPointArray();
            MIntArray            ids       = new MIntArray();

            mayaMesh.getPoints(mayaVerts, MSpace.Space.kWorld);


            for (int i = 0; i < mayaMesh.numPolygons; i++)
            {
                mayaMesh.getPolygonVertices(i, ids);
                verts = new PointList(ids.Count);

                foreach (var vtxid in ids)
                {
                    if (MGlobal.isZAxisUp)
                    {
                        verts.Add(Point.ByCoordinates(mayaVerts[vtxid].x, mayaVerts[vtxid].y, mayaVerts[vtxid].z));
                    }
                    else
                    {
                        verts.Add(Point.ByCoordinates(mayaVerts[vtxid].x, -mayaVerts[vtxid].z, mayaVerts[vtxid].y));
                    }
                }
                faces.Add(verts);
            }

            return(faces);
        }
Ejemplo n.º 4
0
        private MIntArray GetMaxTime()
        {
            MIntArray maxTime = new MIntArray();

            MGlobal.executeCommand("playbackOptions -q -animationEndTime", maxTime);
            return(maxTime);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Return true if node descendant hierarchy has any exportable Mesh, Camera, Light or Locator
        /// </summary>
        private bool isNodeRelevantToExportRec(MDagPath mDagPathRoot)
        {
            var       mIteratorType = new MIteratorType();
            MIntArray listOfFilters = new MIntArray();

            listOfFilters.Add((int)MFn.Type.kMesh);
            listOfFilters.Add((int)MFn.Type.kCamera);
            listOfFilters.Add((int)MFn.Type.kLight);
            listOfFilters.Add((int)MFn.Type.kLocator);
            mIteratorType.setFilterList(listOfFilters);
            var dagIterator = new MItDag(mIteratorType, MItDag.TraversalType.kDepthFirst);

            dagIterator.reset(mDagPathRoot);

            while (!dagIterator.isDone)
            {
                MDagPath mDagPath = new MDagPath();
                dagIterator.getPath(mDagPath);

                // Check direct descendants
                if (getApiTypeOfDirectDescendants(mDagPath) != MFn.Type.kUnknown)
                {
                    return(true);
                }

                dagIterator.next();
            }

            // No relevant node found among descendants
            return(false);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Extract ordered indices on a triangle basis
        /// Extract position and normal of each vertex per face
        /// </summary>
        /// <param name="mFnMesh"></param>
        /// <param name="vertices"></param>
        /// <param name="indices"></param>
        /// <param name="subMeshes"></param>
        /// <param name="optimizeVertices"></param>
        private void ExtractGeometry(MFnMesh mFnMesh, List <GlobalVertex> vertices, List <int> indices, List <BabylonSubMesh> subMeshes, bool optimizeVertices)
        {
            // TODO - Multimaterials: create a BabylonSubMesh per submaterial
            // TODO - optimizeVertices
            MIntArray triangleCounts    = new MIntArray();
            MIntArray trianglesVertices = new MIntArray();

            mFnMesh.getTriangles(triangleCounts, trianglesVertices);

            // For each polygon of this mesh
            for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++)
            {
                MIntArray verticesId  = new MIntArray();
                int       nbTriangles = triangleCounts[polygonId];

                // For each triangle of this polygon
                for (int triangleIndex = 0; triangleIndex < triangleCounts[polygonId]; triangleIndex++)
                {
                    int[] triangleVertices = new int[3];
                    mFnMesh.getPolygonTriangleVertices(polygonId, triangleIndex, triangleVertices);

                    // Inverse winding order
                    var tmp = triangleVertices[1];
                    triangleVertices[1] = triangleVertices[2];
                    triangleVertices[2] = tmp;

                    // For each vertex of this triangle (3 vertices per triangle)
                    foreach (int vertexId in triangleVertices)
                    {
                        MPoint point = new MPoint();
                        mFnMesh.getPoint(vertexId, point);

                        MVector normal = new MVector();
                        mFnMesh.getFaceVertexNormal(polygonId, vertexId, normal);

                        var vertex = new GlobalVertex
                        {
                            BaseIndex = vertexId,
                            Position  = point.toArray(),
                            Normal    = normal.toArray()
                        };

                        indices.Add(vertices.Count);
                        vertices.Add(vertex);
                    }
                }
            }

            // BabylonSubMesh
            var subMesh = new BabylonSubMesh {
                indexStart = 0, materialIndex = 0
            };

            subMeshes.Add(subMesh);

            subMesh.indexCount    = indices.Count;
            subMesh.verticesStart = 0;
            subMesh.verticesCount = vertices.Count;
        }
Ejemplo n.º 7
0
		public apiMeshGeomUV()
		{
			faceVertexIndex = new MIntArray();
			ucoord = new MFloatArray();
			vcoord = new MFloatArray();

			reset();
		}
Ejemplo n.º 8
0
        public apiMeshGeomUV()
        {
            faceVertexIndex = new MIntArray();
            ucoord          = new MFloatArray();
            vcoord          = new MFloatArray();

            reset();
        }
Ejemplo n.º 9
0
        protected MObject createMesh(MTime time, ref MObject outData)
        {
            int              numVertices, frame;
            float            cubeSize;
            MFloatPointArray points = new MFloatPointArray();
            MFnMesh          meshFS = new MFnMesh();

            // Scale the cube on the frame number, wrap every 10 frames.
            frame = (int)time.asUnits(MTime.Unit.kFilm);
            if (frame == 0)
            {
                frame = 1;
            }
            cubeSize = 0.5f * (float)(frame % 10);

            const int numFaces = 6;

            numVertices = 8;

            MFloatPoint vtx_1 = new MFloatPoint(-cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_2 = new MFloatPoint(cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_3 = new MFloatPoint(cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_4 = new MFloatPoint(-cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_5 = new MFloatPoint(-cubeSize, cubeSize, -cubeSize);
            MFloatPoint vtx_6 = new MFloatPoint(-cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_7 = new MFloatPoint(cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_8 = new MFloatPoint(cubeSize, cubeSize, -cubeSize);

            points.append(vtx_1);
            points.append(vtx_2);
            points.append(vtx_3);
            points.append(vtx_4);
            points.append(vtx_5);
            points.append(vtx_6);
            points.append(vtx_7);
            points.append(vtx_8);


            // Set up an array containing the number of vertices
            // for each of the 6 cube faces (4 verticies per face)
            //
            int[]     face_counts = { 4, 4, 4, 4, 4, 4 };
            MIntArray faceCounts  = new MIntArray(face_counts);

            // Set up and array to assign vertices from points to each face
            //
            int[]     face_connects = { 0, 1, 2, 3,
                                        4,     5, 6, 7,
                                        3,     2, 6, 5,
                                        0,     3, 5, 4,
                                        0,     4, 7, 1,
                                        1,     7, 6, 2 };
            MIntArray faceConnects = new MIntArray(face_connects);

            MObject newMesh = meshFS.create(numVertices, numFaces, points, faceCounts, faceConnects, outData);

            return(newMesh);
        }
Ejemplo n.º 10
0
 public polyPrimitive()
 {
     iarr         = new MFloatPointArray();
     pa           = new MFloatPointArray();
     faceCounts   = new MIntArray();
     faceConnects = new MIntArray();
     dagMod       = new MDagModifier();
     MGlobal.displayInfo("test polyPrimitive.");
 }
Ejemplo n.º 11
0
        public static bool ContainsHoles(this MFnMesh mesh)
        {
            MIntArray holeInfoArray   = new MIntArray();
            MIntArray holeVertexArray = new MIntArray();

            mesh.getHoles(holeInfoArray, holeVertexArray);

            return(holeInfoArray.length != 0);
        }
Ejemplo n.º 12
0
		public apiMeshGeom()
		{
			vertices = new MPointArray();
			face_counts = new MIntArray();
			face_connects = new MIntArray();
			normals = new MVectorArray();
			uvcoords = new apiMeshGeomUV();
			faceCount = 0;
		}
Ejemplo n.º 13
0
 public apiMeshGeom()
 {
     vertices      = new MPointArray();
     face_counts   = new MIntArray();
     face_connects = new MIntArray();
     normals       = new MVectorArray();
     uvcoords      = new apiMeshGeomUV();
     faceCount     = 0;
 }
Ejemplo n.º 14
0
        private void computeMeshData()
        {
            foreach (MayaMesh mesh in allMeshes)
            {
                // Get the Maya mesh
                MFnMesh mayaMesh = new MFnMesh(mesh.mayaObjectPath);

                // Does the maya mesh have UVs?
                MStringArray uvSetNames = new MStringArray();
                mayaMesh.getUVSetNames(uvSetNames);
                bool hasUvs = (uvSetNames.length > 0) && (mayaMesh.numUVs(uvSetNames[0]) > 0);

                // Iterate through all of the vertices and build the data.
                MItMeshFaceVertex it = new MItMeshFaceVertex(mesh.mayaObjectPath);
                while (!it.isDone)
                {
                    // Create a new vertex and populate its data.
                    Vertex vert = new Vertex();

                    // Get the local position relative to the world origin.
                    MPoint mayaPos = it.position(MSpace.Space.kObject);
                    vert.position = new Vector3((float)mayaPos.x, (float)mayaPos.y, (float)mayaPos.z);
                    //vert.position = new Vector3((float)mayaPos.x - mesh.sourceXForm.mayaWorldPosition.x,
                    //(float)mayaPos.y - mesh.sourceXForm.mayaWorldPosition.y,
                    //(float)mayaPos.z - mesh.sourceXForm.mayaWorldPosition.z);

                    // Get the normal.
                    MVector mayaNrm = new MVector();
                    it.getNormal(mayaNrm, MSpace.Space.kObject);
                    vert.normal = new Vector3((float)mayaNrm.x, (float)mayaNrm.y, (float)mayaNrm.z);

                    // Texcoords.
                    if (hasUvs && it.hasUVsProperty)
                    {
                        float[] mayaUvs = new float[2];
                        it.getUV(mayaUvs, uvSetNames[0]);
                        vert.texcoord = new Vector2(mayaUvs[0], mayaUvs[1]);
                    }

                    // Append the vertex.
                    mesh.vertices.Add(vert);
                    it.next();
                }

                // Get all index data.
                MIntArray mia1 = new MIntArray();
                MIntArray mia2 = new MIntArray();
                mayaMesh.getTriangleOffsets(mia1, mia2);
                foreach (int idx in mia2)
                {
                    mesh.indices.Add((uint)idx);
                }
            }
        }
Ejemplo n.º 15
0
        public static bool CombineMeshes(List <MFnMesh> meshes, bool smartMergeEdge = false)
        {
            for (int i = 0; i < meshes.Count; i++)
            {
                MFnMesh m = new MFnMesh();

                MIntArray vertCounts = new MIntArray(), indiceLists = new MIntArray();
                meshes[i].getVertices(vertCounts, indiceLists);
            }

            return(false);
        }
Ejemplo n.º 16
0
        public TriangleMeshAdapater(MFnMesh mesh)
        {
            MIntArray   indices        = new MIntArray();
            MIntArray   triangleCounts = new MIntArray();
            MPointArray points         = new MPointArray();

            mesh.getTriangles(triangleCounts, indices);
            mesh.getPoints(points);

            // Get the triangle indices
            Indices = new Int32Collection((int)indices.length);
            for (int i = 0; i < indices.length; ++i)
            {
                Indices.Add(indices[i]);
            }

            // Get the control points (vertices)
            Points = new Point3DCollection((int)points.length);
            for (int i = 0; i < (int)points.length; ++i)
            {
                MPoint pt = points[i];
                Points.Add(new Point3D(pt.x, pt.y, pt.z));
            }

            // Get the number of triangle faces and polygon faces
            Debug.Assert(indices.length % 3 == 0);
            int triFaces  = (int)indices.length / 3;
            int polyFaces = mesh.numPolygons;

            // We have normals per polygon, we want one per triangle.
            Normals = new Vector3DCollection(triFaces);
            int nCurrentTriangle = 0;

            // Iterate over each polygon
            for (int i = 0; i < polyFaces; ++i)
            {
                // Get the polygon normal
                var maya_normal = new MVector();
                mesh.getPolygonNormal((int)i, maya_normal);
                System.Windows.Media.Media3D.Vector3D normal = new System.Windows.Media.Media3D.Vector3D(maya_normal.x, maya_normal.y, maya_normal.z);

                // Iterate over each tri in the current polygon
                int nTrisAtFace = triangleCounts[i];
                for (int j = 0; j < nTrisAtFace; ++j)
                {
                    Debug.Assert(nCurrentTriangle < triFaces);
                    Normals.Add(normal);
                    nCurrentTriangle++;
                }
            }
            Debug.Assert(nCurrentTriangle == triFaces);
        }
Ejemplo n.º 17
0
        public static List <object> MelCommand(string MelCommand)
        {
            MStringArray   stringResults = new MStringArray();
            MIntArray      intResults    = new MIntArray();
            MDoubleArray   doubleResults = new MDoubleArray();
            MVectorArray   vectorResults = new MVectorArray();
            List <object>  results       = new List <object>();
            MCommandResult mcr           = new MCommandResult();


            MDagPath dag = new MDagPath();

            try
            {
                MGlobal.executeCommand(MelCommand, mcr);
                //   MGlobal.executeCommand(MelCommand, stringResults);
            }
            catch (MemberAccessException e)
            {
                MGlobal.displayWarning(e.Message);
            }

            switch (mcr.resultType)
            {
            case MCommandResult.Type.kStringArray:
                mcr.getResult(stringResults);
                results.AddRange(stringResults);
                break;

            case MCommandResult.Type.kIntArray:
                mcr.getResult(intResults);
                results.AddRange(intResults.Cast <object>());
                break;

            case MCommandResult.Type.kDoubleArray:
                mcr.getResult(doubleResults);
                results.AddRange(doubleResults.Cast <object>());
                break;

            case MCommandResult.Type.kVectorArray:
                mcr.getResult(vectorResults);
                results.AddRange(vectorResults.Cast <object>());
                break;

            default:
                mcr.getResult(stringResults);
                results.AddRange(stringResults);
                break;
            }
            mcr.Dispose();
            return(results);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Extract the vertices, normals and triangles of a mesh into the M2 collision data fields.
        /// </summary>
        /// <param name="wowModel"></param>
        private static void InjectCollisionMesh(M2 wowModel)
        {
            var collisionFound = false;

            for (var meshIter = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kMesh);
                 !meshIter.isDone; meshIter.next())
            {
                var meshPath = new MDagPath();
                meshIter.getPath(meshPath);

                var meshFn = new MFnMesh(meshPath);
                // only want non-history items
                if (meshFn.isIntermediateObject)
                {
                    continue;
                }
                var name = meshFn.name;
                if (name != "Collision")
                {
                    continue;                     //TODO use custom attribute
                }
                if (collisionFound)
                {
                    throw new Exception("More than one collision box has been found. One supported.");
                }
                MGlobal.displayInfo("\t Collision mesh detected.");

                wowModel.CollisionBox = new CAaBox(AxisInvert(meshFn.boundingBox.min),
                                                   AxisInvert(meshFn.boundingBox.max));
                wowModel.CollisionSphereRadius =
                    (float)Math.Max(meshFn.boundingBox.depth / 2, meshFn.boundingBox.width / 2);

                //TODO fixme better iterate through faces
                var collisionPoints = new MFloatPointArray();
                meshFn.getPoints(collisionPoints, MSpace.Space.kWorld);
                var collisionNormals = new MFloatVectorArray();
                meshFn.getNormals(collisionNormals, MSpace.Space.kWorld);
                var collisionTriangles = new MIntArray();
                meshFn.getTriangles(new MIntArray(), collisionTriangles);
                for (var i = 0; i < collisionPoints.Count; i++)
                {
                    wowModel.CollisionVertices.Add(AxisInvert(collisionPoints[i]));
                    wowModel.CollisionNormals.Add(AxisInvert(collisionNormals[i]));
                }
                foreach (var vertIndex in collisionTriangles)
                {
                    wowModel.CollisionTriangles.Add((ushort)vertIndex);
                }

                collisionFound = true;
            }
        }
Ejemplo n.º 19
0
        public static int[][] getFaceVertId(MFnMesh mayaMesh)
        {
            List <int[]> vtxIds = new List <int[]>(mayaMesh.numPolygons);
            MIntArray    ids    = new MIntArray();

            for (int i = 0; i < mayaMesh.numPolygons; i++)
            {
                mayaMesh.getPolygonVertices(i, ids);

                vtxIds.Add(ids.ToArray());
            }
            return(vtxIds.ToArray());
        }
Ejemplo n.º 20
0
        private static void unpackDynMesh(Mesh dynMesh, out MIntArray faceCnx, out MFloatPointArray verticies, out MIntArray faceVtxCt)
        {
            MIntArray        m_faceCnx   = new MIntArray();
            MFloatPointArray m_verticies = new MFloatPointArray();
            MIntArray        m_faceVtxCt = new MIntArray();

            MFloatPoint vtxToAdd = new MFloatPoint();


            foreach (var vtx in dynMesh.VertexPositions)
            {
                if (MGlobal.isZAxisUp)
                {
                    vtxToAdd.x = (float)vtx.X;
                    vtxToAdd.y = (float)vtx.Y;
                    vtxToAdd.z = (float)vtx.Z;
                }
                else
                {
                    vtxToAdd.x = (float)vtx.X;
                    vtxToAdd.y = (float)vtx.Z;
                    vtxToAdd.z = -(float)vtx.Y;
                }

                m_verticies.Add(vtxToAdd);
            }

            foreach (var fidx in dynMesh.FaceIndices)
            {
                int vtxCt = (int)fidx.Count;
                m_faceVtxCt.Add(vtxCt);
                if (vtxCt == 3)
                {
                    m_faceCnx.Add((int)fidx.A);
                    m_faceCnx.Add((int)fidx.B);
                    m_faceCnx.Add((int)fidx.C);
                }
                else
                {
                    m_faceCnx.Add((int)fidx.A);
                    m_faceCnx.Add((int)fidx.B);
                    m_faceCnx.Add((int)fidx.C);
                    m_faceCnx.Add((int)fidx.D);
                }
            }

            verticies = m_verticies;
            faceCnx   = m_faceCnx;
            faceVtxCt = m_faceVtxCt;
        }
Ejemplo n.º 21
0
        public TriangleMeshAdapater(MFnMesh mesh)
        {
            MIntArray indices = new MIntArray();
            MIntArray triangleCounts = new MIntArray();
            MPointArray points = new MPointArray();

            mesh.getTriangles(triangleCounts, indices);
            mesh.getPoints(points);

            // Get the triangle indices
            Indices = new Int32Collection((int)indices.length);
            for (int i = 0; i < indices.length; ++i)
                Indices.Add(indices[i]);

            // Get the control points (vertices)
            Points = new Point3DCollection((int)points.length);
            for (int i = 0; i < (int)points.length; ++i)
            {
                MPoint pt = points[i];
                Points.Add(new Point3D(pt.x, pt.y, pt.z));
            }

            // Get the number of triangle faces and polygon faces 
            Debug.Assert(indices.length % 3 == 0);
            int triFaces = (int)indices.length / 3;
            int polyFaces = mesh.numPolygons;

            // We have normals per polygon, we want one per triangle. 
            Normals = new Vector3DCollection(triFaces);
            int nCurrentTriangle = 0;

            // Iterate over each polygon
            for (int i = 0; i < polyFaces; ++i)
            {
                // Get the polygon normal
                var maya_normal = new MVector();
                mesh.getPolygonNormal((int)i, maya_normal);
                System.Windows.Media.Media3D.Vector3D normal = new System.Windows.Media.Media3D.Vector3D(maya_normal.x, maya_normal.y, maya_normal.z);

                // Iterate over each tri in the current polygon
                int nTrisAtFace = triangleCounts[i];
                for (int j = 0; j < nTrisAtFace; ++j)
                {
                    Debug.Assert(nCurrentTriangle < triFaces);
                    Normals.Add(normal);
                    nCurrentTriangle++;
                }
            }
            Debug.Assert(nCurrentTriangle == triFaces);
        }
Ejemplo n.º 22
0
        private void ValidateMeshTopology(MFnMesh mesh, MDagPath meshDagPath, MIntArray polygonShaderIndices, ref MIntArray vertexShaders, uint shaderCount)
        {
            //Check if the mesh contains holes
            MIntArray holeInfoArray   = new MIntArray();
            MIntArray holeVertexArray = new MIntArray();

            mesh.getHoles(holeInfoArray, holeVertexArray);
            if (holeInfoArray.length != 0)
            {
                MGlobal.displayError("SKNFile:Create - Mesh contains holes");
                throw new Exception("SKNFile:Create - Mesh contains holes");
            }

            //Check for non-Triangulated polygons and shared shaders
            vertexShaders = new MIntArray((uint)mesh.numVertices, -1);
            MItMeshPolygon polygonIterator = new MItMeshPolygon(meshDagPath);

            for (polygonIterator.reset(); !polygonIterator.isDone; polygonIterator.next())
            {
                if (!polygonIterator.hasValidTriangulation)
                {
                    MGlobal.displayError("SKNFile:Create - Mesh contains a non-Triangulated polygon");
                    throw new Exception("SKNFile:Create - Mesh contains a non-Triangulated polygon");
                }

                int       shaderIndex = polygonShaderIndices[(int)polygonIterator.index()];
                MIntArray vertices    = new MIntArray();

                polygonIterator.getVertices(vertices);
                if (shaderIndex == -1)
                {
                    MGlobal.displayError("SKNFile:Create - Mesh contains a face with no shader");
                    throw new Exception("SKNFile:Create - Mesh contains a face with no shader");
                }

                for (int i = 0; i < vertices.length; i++)
                {
                    if (shaderCount > 1 && vertexShaders[vertices[i]] != -1 && shaderIndex != vertexShaders[vertices[i]])
                    {
                        MGlobal.displayError("SKNFile:Create - Mesh contains a vertex with multiple sahders");
                        throw new Exception("SKNFile:Create - Mesh contains a vertex with multiple sahders");
                    }
                    else
                    {
                        vertexShaders[vertices[i]] = shaderIndex;
                    }
                }
            }
        }
Ejemplo n.º 23
0
        internal static Mesh MTDMeshFromMayaMesh(MFnMesh mayaMesh, MSpace.Space space)
        {
            PointList vertices = new PointList(mayaMesh.numVertices);

            ;
            List <IndexGroup> faceIndexList = new List <IndexGroup>(mayaMesh.numPolygons);

            MPointArray mayaVerts = new MPointArray();

            mayaMesh.getPoints(mayaVerts, space);
            if (MGlobal.isYAxisUp)
            {
                vertices.AddRange(mayaVerts.Select(v => Point.ByCoordinates(v.x, -v.z, v.y)));
            }
            else
            {
                vertices.AddRange(mayaVerts.Select(v => Point.ByCoordinates(v.x, v.y, v.z)));
            }

            MIntArray faceIndex = new MIntArray();

            for (int i = 0; i < mayaMesh.numPolygons; i++)
            {
                mayaMesh.getPolygonVertices(i, faceIndex);
                if (faceIndex.length > 4)
                {
                    WarningException wa = new WarningException("The DynMesh will not show in Dynamo if it has any faces with 4 verts or more. The DynMesh can be represented as closed curves .");
                    return(null);
                }
                if (faceIndex.length == 3)
                {
                    faceIndexList.Add(IndexGroup.ByIndices((uint)faceIndex[0], (uint)faceIndex[1], (uint)faceIndex[2]));
                }
                else
                {
                    faceIndexList.Add(IndexGroup.ByIndices((uint)faceIndex[0], (uint)faceIndex[1], (uint)faceIndex[2],
                                                           (uint)faceIndex[3]));
                }
            }
            mayaMesh.Dispose();
            mayaVerts.Dispose();
            faceIndex.Dispose();


            using (vertices)
            {
                return(Mesh.ByPointsFaceIndices(vertices, faceIndexList));
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Extract all shaders (M2Batch) linked to a mesh.
        /// </summary>
        private static void ExtractMeshShaders(MayaM2Mesh mesh, MDagPath meshPath)
        {
            MGlobal.displayInfo("Looking for shaders in mesh " + meshPath.fullPathName);
            var meshFn = new MFnMesh(meshPath);

            // get the number of instances
            var numInstances = meshFn.parentCount;

            MGlobal.displayInfo("\t" + numInstances + " instances.");

            // loop through each instance of the mesh
            for (uint i = 0; i < numInstances; ++i)
            {
                // attach a function set to this instances parent transform
                //var fn = new MFnDependencyNode(fnMesh.parent(i));

                // this will hold references to the shaders used on the meshes
                var shaderEngines = new MObjectArray();

                // this is used to hold indices to the materials returned in the object array
                var faceIndices = new MIntArray();

                // get the shaders used by the i'th mesh instance
                meshFn.getConnectedShaders(i, shaderEngines, faceIndices);

                switch (shaderEngines.length)
                {
                // if no shader applied to the mesh instance
                case 0:
                    break;

                // if all faces use the same material
                case 1:
                    var materials = GetMaterials(shaderEngines[0]);
                    MGlobal.displayInfo("\t\tIn shaderEngine[0], found " + materials.length + " materials.");

                    //TODO Extract Material data
                    ExtractMaterial(mesh, materials[0]);
                    //TODO Extract Transparency data
                    //TODO Shader
                    break;

                //Multiple materials, each applied only on some faces.
                default:
                    throw new NotImplementedException("Cannot handle more than one shaderEngine per mesh.");
                }
            }
        }
Ejemplo n.º 25
0
        public MObject ConvertMeshMaya(TriMesh triMesh)
        {
            MFnMesh meshMaya = new MFnMesh();

            int verticeNum          = triMesh.Vertices.Count;
            MFloatPointArray points = new MFloatPointArray();

            for (int i = 0; i < verticeNum; i++)
            {
                float x = (float)triMesh.Vertices[i].Traits.Position.x;
                float y = (float)triMesh.Vertices[i].Traits.Position.y;
                float z = (float)triMesh.Vertices[i].Traits.Position.z;

                MFloatPoint vertex = new MFloatPoint(x, y, z);
                points.append(vertex);
            }


            int faceNum = triMesh.Faces.Count;

            int[] face_Counts = new int[faceNum];
            for (int i = 0; i < faceNum; i++)
            {
                face_Counts[i] = 3;
            }
            MIntArray faceCounts = new MIntArray(face_Counts);


            int[] faceTopology = new int[faceNum * 3];

            for (int j = 0; j < faceNum; j++)
            {
                int index = j * 3;
                faceTopology[index] = triMesh.Faces[j].GetVertex(0).Index;

                faceTopology[index + 1] = triMesh.Faces[j].GetVertex(1).Index;

                faceTopology[index + 2] = triMesh.Faces[j].GetVertex(2).Index;
            }

            MIntArray faceConnects = new MIntArray(faceTopology);

            MObject mesh = meshMaya.create(verticeNum, faceNum, points, faceCounts, faceConnects);

            return(mesh);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Get the local indices from mesh relative triangle indices obtained with MItMeshPolygon.getTriangle().
        /// Original C++ script by Bruno 'Beosil' Heidelberger and Thomas Cowell.
        /// </summary>
        /// <param name="polyMeshRelative"></param>
        /// <param name="triMeshRelative"></param>
        /// <returns>A list of 3 face-relative indices each.</returns>
        private static MIntArray GetLocalTriangle(MIntArray polyMeshRelative, MIntArray triMeshRelative)
        {
            Debug.Assert(triMeshRelative.Count == 3);
            var result = new MIntArray();

            foreach (var vertMeshIndex in triMeshRelative)
            {
                for (var gv = 0; gv < polyMeshRelative.Count; gv++)
                {
                    if (polyMeshRelative[gv] != vertMeshIndex)
                    {
                        continue;
                    }
                    result.Add(gv);
                    break;
                }
            }
            return(result);
        }
Ejemplo n.º 27
0
        private static void unpackTsMesh(TSplineSurface tsMesh, out MIntArray faceCnx, out MFloatPointArray verticies, out MIntArray faceVtxCt)
        {
            MIntArray        m_faceCnx   = new MIntArray();
            MFloatPointArray m_verticies = new MFloatPointArray();
            MIntArray        m_faceVtxCt = new MIntArray();

            MFloatPoint vtxToAdd = new MFloatPoint();

            var tsMeshCompress = tsMesh.CompressIndexes();

            foreach (var vtx in tsMeshCompress.Vertices)
            {
                if (MGlobal.isZAxisUp)
                {
                    vtxToAdd.x = (float)vtx.PointGeometry.X;
                    vtxToAdd.y = (float)vtx.PointGeometry.Y;
                    vtxToAdd.z = (float)vtx.PointGeometry.Z;
                }
                else
                {
                    vtxToAdd.x = (float)vtx.PointGeometry.X;
                    vtxToAdd.y = (float)vtx.PointGeometry.Z;
                    vtxToAdd.z = -(float)vtx.PointGeometry.Y;
                }

                m_verticies.Add(vtxToAdd);
            }

            foreach (var fidx in tsMeshCompress.Faces)
            {
                int vtxCt = fidx.Vertices.Length;
                m_faceVtxCt.Add(vtxCt);

                foreach (var fVert in fidx.Vertices)
                {
                    m_faceCnx.Add(fVert.Index);
                }
            }
            verticies = m_verticies;
            faceCnx   = m_faceCnx;
            faceVtxCt = m_faceVtxCt;
        }
Ejemplo n.º 28
0
        public static List <int[]> GetFaceVertexIdx(string dagName, string space)
        {
            MDagPath dagPath = DMInterop.getDagNode(dagName);

            MSpace.Space mspace = MSpace.Space.kWorld;
            Enum.TryParse(space, out mspace);

            MFnMesh mayaMesh = new MFnMesh(dagPath);

            List <int[]> vtxIds = new List <int[]>(mayaMesh.numPolygons);
            MIntArray    ids    = new MIntArray();

            for (int i = 0; i < mayaMesh.numPolygons; i++)
            {
                mayaMesh.getPolygonVertices(i, ids);

                vtxIds.Add(ids.ToArray());
            }
            return(vtxIds);
        }
Ejemplo n.º 29
0
        public TriMesh ConvertTriMesh(MFnMesh mesh)
        {
            if (mesh == null)
            {
                MGlobal.displayInfo("Mesh is null \n");
            }

            TriMesh trimesh = new TriMesh();

            MIntArray   indices        = new MIntArray();
            MIntArray   triangleCounts = new MIntArray();
            MPointArray points         = new MPointArray();

            mesh.getTriangles(triangleCounts, indices);
            mesh.getPoints(points);

            // Get the triangle indices

            for (int i = 0; i < (int)points.length; ++i)
            {
                MPoint       pt    = points[i];
                VertexTraits trait = new VertexTraits(pt.x, pt.y, pt.z);
                trimesh.Vertices.Add(trait);
            }


            MGlobal.displayInfo(indices.Count.ToString() + "\n");
            int j = 0;

            while (j < indices.Count)
            {
                int a = indices[j];
                j++;
                int b = indices[j];
                j++;
                int c = indices[j];
                j++;
                trimesh.Faces.AddTriangles(trimesh.Vertices[a], trimesh.Vertices[b], trimesh.Vertices[c]);
            }
            return(trimesh);
        }
Ejemplo n.º 30
0
        public static List <Surface> meshToNurbs(MFnMesh mayaMesh)
        {
            MFnSubd subDmesh = new MFnSubd();

            subDmesh.isIntermediateObject = true;
            MPointArray mayaVerts = new MPointArray();

            mayaMesh.getPoints(mayaVerts, MSpace.Space.kWorld);

            MIntArray polyVertct = new MIntArray();


            MIntArray ids    = new MIntArray();
            MIntArray idList = new MIntArray();

            for (int i = 0; i < mayaMesh.numPolygons; i++)
            {
                mayaMesh.getPolygonVertices(i, ids);
                foreach (var id in ids)
                {
                    idList.Add(id);
                }
                polyVertct.Add(ids.Count);
            }
            subDmesh.createBaseMesh(false, mayaMesh.numVertices, mayaMesh.numPolygons, mayaVerts, polyVertct, idList);

            try
            {
                MUintArray   creaseEdgId   = new MUintArray();
                MDoubleArray creaseEdgeVal = new MDoubleArray();
                mayaMesh.getCreaseEdges(creaseEdgId, creaseEdgeVal);

                foreach (var edgId in creaseEdgId)
                {
                    subDmesh.edgeSetCrease(edgId, true);
                }
            }
            catch {}

            try
            {
                MUintArray   creaseVertId  = new MUintArray();
                MDoubleArray creaseVertVal = new MDoubleArray();
                mayaMesh.getCreaseVertices(creaseVertId, creaseVertVal);

                foreach (var vertId in creaseVertId)
                {
                    subDmesh.vertexSetCrease(vertId, true);
                }
            }
            catch { }


            subDmesh.updateAllEditsAndCreases();

            MObjectArray nurbsSurfs = new MObjectArray();

            subDmesh.convertToNurbs(nurbsSurfs);

            List <MFnNurbsSurface> mfnSurfaceList = new List <MFnNurbsSurface>(nurbsSurfs.Count);

            foreach (var surf in nurbsSurfs)
            {
                mfnSurfaceList.Add(new MFnNurbsSurface(surf));
            }

            List <Surface> dynSurfaceList = new List <Surface>(mfnSurfaceList.Count);

            foreach (var mfnNS in mfnSurfaceList)
            {
                dynSurfaceList.Add(DMSurface.mNurbsSurfaceToDynamoSurface(mfnNS, MSpace.Space.kObject));
            }

            MGlobal.deleteNode(subDmesh.model);
            return(dynSurfaceList);
        }
Ejemplo n.º 31
0
		//
		// Description
		//
		//     This function takes an input surface of type kMeshData and converts
		//     the geometry into this nodes attributes.
		//     Returns false if nothing is connected.
		//
		public bool computeInputMesh(MPlug plug,
									 MDataBlock datablock,
									 MPointArray vertices,
									 MIntArray counts,
									 MIntArray connects,
									 MVectorArray normals,
									 apiMeshGeomUV uvs)
		{
			// Get the input subdiv
			//
			MDataHandle inputData = datablock.inputValue( inputMesh );
			MObject surf = inputData.asMesh;

			// Check if anything is connected
			//
			MObject thisObj = thisMObject();
			MPlug surfPlug = new MPlug( thisObj, inputMesh );
			if ( !surfPlug.isConnected )
			{
				datablock.setClean( plug );
				return false;
			}

			// Extract the mesh data
			//
			MFnMesh surfFn = new MFnMesh(surf);
			surfFn.getPoints( vertices, MSpace.Space.kObject );

			// Check to see if we have UVs to copy.
			//
			bool hasUVs = surfFn.numUVsProperty > 0;
			surfFn.getUVs( uvs.ucoord, uvs.vcoord );

			for ( int i=0; i<surfFn.numPolygons; i++ )
			{
				MIntArray polyVerts = new MIntArray();
				surfFn.getPolygonVertices( i, polyVerts );
				int pvc = (int)polyVerts.length;
				counts.append( pvc );
				int uvId;
				for ( int v=0; v<pvc; v++ )
				{
					if ( hasUVs )
					{
						surfFn.getPolygonUVid( i, v, out uvId );
						uvs.faceVertexIndex.append( uvId );
					}
					connects.append( polyVerts[v] );
				}
			}

			for ( int n=0; n<(int)vertices.length; n++ )
			{
				MVector normal = new MVector();
				surfFn.getVertexNormal( n, normal );
				normals.append( normal );
			}

			return true;
		}
Ejemplo n.º 32
0
		//
		// Description
		//
		//    Constructs a cube
		//
		public void buildCube(double cube_size, 
							  MPointArray pa,
							  MIntArray faceCounts, 
							  MIntArray faceConnects,
							  MVectorArray normals, 
							  apiMeshGeomUV uvs)
		{
			const int num_faces			= 6;
			const int num_face_connects	= 24;
			const double normal_value   = 0.5775;
			const int uv_count			= 14; 
	
			pa.clear();
			faceCounts.clear();
			faceConnects.clear();
			uvs.reset();

			pa.append( new MPoint( -cube_size, -cube_size, -cube_size ) );
			pa.append( new MPoint(  cube_size, -cube_size, -cube_size ) );
			pa.append( new MPoint(  cube_size, -cube_size,  cube_size ) );
			pa.append( new MPoint( -cube_size, -cube_size,  cube_size ) );
			pa.append( new MPoint( -cube_size,  cube_size, -cube_size ) );
			pa.append( new MPoint( -cube_size,  cube_size,  cube_size ) );
			pa.append( new MPoint(  cube_size,  cube_size,  cube_size ) );
			pa.append( new MPoint(  cube_size,  cube_size, -cube_size ) );

			normals.append( new MVector( -normal_value, -normal_value, -normal_value ) );
			normals.append( new MVector(  normal_value, -normal_value, -normal_value ) );
			normals.append( new MVector(  normal_value, -normal_value,  normal_value ) );
			normals.append( new MVector( -normal_value, -normal_value,  normal_value ) );
			normals.append( new MVector( -normal_value,  normal_value, -normal_value ) );
			normals.append( new MVector( -normal_value,  normal_value,  normal_value ) );
			normals.append( new MVector(  normal_value,  normal_value,  normal_value ) );
			normals.append( new MVector(  normal_value,  normal_value, -normal_value ) );

			// Define the UVs for the cube. 
			//
			float[] uv_pts = new float[uv_count*2] { 0.375f, 0.0f,
													 0.625f, 0.0f,
													 0.625f, 0.25f,
													 0.375f, 0.25f,
													 0.625f, 0.5f,
													 0.375f, 0.5f,
													 0.625f, 0.75f,
													 0.375f, 0.75f,
													 0.625f, 1.0f,
													 0.375f, 1.0f,
													 0.875f, 0.0f,
													 0.875f, 0.25f,
													 0.125f, 0.0f,
													 0.125f, 0.25f };

			// UV Face Vertex Id.
			//
			int[] uv_fvid = new int[num_face_connects]{ 0, 1, 2, 3, 
														3, 2, 4, 5, 
														5, 4, 6, 7, 
														7, 6, 8, 9, 
														1, 10, 11, 2, 
														12, 0, 3, 13 };

			int i;
			for ( i = 0; i < uv_count; i ++ ) {
				uvs.append_uv( uv_pts[i*2], uv_pts[i*2 + 1] ); 
			}
	
			for ( i = 0; i < num_face_connects; i ++ ) { 
				uvs.faceVertexIndex.append( uv_fvid[i] ); 
			}

			// Set up an array containing the number of vertices
			// for each of the 6 cube faces (4 vertices per face)
			//
			int[] face_counts = new int[num_faces]{ 4, 4, 4, 4, 4, 4 };

			for ( i=0; i<num_faces; i++ )
			{
				faceCounts.append( face_counts[i] );
			}

			// Set up and array to assign vertices from pa to each face 
			//
			int[] face_connects = new int[ num_face_connects ]{ 0, 1, 2, 3,
																4, 5, 6, 7,
																3, 2, 6, 5,
																0, 3, 5, 4,
																0, 4, 7, 1,
																1, 7, 6, 2 };
			for ( i=0; i<num_face_connects; i++ )
			{
				faceConnects.append( face_connects[i] );
			}
		}
Ejemplo n.º 33
0
        public void Load(string name)
        {
            List <StaticObjectVertex> vertices = GetVertices();
            List <uint> indices = GetIndices();

            MIntArray        polygonIndexCounts = new MIntArray((uint)indices.Count / 3);
            MIntArray        polygonIndices     = new MIntArray((uint)indices.Count);
            MFloatPointArray meshVertices       = new MFloatPointArray((uint)vertices.Count);
            MFloatArray      arrayU             = new MFloatArray((uint)vertices.Count);
            MFloatArray      arrayV             = new MFloatArray((uint)vertices.Count);
            MFnMesh          mesh        = new MFnMesh();
            MDagPath         meshDagPath = new MDagPath();
            MDGModifier      modifier    = new MDGModifier();
            MFnSet           set         = new MFnSet();

            for (int i = 0; i < indices.Count / 3; i++)
            {
                polygonIndexCounts[i] = 3;
            }

            for (int i = 0; i < indices.Count; i++)
            {
                polygonIndices[i] = (int)indices[i];
            }

            for (int i = 0; i < vertices.Count; i++)
            {
                StaticObjectVertex vertex = vertices[i];

                meshVertices[i] = new MFloatPoint(vertex.Position.X, vertex.Position.Y, vertex.Position.Z);
                arrayU[i]       = vertex.UV.X;
                arrayV[i]       = 1 - vertex.UV.Y;
            }

            //Assign mesh data
            mesh.create(vertices.Count, indices.Count / 3, meshVertices, polygonIndexCounts, polygonIndices, arrayU, arrayV, MObject.kNullObj);
            mesh.getPath(meshDagPath);
            mesh.assignUVs(polygonIndexCounts, polygonIndices);

            //Set names
            mesh.setName(name);
            MFnTransform transformNode = new MFnTransform(mesh.parent(0));

            transformNode.setName("transform_" + name);

            //Get render partition
            MFnPartition renderPartition = MayaHelper.FindRenderPartition();

            //Create Materials
            uint startIndex = 0;

            for (int i = 0; i < this.Submeshes.Count; i++)
            {
                MFnDependencyNode   dependencyNode = new MFnDependencyNode();
                MFnLambertShader    lambertShader  = new MFnLambertShader();
                StaticObjectSubmesh submesh        = this.Submeshes[i];

                lambertShader.create(true);
                lambertShader.setName(submesh.Name);
                lambertShader.color = MaterialProvider.GetMayaColor(i);

                MObject shadingEngine = dependencyNode.create("shadingEngine", submesh.Name + "_SG");
                MObject materialInfo  = dependencyNode.create("materialInfo", submesh.Name + "_MaterialInfo");
                MPlug   partitionPlug = new MFnDependencyNode(shadingEngine).findPlug("partition");
                MPlug   setsPlug      = MayaHelper.FindFirstNotConnectedElement(renderPartition.findPlug("sets"));
                modifier.connect(partitionPlug, setsPlug);

                MPlug outColorPlug      = lambertShader.findPlug("outColor");
                MPlug surfaceShaderPlug = new MFnDependencyNode(shadingEngine).findPlug("surfaceShader");
                modifier.connect(outColorPlug, surfaceShaderPlug);

                MPlug messagePlug      = new MFnDependencyNode(shadingEngine).findPlug("message");
                MPlug shadingGroupPlug = new MFnDependencyNode(materialInfo).findPlug("shadingGroup");
                modifier.connect(messagePlug, shadingGroupPlug);

                modifier.doIt();

                MFnSingleIndexedComponent component = new MFnSingleIndexedComponent();
                MObject   faceComponent             = component.create(MFn.Type.kMeshPolygonComponent);
                MIntArray groupPolygonIndices       = new MIntArray();
                uint      endIndex = (startIndex + (uint)submesh.Indices.Count) / 3;
                for (uint j = startIndex / 3; j < endIndex; j++)
                {
                    groupPolygonIndices.append((int)j);
                }
                component.addElements(groupPolygonIndices);

                set.setObject(shadingEngine);
                set.addMember(meshDagPath, faceComponent);

                startIndex += (uint)submesh.Indices.Count;
            }

            mesh.updateSurface();
        }
Ejemplo n.º 34
0
        private void computeMeshData()
        {
            foreach( MayaMesh mesh in allMeshes )
            {
                // Get the Maya mesh
                MFnMesh mayaMesh = new MFnMesh(mesh.mayaObjectPath);

                // Does the maya mesh have UVs?
                MStringArray uvSetNames = new MStringArray();
                mayaMesh.getUVSetNames(uvSetNames);
                bool hasUvs = (uvSetNames.length > 0) && (mayaMesh.numUVs(uvSetNames[0]) > 0);

                // Iterate through all of the vertices and build the data.
                MItMeshFaceVertex it = new MItMeshFaceVertex(mesh.mayaObjectPath);
                while( !it.isDone )
                {
                    // Create a new vertex and populate its data.
                    Vertex vert = new Vertex();

                    // Get the local position relative to the world origin.
                    MPoint mayaPos = it.position(MSpace.Space.kObject);
                    vert.position = new Vector3((float)mayaPos.x, (float)mayaPos.y, (float)mayaPos.z);
                    //vert.position = new Vector3((float)mayaPos.x - mesh.sourceXForm.mayaWorldPosition.x,
                                                                            //(float)mayaPos.y - mesh.sourceXForm.mayaWorldPosition.y,
                                                                            //(float)mayaPos.z - mesh.sourceXForm.mayaWorldPosition.z);

                    // Get the normal.
                    MVector mayaNrm = new MVector();
                    it.getNormal(mayaNrm, MSpace.Space.kObject);
                    vert.normal = new Vector3((float)mayaNrm.x, (float)mayaNrm.y, (float)mayaNrm.z);

                    // Texcoords.
                    if( hasUvs && it.hasUVsProperty )
                    {
                        float[] mayaUvs = new float[2];
                        it.getUV(mayaUvs, uvSetNames[0]);
                        vert.texcoord = new Vector2(mayaUvs[0], mayaUvs[1]);
                    }

                    // Append the vertex.
                    mesh.vertices.Add(vert);
                    it.next();
                }

                // Get all index data.
                MIntArray mia1 = new MIntArray();
                MIntArray mia2 = new MIntArray();
                mayaMesh.getTriangleOffsets(mia1, mia2);
                foreach( int idx in mia2 )
                {
                    mesh.indices.Add((uint)idx);
                }
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Extract ordered indices on a triangle basis
        /// Extract position and normal of each vertex per face
        /// </summary>
        /// <param name="mFnMesh"></param>
        /// <param name="vertices"></param>
        /// <param name="indices"></param>
        /// <param name="subMeshes"></param>
        /// <param name="uvSetNames"></param>
        /// <param name="isUVExportSuccess"></param>
        /// <param name="optimizeVertices"></param>
        private void ExtractGeometry(MFnMesh mFnMesh, List <GlobalVertex> vertices, List <int> indices, List <BabylonSubMesh> subMeshes, MStringArray uvSetNames, ref bool[] isUVExportSuccess, bool optimizeVertices)
        {
            // TODO - optimizeVertices
            MIntArray triangleCounts    = new MIntArray();
            MIntArray trianglesVertices = new MIntArray();

            mFnMesh.getTriangles(triangleCounts, trianglesVertices);

            MObjectArray shaders        = new MObjectArray();
            MIntArray    faceMatIndices = new MIntArray(); // given a face index => get a shader index

            mFnMesh.getConnectedShaders(0, shaders, faceMatIndices);

            // Export geometry even if an error occured with shaders
            // This is a fix for Maya test files
            // TODO - Find the reason why shaders.count = 0
            int  nbShaders   = Math.Max(1, shaders.Count);
            bool checkShader = nbShaders == shaders.Count;

            RaiseVerbose("shaders.Count=" + shaders.Count, 2);

            // For each material of this mesh
            for (int indexShader = 0; indexShader < nbShaders; indexShader++)
            {
                var nbIndicesSubMesh      = 0;
                var minVertexIndexSubMesh = int.MaxValue;
                var maxVertexIndexSubMesh = int.MinValue;
                var subMesh = new BabylonSubMesh {
                    indexStart = indices.Count, materialIndex = indexShader
                };

                // For each polygon of this mesh
                for (int polygonId = 0; polygonId < faceMatIndices.Count; polygonId++)
                {
                    if (checkShader && faceMatIndices[polygonId] != indexShader)
                    {
                        continue;
                    }

                    // The object-relative (mesh-relative/global) vertex indices for this face
                    MIntArray polygonVertices = new MIntArray();
                    mFnMesh.getPolygonVertices(polygonId, polygonVertices);

                    // For each triangle of this polygon
                    for (int triangleId = 0; triangleId < triangleCounts[polygonId]; triangleId++)
                    {
                        int[] polygonTriangleVertices = new int[3];
                        mFnMesh.getPolygonTriangleVertices(polygonId, triangleId, polygonTriangleVertices);

                        /*
                         * Switch coordinate system at global level
                         *
                         * Piece of code kept just in case
                         * See BabylonExporter for more information
                         */
                        //// Inverse winding order to flip faces
                        //var tmp = triangleVertices[1];
                        //triangleVertices[1] = triangleVertices[2];
                        //triangleVertices[2] = tmp;

                        // For each vertex of this triangle (3 vertices per triangle)
                        foreach (int vertexIndexGlobal in polygonTriangleVertices)
                        {
                            // Get the face-relative (local) vertex id
                            int vertexIndexLocal = 0;
                            for (vertexIndexLocal = 0; vertexIndexLocal < polygonVertices.Count; vertexIndexLocal++)
                            {
                                if (polygonVertices[vertexIndexLocal] == vertexIndexGlobal)
                                {
                                    break;
                                }
                            }

                            GlobalVertex vertex = ExtractVertex(mFnMesh, polygonId, vertexIndexGlobal, vertexIndexLocal, uvSetNames, ref isUVExportSuccess);
                            vertex.CurrentIndex = vertices.Count;

                            indices.Add(vertex.CurrentIndex);
                            vertices.Add(vertex);

                            minVertexIndexSubMesh = Math.Min(minVertexIndexSubMesh, vertex.CurrentIndex);
                            maxVertexIndexSubMesh = Math.Max(maxVertexIndexSubMesh, vertex.CurrentIndex);
                            nbIndicesSubMesh++;
                        }
                    }
                }

                if (nbIndicesSubMesh != 0)
                {
                    subMesh.indexCount    = nbIndicesSubMesh;
                    subMesh.verticesStart = minVertexIndexSubMesh;
                    subMesh.verticesCount = maxVertexIndexSubMesh - minVertexIndexSubMesh + 1;

                    subMeshes.Add(subMesh);
                }
            }
        }
Ejemplo n.º 36
0
        protected MObject createMesh(MTime time, ref MObject outData)
        {
            int numVertices, frame;
            float cubeSize;
            MFloatPointArray points = new MFloatPointArray();
            MFnMesh meshFS = new MFnMesh();

            // Scale the cube on the frame number, wrap every 10 frames.
            frame = (int)time.asUnits(MTime.Unit.kFilm);
            if (frame == 0)
                frame = 1;
            cubeSize = 0.5f * (float)(frame % 10);

            const int numFaces = 6;
            numVertices = 8;

            MFloatPoint vtx_1 = new MFloatPoint(-cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_2 = new MFloatPoint(cubeSize, -cubeSize, -cubeSize);
            MFloatPoint vtx_3 = new MFloatPoint(cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_4 = new MFloatPoint(-cubeSize, -cubeSize, cubeSize);
            MFloatPoint vtx_5 = new MFloatPoint(-cubeSize, cubeSize, -cubeSize);
            MFloatPoint vtx_6 = new MFloatPoint(-cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_7 = new MFloatPoint(cubeSize, cubeSize, cubeSize);
            MFloatPoint vtx_8 = new MFloatPoint(cubeSize, cubeSize, -cubeSize);
            points.append(vtx_1);
            points.append(vtx_2);
            points.append(vtx_3);
            points.append(vtx_4);
            points.append(vtx_5);
            points.append(vtx_6);
            points.append(vtx_7);
            points.append(vtx_8);

            // Set up an array containing the number of vertices
            // for each of the 6 cube faces (4 verticies per face)
            //
            int[] face_counts = { 4, 4, 4, 4, 4, 4 };
            MIntArray faceCounts = new MIntArray(face_counts);

            // Set up and array to assign vertices from points to each face
            //
            int[] face_connects = {	0, 1, 2, 3,
                                    4, 5, 6, 7,
                                    3, 2, 6, 5,
                                    0, 3, 5, 4,
                                    0, 4, 7, 1,
                                    1, 7, 6, 2	};
            MIntArray faceConnects = new MIntArray(face_connects);

            MObject newMesh = meshFS.create(numVertices, numFaces, points, faceCounts, faceConnects, outData);

            return newMesh;
        }
Ejemplo n.º 37
0
		//
		// Description
		//
		//    Create circles of vertices starting with 
		//    the top pole ending with the bottom pole
		//
		public void buildSphere(double rad,
								int div,
								MPointArray vertices,
								MIntArray counts,
								MIntArray connects,
								MVectorArray normals,
								apiMeshGeomUV uvs)
		{
			double u = -Math.PI / 2.0;
			double v = -Math.PI;
			double u_delta = Math.PI / ((double)div); 
			double v_delta = 2 * Math.PI / ((double)div); 

			MPoint topPole = new MPoint( 0.0, rad, 0.0 );
			MPoint botPole = new MPoint( 0.0, -rad, 0.0 );

			// Build the vertex and normal table
			//
			vertices.append( botPole );
			normals.append( botPole.minus(MPoint.origin) );
			int i;
			for ( i=0; i<(div-1); i++ )
			{
				u += u_delta;
				v = -Math.PI;

				for ( int j=0; j<div; j++ )
				{
					double x = rad * Math.Cos(u) * Math.Cos(v);
					double y = rad * Math.Sin(u);
					double z = rad * Math.Cos(u) * Math.Sin(v) ;
					MPoint pnt = new MPoint( x, y, z );
					vertices.append( pnt );
					normals.append( pnt.minus(MPoint.origin) );
					v += v_delta;
				}
			}
			vertices.append( topPole );
			normals.append( topPole.minus(MPoint.origin) );

			// Create the connectivity lists
			//
			int vid = 1;
			int numV = 0;
			for ( i=0; i<div; i++ )
			{
				for ( int j=0; j<div; j++ )
				{
					if ( i==0 )
					{
						counts.append( 3 );
						connects.append( 0 );
						connects.append( j+vid );
						connects.append( (j==(div-1)) ? vid : j+vid+1 );
					}
					else if ( i==(div-1) )
					{
						counts.append( 3 );
						connects.append( j+vid+1-div );
						connects.append( vid+1 );
						connects.append( j==(div-1) ? vid+1-div : j+vid+2-div );
					}
					else
					{
						counts.append( 4 );
						connects.append( j + vid+1-div );
						connects.append( j + vid+1 );
						connects.append( j == (div-1) ? vid+1 : j+vid+2 );
						connects.append( j == (div-1) ? vid+1-div : j+vid+2-div );
					}
					numV++;
				}
				vid = numV;
			}

			// TODO: Define UVs for sphere ...
			//
		}
Ejemplo n.º 38
0
        public Material MakeMaterial(MFnMesh fnMesh)
        {
            MaterialGroup matGroup =new MaterialGroup () ;

            MObjectArray shaders =new MObjectArray() ;
            MIntArray indices =new MIntArray () ;
            fnMesh.getConnectedShaders (0, shaders, indices) ;
            for ( int i =0 ; i < shaders.length ; i++ ) {
                MFnDependencyNode shaderGroup =new MFnDependencyNode (shaders [i]) ;
                MPlug shaderPlug =shaderGroup.findPlug ("surfaceShader") ;
                MPlugArray connections =new MPlugArray () ;
                shaderPlug.connectedTo (connections, true, false) ;
                for ( int u =0 ; u < connections.length ; u++ ) {
                    MFnDependencyNode depNode =new MFnDependencyNode (connections [u].node) ;

                    //MPlug colorPlug =depNode.findPlug ("color") ;
                    //MColor mcolor =new MColor () ;
                    ///*MPlugArray cc =new MPlugArray () ;
                    //colorPlug.connectedTo (cc, true , false) ;
                    //if ( cc.length > 0 ) {
                    //    // Plug is driven by an input connection.
                    //    for ( int v =0 ; v < cc.length ; v++ ) {
                    //        MPlug color2Plug =cc [v] ;
                    //        Console.WriteLine (color2Plug.numChildren) ;
                    //        color2Plug.child (0).getValue (mcolor.r) ;
                    //        color2Plug.child (1).getValue (mcolor.g) ;
                    //        color2Plug.child (2).getValue (mcolor.b) ;
                    //        //color2Plug.child (3).getValue (mcolor.a) ;
                    //    }
                    //} else {*/
                    //    mcolor.r =colorPlug.child (0).asFloat () ;
                    //    mcolor.g =colorPlug.child (1).asFloat () ;
                    //    mcolor.b =colorPlug.child (2).asFloat () ;
                    //    //colorPlug.child (3).getValue (mcolor.a) ;
                    ////}

                    //MPlug trPlug =depNode.findPlug ("transparency") ;
                    //float transparency =1.0f - trPlug.child (0).asFloat () ;
                    ////return new DiffuseMaterial (new SolidColorBrush (Color.FromScRgb (transparency, mcolor.r, mcolor.g, mcolor.b))) ;

                    //DiffuseMaterial diffuse =new DiffuseMaterial (new SolidColorBrush (Color.FromScRgb (transparency, mcolor.r, mcolor.g, mcolor.b))) ;
                    //colorPlug =depNode.findPlug ("ambientColor") ;
                    //mcolor.r =colorPlug.child (0).asFloat () ;
                    //mcolor.g =colorPlug.child (1).asFloat () ;
                    //mcolor.b =colorPlug.child (2).asFloat () ;
                    //diffuse.AmbientColor =Color.FromScRgb (transparency, mcolor.r, mcolor.g, mcolor.b) ;
                    //matGroup.Children.Add (diffuse) ;

                    //colorPlug =depNode.findPlug ("specularColor") ;
                    //mcolor.r =colorPlug.child (0).asFloat () ;
                    //mcolor.g =colorPlug.child (1).asFloat () ;
                    //mcolor.b =colorPlug.child (2).asFloat () ;
                    //MPlug powerPlug =depNode.findPlug ("cosinePower") ;

                    //SpecularMaterial specular =new SpecularMaterial (new SolidColorBrush (Color.FromScRgb (1.0f, mcolor.r, mcolor.g, mcolor.b)), powerPlug.asDouble ()) ;
                    //matGroup.Children.Add (specular) ;

                    //EmissiveMaterial emissive =new EmissiveMaterial () ;
                    //matGroup.Children.Add (emissive) ;

                    try {
                        MFnLambertShader lambert =new MFnLambertShader (connections [u].node) ;

                        SolidColorBrush brush =new SolidColorBrush (Color.FromScRgb (1.0f - lambert.transparency.r, lambert.color.r, lambert.color.g, lambert.color.b)) ;
                        brush.Opacity =1.0f - lambert.transparency.r ;
                        DiffuseMaterial diffuse =new DiffuseMaterial (brush) ;
                        diffuse.AmbientColor =Color.FromScRgb (1.0f - lambert.ambientColor.a, lambert.ambientColor.r, lambert.ambientColor.g, lambert.ambientColor.b) ;
                        // no more attributes
                        matGroup.Children.Add (diffuse) ;

                        // No specular color

                        EmissiveMaterial emissive =new EmissiveMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - lambert.incandescence.a, lambert.incandescence.r, lambert.incandescence.g, lambert.incandescence.b))) ;
                        // no more attributes
                        matGroup.Children.Add (emissive) ;
                    } catch {
                    }

                    //try {
                    //    MFnReflectShader reflect =new MFnReflectShader (connections [u].node) ;

                    //    SpecularMaterial specular =new SpecularMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - reflect.specularColor.a, reflect.specularColor.r, reflect.specularColor.g, reflect.specularColor.b)), reflect.cosPower) ;
                    //    // no more attributes
                    //    matGroup.Children.Add (specular) ;
                    //} catch {
                    //}

                    try {
                        MFnPhongShader phong =new MFnPhongShader (connections [u].node) ;

                        //See Lambert
                        //SolidColorBrush brush =new SolidColorBrush (Color.FromScRgb (1.0f - phong.transparency.r, phong.color.r, phong.color.g, phong.color.b)) ;
                        //brush.Opacity =1.0f - phong.transparency.r ;
                        //DiffuseMaterial diffuse =new DiffuseMaterial (brush) ;
                        //diffuse.AmbientColor =Color.FromScRgb (1.0f - phong.ambientColor.a, phong.ambientColor.r, phong.ambientColor.g, phong.ambientColor.b) ;
                        //// no more attributes
                        //matGroup.Children.Add (diffuse) ;

                        SpecularMaterial specular =new SpecularMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - phong.specularColor.a, phong.specularColor.r, phong.specularColor.g, phong.specularColor.b)), phong.cosPower) ;
                        // no more attributes
                        matGroup.Children.Add (specular) ;

                        //See Lambert
                        //EmissiveMaterial emissive =new EmissiveMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - phong.incandescence.a, phong.incandescence.r, phong.incandescence.g, phong.incandescence.b))) ;
                        //// no more attributes
                        //matGroup.Children.Add (emissive) ;
                    } catch {
                    }

                    // todo
                    //try {
                    //    MFnBlinnShader phong =new MFnBlinnShader (connections [u].node) ;

                    //    //See Lambert
                    //    //SolidColorBrush brush =new SolidColorBrush (Color.FromScRgb (1.0f - phong.transparency.r, phong.color.r, phong.color.g, phong.color.b)) ;
                    //    //brush.Opacity =1.0f - phong.transparency.r ;
                    //    //DiffuseMaterial diffuse =new DiffuseMaterial (brush) ;
                    //    //diffuse.AmbientColor = Color.FromScRgb (1.0f - phong.ambientColor.a, phong.ambientColor.r, phong.ambientColor.g, phong.ambientColor.b) ;
                    //    //// no more attributes
                    //    //matGroup.Children.Add (diffuse) ;

                    //    //See Lambert
                    //    //EmissiveMaterial emissive =new EmissiveMaterial (new SolidColorBrush (Color.FromScRgb (1.0f - phong.incandescence.a, phong.incandescence.r, phong.incandescence.g, phong.incandescence.b))) ;
                    //    //// no more attributes
                    //    //matGroup.Children.Add (emissive) ;
                    //} catch {
                    //}
                }
            }

            // Default to Blue
            if ( matGroup.Children.Count == 0 )
                 matGroup.Children.Add (new DiffuseMaterial (new SolidColorBrush (Color.FromRgb (0, 0, 255)))) ;
            return (matGroup) ;
        }
Ejemplo n.º 39
0
		public polyPrimitive()
		{
			iarr = new MFloatPointArray();
			pa = new MFloatPointArray();
			faceCounts = new MIntArray();
			faceConnects = new MIntArray();
			dagMod = new MDagModifier();
			MGlobal.displayInfo("test polyPrimitive.");
		}
Ejemplo n.º 40
0
        private BabylonNode ExportMesh(MObject mObject, BabylonScene babylonScene)
        {
            MFnMesh    mFnMesh    = new MFnMesh(mObject);
            MFnDagNode mFnDagNode = new MFnDagNode(mObject);

            var        mObjectParent    = mFnMesh.parent(0);
            MFnDagNode mFnDagNodeParent = new MFnDagNode(mObjectParent);

            // --- prints ---
            #region prints

            RaiseVerbose("BabylonExporter.Mesh | mFnMesh data", 2);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.name=" + mFnMesh.name, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.absoluteName=" + mFnMesh.absoluteName, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.fullPathName=" + mFnMesh.fullPathName, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.partialPathName=" + mFnMesh.partialPathName, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numVertices=" + mFnMesh.numVertices, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numEdges=" + mFnMesh.numEdges, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numPolygons=" + mFnMesh.numPolygons, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numFaceVertices=" + mFnMesh.numFaceVertices, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numNormals=" + mFnMesh.numNormals, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numUVSets=" + mFnMesh.numUVSets, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numUVsProperty=" + mFnMesh.numUVsProperty, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.activeColor=" + mFnMesh.activeColor.toString(), 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.attributeCount=" + mFnMesh.attributeCount, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.childCount=" + mFnMesh.childCount, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.displayColors=" + mFnMesh.displayColors, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.dormantColor=" + mFnMesh.dormantColor, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.hasUniqueName=" + mFnMesh.hasUniqueName, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.inUnderWorld=" + mFnMesh.inUnderWorld, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isDefaultNode=" + mFnMesh.isDefaultNode, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanceable=" + mFnMesh.isInstanceable, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanced(true)=" + mFnMesh.isInstanced(true), 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanced(false)=" + mFnMesh.isInstanced(false), 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanced()=" + mFnMesh.isInstanced(), 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isIntermediateObject=" + mFnMesh.isIntermediateObject, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isShared=" + mFnMesh.isShared, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numColorSets=" + mFnMesh.numColorSets, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numColorsProperty=" + mFnMesh.numColorsProperty, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.objectColor=" + mFnMesh.objectColor, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.parentCount=" + mFnMesh.parentCount, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.parentNamespace=" + mFnMesh.parentNamespace, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.uuid().asString()=" + mFnMesh.uuid().asString(), 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.dagRoot().apiType=" + mFnMesh.dagRoot().apiType, 3);
            RaiseVerbose("BabylonExporter.Mesh | mFnMesh.model.equalEqual(mFnMesh.objectProperty)=" + mFnMesh.model.equalEqual(mFnMesh.objectProperty), 3);
            RaiseVerbose("BabylonExporter.Mesh | ToString(mFnMesh.transformationMatrix)=" + mFnMesh.transformationMatrix.toString(), 3);
            var transformationMatrix = new MTransformationMatrix(mFnMesh.transformationMatrix);
            RaiseVerbose("BabylonExporter.Mesh | transformationMatrix.getTranslation().toString()=" + transformationMatrix.getTranslation().toString(), 3);
            var transformationMatrixParent = new MTransformationMatrix(mFnDagNodeParent.transformationMatrix);
            RaiseVerbose("BabylonExporter.Mesh | transformationMatrixParent.getTranslation().toString()=" + transformationMatrixParent.getTranslation().toString(), 3);

            // Geometry
            MIntArray triangleCounts    = new MIntArray();
            MIntArray trianglesVertices = new MIntArray();
            mFnMesh.getTriangles(triangleCounts, trianglesVertices);
            RaiseVerbose("BabylonExporter.Mesh | triangleCounts.ToArray()=" + triangleCounts.ToArray().toString(), 3);
            RaiseVerbose("BabylonExporter.Mesh | trianglesVertices.ToArray()=" + trianglesVertices.ToArray().toString(), 3);
            int[] polygonsVertexCount = new int[mFnMesh.numPolygons];
            for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++)
            {
                polygonsVertexCount[polygonId] = mFnMesh.polygonVertexCount(polygonId);
            }
            RaiseVerbose("BabylonExporter.Mesh | polygonsVertexCount=" + polygonsVertexCount.toString(), 3);

            //MFloatPointArray points = new MFloatPointArray();
            //mFnMesh.getPoints(points);
            //RaiseVerbose("BabylonExporter.Mesh | points.ToArray()=" + points.ToArray().Select(mFloatPoint => mFloatPoint.toString()), 3);

            //MFloatVectorArray normals = new MFloatVectorArray();
            //mFnMesh.getNormals(normals);
            //RaiseVerbose("BabylonExporter.Mesh | normals.ToArray()=" + normals.ToArray().Select(mFloatPoint => mFloatPoint.toString()), 3);

            for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++)
            {
                MIntArray verticesId = new MIntArray();
                RaiseVerbose("BabylonExporter.Mesh | polygonId=" + polygonId, 3);

                int nbTriangles = triangleCounts[polygonId];
                RaiseVerbose("BabylonExporter.Mesh | nbTriangles=" + nbTriangles, 3);

                for (int triangleIndex = 0; triangleIndex < triangleCounts[polygonId]; triangleIndex++)
                {
                    RaiseVerbose("BabylonExporter.Mesh | triangleIndex=" + triangleIndex, 3);
                    int[] triangleVertices = new int[3];
                    mFnMesh.getPolygonTriangleVertices(polygonId, triangleIndex, triangleVertices);
                    RaiseVerbose("BabylonExporter.Mesh | triangleVertices=" + triangleVertices.toString(), 3);

                    foreach (int vertexId in triangleVertices)
                    {
                        RaiseVerbose("BabylonExporter.Mesh | vertexId=" + vertexId, 3);
                        MPoint point = new MPoint();
                        mFnMesh.getPoint(vertexId, point);
                        RaiseVerbose("BabylonExporter.Mesh | point=" + point.toString(), 3);

                        MVector normal = new MVector();
                        mFnMesh.getFaceVertexNormal(polygonId, vertexId, normal);
                        RaiseVerbose("BabylonExporter.Mesh | normal=" + normal.toString(), 3);
                    }
                }
            }

            #endregion


            if (IsMeshExportable(mFnMesh) == false)
            {
                return(null);
            }

            RaiseMessage(mFnMesh.name, 1);

            var babylonMesh = new BabylonMesh {
                name = mFnMesh.name, id = mFnMesh.uuid().asString()
            };

            // Position / rotation / scaling / hierarchy
            ExportNode(babylonMesh, mFnDagNode, babylonScene);

            // Misc.
            // TODO - Retreive from Maya
            // TODO - What is the difference between isVisible and visibility?
            // TODO - Fix fatal error: Attempting to save in C:/Users/Fabrice/AppData/Local/Temp/Fabrice.20171205.1613.ma
            //babylonMesh.isVisible = mDagPath.isVisible;
            //babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
            //babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
            //babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1;

            if (mFnMesh.numPolygons < 1)
            {
                RaiseError($"Mesh {babylonMesh.name} has no face", 2);
            }

            if (mFnMesh.numVertices < 3)
            {
                RaiseError($"Mesh {babylonMesh.name} has not enough vertices", 2);
            }

            if (mFnMesh.numVertices >= 65536)
            {
                RaiseWarning($"Mesh {babylonMesh.name} has more than 65536 vertices which means that it will require specific WebGL extension to be rendered. This may impact portability of your scene on low end devices.", 2);
            }

            // TODO - Material

            var vertices = new List <GlobalVertex>();
            var indices  = new List <int>();
            // TODO - UV, color, alpha
            //var mappingChannels = unskinnedMesh.ActiveMapChannelNum;
            //bool hasUV = false;
            //bool hasUV2 = false;
            //for (int i = 0; i < mappingChannels.Count; ++i)
            //{
            //    var indexer = i;
            //    var channelNum = mappingChannels[indexer];
            //    if (channelNum == 1)
            //    {
            //        hasUV = true;
            //    }
            //    else if (channelNum == 2)
            //    {
            //        hasUV2 = true;
            //    }
            //}
            //var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
            //var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;

            // TODO - Add custom properties
            var optimizeVertices = false; // meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");

            // Compute normals
            var subMeshes = new List <BabylonSubMesh>();
            ExtractGeometry(mFnMesh, vertices, indices, subMeshes, optimizeVertices);

            if (vertices.Count >= 65536)
            {
                RaiseWarning($"Mesh {babylonMesh.name} has {vertices.Count} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", 2);

                if (!optimizeVertices)
                {
                    RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
                }
            }

            RaiseMessage($"{vertices.Count} vertices, {indices.Count / 3} faces", 2);

            // Buffers
            babylonMesh.positions = vertices.SelectMany(v => v.Position).ToArray();
            babylonMesh.normals   = vertices.SelectMany(v => v.Normal).ToArray();

            babylonMesh.subMeshes = subMeshes.ToArray();

            // Buffers - Indices
            babylonMesh.indices = indices.ToArray();


            babylonScene.MeshesList.Add(babylonMesh);
            RaiseMessage("BabylonExporter.Mesh | done", 3);

            return(babylonMesh);
        }
Ejemplo n.º 41
0
		//======================================================================
		//
		// Do the metadata creation. The metadata will be randomly initialized
		// based on the channel type and the structure specified. For recognized
		// components the number of metadata elements will correspond to the count
		// of components in the selected mesh, otherwise a random number of metadata
		// elements between 1 and 100 will be created (at consecutive indices).
		//
		// The previously existing metadata is preserved for later undo.
		//
		override public void doIt(MArgList args)
		{
			MArgDatabase argsDb = new MArgDatabase(syntax, args);

			checkArgs(ref argsDb);

			clearResult();

			uint numNodes = fNodes.length;
			int i;
			for (i = 0; i < numNodes; ++i)
			{
                // fNodes[i] is the transform not the shape itself
                MFnDagNode dagNode = new MFnDagNode(fNodes[i]);
                MObject obj = dagNode.child(0);
                // obj is the shape, which is where we can add the meta data
				MFnDependencyNode node = new MFnDependencyNode(obj);
				// Get the current metadata (empty if none yet)
				Associations newMetadata = new Associations(node.metadata);
				Channel newChannel = newMetadata.channel(fChannelType);

				// Check to see if the requested stream name already exists
				Stream oldStream = newChannel.dataStream(fStreamName);
				if (oldStream != null)
				{

					string fmt = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataHasStream);
					string msg = String.Format(fmt, fStreamName);
					MGlobal.displayError( msg );
					continue;
				}

				Stream newStream = new Stream(fStructure, fStreamName);

                string strmName = newStream.name;

				int indexCount = 0;
                MFnMesh mesh = null;
                Random rndIndexCount = new Random();
                // Treat the channel type initializations different for meshes
				if (obj.hasFn(MFn.Type.kMesh))
				{
                    mesh = new MFnMesh(obj);
					// Get mesh-specific channel type parameters
					if (fChannelType == "face")
					{
						indexCount = mesh.numPolygons;
					}
					else if (fChannelType == "edge")
					{
						indexCount = mesh.numEdges;
					}
					else if (fChannelType == "vertex")
					{
						indexCount = mesh.numVertices;
					}
					else if (fChannelType == "vertexFace")
					{
						indexCount = mesh.numFaceVertices;
					}
					else
					{
						// Set a random number between 1 to 100
                        indexCount = rndIndexCount.Next(1, 100);
					}
				}
				else
				{
					// Create generic channel type information
                    indexCount = rndIndexCount.Next(1, 100);
				}

				// Fill specified stream ranges with random data
				int structureMemberCount = fStructure.memberCount;
				uint m,n,d;
                Random rnd = new Random();
                for (m = 0; m < indexCount; ++m)
				{
					// Walk each structure member and fill with random data
					// tailored to the member data type.
					Handle handle = new Handle(fStructure);
					for (n = 0; n < structureMemberCount; ++n)
					{
						handle.setPositionByMemberIndex(n);

						switch (handle.dataType)
						{
						case Member.eDataType.kBoolean:
							{
                                bool[] data = new bool[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									int randomInt = rnd.Next(0, 2);
									bool randomBool = randomInt == 1 ? true : false;
                                    data[d] = randomBool;
                                }
                                handle.asBooleanArray = data;
								break;
							}
						case Member.eDataType.kDouble:
							{
                                double[] data = new double[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									// Set a random number between -2000000000.0.0 and 2000000000.0.0
									data[d] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
                                }
                                handle.asDoubleArray = data;
								break;
							}
						case Member.eDataType.kDoubleMatrix4x4:
							{
                                double[] data = new double[handle.dataLength * 16];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									data[d*16+0] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+1] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+2] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+3] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+4] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+5] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+6] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+7] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+8] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+9] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+10] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+11] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+12] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+13] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+14] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+15] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
                                }
                                handle.asDoubleMatrix4x4 = data;
								break;
							}
						case Member.eDataType.kFloat:
							{
                                float[] data = new float[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
    								// Set a random number between -2000000.0 and 2000000.0
	    							data[d] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
                                }
                                handle.asFloatArray = data;
								break;
							}
						case Member.eDataType.kFloatMatrix4x4:
							{
                                float[] data = new float[handle.dataLength * 16];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									// Set a random number between -2000000.0 and 2000000.0
									data[d*16+0] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+1] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+2] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+3] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+4] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+5] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+6] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+7] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+8] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+9] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+10] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+11] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+12] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+13] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+14] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+15] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
                                }
                                handle.asFloatMatrix4x4 = data;
								break;
							}
						case Member.eDataType.kInt8:
							{
                                sbyte[] data = new sbyte[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (sbyte)rnd.Next(SByte.MinValue, SByte.MaxValue+1);
                                }
                                handle.asInt8Array = data;
								break;
							}
						case Member.eDataType.kInt16:
							{
								short[] data = new short[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (short)rnd.Next(Int16.MinValue, Int16.MaxValue+1);
                                }
                                handle.asInt16Array = data;
								break;
							}
						case Member.eDataType.kInt32:
							{
								int[] data = new int[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    // rnd.Next returns a number between [arg1,arg2[
                                    // but unfortunately I can't pass Int32.MaxValue+1 here....
                                    data[d] = rnd.Next(Int32.MinValue, Int32.MaxValue);
                                }
                                handle.asInt32Array = data;
								break;
							}
						case Member.eDataType.kInt64:
							{
								long[] data = new long[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    // rnd.Next() gives a number between [0,Int32
                                    data[d] = (long)rnd.Next(Int32.MinValue, Int32.MaxValue);
                                    if( data[d] >= 0 )
                                        data[d] *= Int64.MaxValue / Int32.MaxValue;
                                    else
                                        data[d] *= Int64.MinValue / Int32.MinValue;
                                }
                                handle.asInt64Array = data;
								break;
							}
						case Member.eDataType.kUInt8:
							{
								byte[] data = new byte[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (byte)rnd.Next(0, Byte.MaxValue + 1);
                                }
                                handle.asUInt8Array = data;
								break;
							}
						case Member.eDataType.kUInt16:
							{
								ushort[] data = new ushort[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (ushort)rnd.Next(0, UInt16.MaxValue + 1);
                                }
                                handle.asUInt16Array = data;
								break;
							}
						case Member.eDataType.kUInt32:
							{
								uint[] data = new uint[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (uint)rnd.Next();
                                }
                                handle.asUInt32Array = data;
								break;
							}
						case Member.eDataType.kUInt64:
							{
								ulong[] data = new ulong[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
    								data[d] = ((ulong)rnd.Next()) * UInt64.MaxValue / UInt32.MaxValue;
                                }
                                handle.asUInt64Array = data;
								break;
							}
						case Member.eDataType.kString:
							{
                                string[] randomStrings = new string[] { "banana", "tomatoe", "apple", "pineapple", "apricot", "pepper", "olive", "grapefruit" };
                                string[] data = new string[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    int index = rnd.Next( randomStrings.Length );
    								data[d] = randomStrings[index];
                                }
                                handle.asStringArray = data;
								break;
							}
						default:
							{
								Debug.Assert(false, "This should never happen");
								break;
							}
						}
					}
					newStream.setElement(new Index(m), handle);
				}
				newChannel.setDataStream(newStream);
				newMetadata.setChannel(newChannel);

                // Note: the following will not work if "obj" is a shape constructed by a source object
                // You need to delete the history of the shape before calling this...
                fDGModifier.setMetadata(obj, newMetadata);
                fDGModifier.doIt();

				// Set the result to the number of actual metadata values set as a
				// triple value:
				//	 	(# nodes, # metadata elements, # members per element)
				//
				MIntArray theResult = new MIntArray();
				theResult.append( (int) fNodes.length );
				theResult.append( (int) indexCount );
				theResult.append( (int) structureMemberCount );
				setResult( theResult );

			}
		}
Ejemplo n.º 42
0
       public TriMesh ConvertTriMesh(MFnMesh mesh)
       {
            if(mesh==null)
            {
                MGlobal.displayInfo("Mesh is null \n");
            }

           TriMesh trimesh = new TriMesh();

           MIntArray indices = new MIntArray();
           MIntArray triangleCounts = new MIntArray();
           MPointArray points = new MPointArray();

           mesh.getTriangles(triangleCounts, indices);
           mesh.getPoints(points);

           // Get the triangle indices 
        
           for (int i = 0; i < (int)points.length; ++i)
           {
               MPoint pt = points[i];
               VertexTraits trait = new VertexTraits(pt.x, pt.y, pt.z);
               trimesh.Vertices.Add(trait);
           }
           
           
           MGlobal.displayInfo( indices.Count.ToString() +"\n");
           int j=0;
           while(j<indices.Count)
           {
               int a = indices[j];
               j++;
               int b = indices[j];
               j++;
               int c = indices[j];
               j++;
               trimesh.Faces.AddTriangles(trimesh.Vertices[a], trimesh.Vertices[b], trimesh.Vertices[c]);
                
           } 
           return trimesh;
       }
Ejemplo n.º 43
0
       public MObject ConvertMeshMaya(TriMesh triMesh)
       {
          MFnMesh meshMaya = new MFnMesh();

          int verticeNum = triMesh.Vertices.Count;
          MFloatPointArray points = new MFloatPointArray();
         
          for(int i=0;i<verticeNum;i++)
          {
              float x=(float)triMesh.Vertices[i].Traits.Position.x;
              float y=(float)triMesh.Vertices[i].Traits.Position.y;
              float z=(float)triMesh.Vertices[i].Traits.Position.z;

              MFloatPoint vertex = new MFloatPoint(x,y,z);
              points.append(vertex);
          }

           
           int faceNum = triMesh.Faces.Count;

           int[] face_Counts=new int[faceNum];
           for(int i=0;i<faceNum;i++)
           {
              face_Counts[i]=3;
           }
           MIntArray faceCounts = new MIntArray(face_Counts);


           int[] faceTopology=new int[faceNum*3];
            
           for(int j=0;j<faceNum ;j++)
           {
              int index=j*3;
              faceTopology[index]=triMesh.Faces[j].GetVertex(0).Index ;
               
              faceTopology[index+1]=triMesh.Faces[j].GetVertex(1).Index ;
               
              faceTopology[index+2]=triMesh.Faces[j].GetVertex(2).Index ;
               
           }

           MIntArray faceConnects = new MIntArray(faceTopology);

           MObject mesh= meshMaya.create(verticeNum, faceNum, points, faceCounts, faceConnects);

           return mesh;
       }
Ejemplo n.º 44
0
        unsafe public override void getTweakedUVs(MObject meshObj, MIntArray uvList, MFloatArray uPos, MFloatArray vPos)
        {
            int i = 0;
            MFloatArray uArray = new MFloatArray();
            MFloatArray vArray = new MFloatArray();
            MFnMesh mesh = new MFnMesh(meshObj);
            mesh.getUVs(uArray, vArray);

            uint nbUvShells = 0;
            MIntArray uvShellIds = new MIntArray();

            if ((!flipGlobal) || extendToShell)
                // First, extract the UV shells.
                mesh.getUvShellsIds(uvShellIds, ref nbUvShells);

            if (extendToShell)
            {
                bool[] selected = new bool[nbUvShells];
                for (i = 0; i < nbUvShells; i++)
                {
                    selected[i] = false;
                }

                for (i = 0; i < nbUvShells; i++)
                {
                    int index = uvList[i];
                    index = uvShellIds[index];
                    selected[index] = true;
                }

                uint numUvs = (uint)mesh.numUVsProperty;
                uint numSelUvs = 0;

                // Preallocate a buffer, large enough to hold all Ids. This
                // prevents multiple reallocation from happening when growing
                // the array.
                uvList.length = numUvs;

                for (i = 0; i < numUvs; i++)
                {
                    int index = uvShellIds[i];
                    if (selected[index])
                    {
                        uvList.set((int)i, numSelUvs);
                        numSelUvs++;
                    }
                }

                // clamp the array to the proper size.
                uvList.length = numSelUvs;
            }

            int nbUvShellsInt = (int)nbUvShells;
            // For global flips, just pretend there is only one shell
            if (flipGlobal)
                nbUvShellsInt = 1;

            float[] minMax = new float[nbUvShellsInt * 4];

            for (i = 0; i < nbUvShellsInt; i++)
            {
                minMax[4 * i + 0] = 1e30F;				// Min U
                minMax[4 * i + 1] = 1e30F;				// Min V
                minMax[4 * i + 2] = -1e30F;				// Max U
                minMax[4 * i + 3] = -1e30F;				// Max V
            }

            // Get the bounding box of the UVs, for each shell if flipGlobal
            // is true, or for the whole selection if false.
            for (i = 0; i < uvList.length; i++)
            {
                int indx = uvList[i];
                int shellId = 0;

                if (!flipGlobal)
                {
                    shellId = uvShellIds[indx];
                }

                float value = uArray[indx];
                
                if (value < minMax[4 * shellId + 0])
                    minMax[4 * shellId + 0] = value;

                value = vArray[indx];
                if (value < minMax[4 * shellId + 1])
                    minMax[4 * shellId + 1] = value;

                value = uArray[indx];
                if (value > minMax[4 * shellId + 2])
                    minMax[4 * shellId + 2] = value;

                value = vArray[indx];
                if (value > minMax[4 * shellId + 3])
                    minMax[4 * shellId + 3] = value;
            }

            // Adjust the size of the output arrays
            uPos.length = uvList.length;
            vPos.length = uvList.length;

            for (i = 0; i < uvList.length; i++)
            {
                int shellId = 0;

                int indx = uvList[i];

                if (!flipGlobal)
                    shellId = uvShellIds[indx];

                // Flip U or V along the bounding box center.
                if (horizontal)
                {
                    float value = uArray[indx];
                    value = minMax[4 * shellId + 0] + minMax[4 * shellId + 2] - value;

                    uPos.set(value, (uint)i);
                    value = vArray[indx];
                    vPos.set(value, (uint)i);
                }
                else
                {
                    float value = uArray[indx];
                    uPos.set(value, (uint)i);

                    value = vArray[indx];
                    value = minMax[4 * shellId + 1] + minMax[4 * shellId + 3] - value;
                    vPos.set(value, (uint)i);
                }
            }
            return;
        }