Example #1
0
        // These are used by LoadDebugInfo to format certain types of console output
        // T O   S T R I N G   T R I M E D
        public static string ToStringTrimed(this Assimp.Vector3D v)
        {
            string d    = "+0.000;-0.000"; // "0.00";
            int    pamt = 8;

            return(v.X.ToString(d).PadRight(pamt) + ", " + v.Y.ToString(d).PadRight(pamt) + ", " + v.Z.ToString(d).PadRight(pamt));
        }
Example #2
0
        /// <summary>
        /// Import a mesh from a model file.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Mesh Load(string path)
        {
            Mesh mesh = new Mesh()
            {
                Path = path
            };

            a.AssimpContext context = new a.AssimpContext();
            a.Scene         scene   = context.ImportFile(path, a.PostProcessSteps.Triangulate);
            a.Mesh          aMesh   = scene.Meshes[0];

            mesh.vertices = new Vector4[aMesh.VertexCount];
            mesh.normals  = new Vector4[aMesh.VertexCount];
            mesh.uvs      = new Vector4[aMesh.VertexCount];

            for (int i = 0; i < aMesh.VertexCount; i++)
            {
                a.Vector3D aVertex = aMesh.Vertices[i];
                a.Vector3D aNormal = aMesh.Normals[i];
                a.Vector3D aUv     = aMesh.TextureCoordinateChannels[0][i];

                mesh.vertices[i] = new Vector4(aVertex.X, aVertex.Y, aVertex.Z, 1f);
                mesh.normals[i]  = new Vector4(aNormal.X, aNormal.Y, aNormal.Z, 0f);
                mesh.uvs[i]      = new Vector4(aUv.X, aUv.Y, 0f, 0f);
            }
            mesh.indices = aMesh.GetIndices();

            return(mesh);
        }
Example #3
0
        private void _initMesh(Assimp.Mesh mesh)
        {
            Assimp.Vector3D Zero3D = new Assimp.Vector3D(0f);

            if (mesh.PrimitiveType == Assimp.PrimitiveType.Triangle)
            {
                // Populate the vertex attribute vectors
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    Assimp.Vector3D pos    = mesh.Vertices[i];
                    Assimp.Vector3D normal = mesh.Normals[i];
                    Assimp.Vector3D uv     = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0][i] : Zero3D;

                    positions.Add(new Vector3f(pos.X, pos.Y, pos.Z));
                    normals.Add(new Vector3f(normal.X, normal.Y, normal.Z));
                    uvs.Add(new Vector2f(uv.X, uv.Y));
                }

                // Populate the index buffer
                for (int i = 0; i < mesh.FaceCount; i++)
                {
                    Assimp.Face face = mesh.Faces[i];
                    // TODO: Find a suitable way to draw vertices...
                    // Now only support triangulated faces
                    indices.Add(face.Indices[0]);
                    indices.Add(face.Indices[1]);
                    indices.Add(face.Indices[2]);
                }
            }
        }
Example #4
0
 public static Assimp.Vector3D convertVector(Vector3 localVec)
 {
     Assimp.Vector3D vec = new Assimp.Vector3D();
     vec.X = localVec.X;
     vec.Y = localVec.Y;
     vec.Z = localVec.Z;
     return(vec);
 }
Example #5
0
    public static Vector2[] ReadArrayVector3_to_Vector2(IntPtr array_inline, uint count)
    {
        Vector2[] result = new Vector2[count];
        int       size   = Assimp.InternalInterop.SizeOfInline <Assimp.Vector3D>();

        for (int i = 0; i < count; i++)
        {
            IntPtr          currPos = Assimp.MemoryHelper.AddIntPtr(array_inline, size * i);
            Assimp.Vector3D v       = Assimp.MemoryHelper.Read <Assimp.Vector3D>(currPos);
            result[i] = new Vector2(v.X, v.Y);
        }
        return(result);
    }
Example #6
0
        public Assimp.Vector3D GetAssimpPoint()
        {
            Matrix4x4 pos = converter.Matrix3DToAssimpMatrix4x4(Matrix[Session.CurrentSession.CurrentProject.CurrentModel3D.Animation.Tick]);

            Assimp.Vector3D translation = new Assimp.Vector3D();
            Assimp.Quaternion rot = new Assimp.Quaternion();

            // Get the Absolute positions

            pos.DecomposeNoScaling(out rot, out translation);

            // TODO : Get back to relative position
            
            return translation / delta[Session.CurrentSession.CurrentProject.CurrentModel3D.Animation.Tick];
        }
Example #7
0
 /// <summary>
 /// Transform a direction vector by the given Matrix. Note: this is for assimp
 /// matrix which is row major.
 /// </summary>
 /// <param name="vec">The vector to transform</param>
 /// <param name="mat">The desired transformation</param>
 /// <param name="result">The transformed vector</param>
 public static ai.Vector3D eTransformVector(this ai.Matrix4x4 mat, ai.Vector3D vec)
 {
     return(new ai.Vector3D
     {
         X = vec.X * mat.A1
             + vec.Y * mat.B1
             + vec.Z * mat.C1
             + mat.A4,
         Y = vec.X * mat.A2
             + vec.Y * mat.B2
             + vec.Z * mat.C2
             + mat.B4,
         Z = vec.X * mat.A3
             + vec.Y * mat.B3
             + vec.Z * mat.C3
             + mat.C4
     });
 }
Example #8
0
        private Vertex[] ProcessVerticies(Assimp.Mesh assImpMesh)
        {
            List <Assimp.Vector3D> assImpMeshVertices = assImpMesh.Vertices;
            List <Assimp.Vector3D> assImpMeshNormals  = assImpMesh.Normals;
            List <Assimp.Vector3D> assImpMeshTangents = assImpMesh.Tangents;

            List <Assimp.Vector3D>[] assImpMeshTextureCoords = assImpMesh.TextureCoordinateChannels;

            Vertex[] vertices = new Vertex[assImpMeshVertices.Count];
            for (int i = 0; i < assImpMeshVertices.Count; i++)
            {
                Assimp.Vector3D position  = assImpMeshVertices[i];
                Vector3         pos       = new Vector3(position.X, position.Y, position.Z);
                Vector3         normals   = new Vector3(0, 0, 0);
                Vector3         tangent   = new Vector3(0, 0, 0);
                Vector2         texCoords = new Vector2(0, 0);

                if (assImpMesh.HasNormals)
                {
                    Assimp.Vector3D assImpMeshNormal = assImpMeshNormals[i];
                    normals.X = assImpMeshNormal.X;
                    normals.Y = assImpMeshNormal.Y;
                    normals.Z = assImpMeshNormal.Z;
                }

                /*if (assImpMesh.HasTangentBasis) {
                 *  Assimp.Vector3D assImpMeshTangent = assImpMeshTangents[i];
                 *  tangent.X = assImpMeshTangent.X;
                 *  tangent.Y = assImpMeshTangent.Y;
                 *  tangent.Z = assImpMeshTangent.Z;
                 * }*/

                if (assImpMesh.HasTextureCoords(0))
                {
                    Assimp.Vector3D assImpMeshTexCoord = assImpMeshTextureCoords[0][i];
                    texCoords.X = assImpMeshTexCoord.X;
                    texCoords.Y = assImpMeshTexCoord.Y;
                }

                vertices[i] = new Vertex(pos, normals, tangent, texCoords);
            }

            return(vertices);
        }
Example #9
0
        private Mesh <Vertex> proccessCollisionMesh(ai.Mesh mesh, ai.Scene scene)
        {
            List <vec3> vertices = new List <vec3>();
            List <uint> indices  = new List <uint>();

            for (int i = 0; i < mesh.VertexCount; i++)
            {
                ai.Vector3D mvp = mesh.Vertices[i];
                vec3        v   = new vec3(mvp.X, mvp.Y, mvp.Z);
                /*if(!vertices.Contains(v))*/
                vertices.Add(v);
            }

            for (int i = 0; i < mesh.FaceCount; i++)
            {
                for (int j = 0; j < mesh.Faces[i].IndexCount; j++)
                {
                    indices.Add((uint)mesh.Faces[i].Indices[j]);
                }
            }

            return(new CollisionMesh(vertices.ToArray(), indices.ToArray()));
        }
Example #10
0
 public static Vector3 ToNumerics(this Ai.Vector3D value)
 {
     return(new Vector3(value.X, value.Y, value.Z));
 }
Example #11
0
 public static Vector3 AsVector3(this Vector3D self)
 {
     return(new Vector3(self.X, self.Y, self.Z));
 }
Example #12
0
        public static GameObject Load(string meshPath, float scaleX = 1, float scaleY = 1, float scaleZ = 1)
        {
            if (!File.Exists(meshPath))
            {
                return(null);
            }

            AssimpContext importer = new AssimpContext();
            Scene         scene    = importer.ImportFile(meshPath);

            if (scene == null)
            {
                return(null);
            }

            string parentDir = Directory.GetParent(meshPath).FullName;

            // Materials
            List <UnityEngine.Material> uMaterials = new List <Material>();

            if (scene.HasMaterials)
            {
                foreach (var m in scene.Materials)
                {
                    UnityEngine.Material uMaterial = new UnityEngine.Material(Shader.Find("Standard"));

                    // Albedo
                    if (m.HasColorDiffuse)
                    {
                        Color color = new Color(
                            m.ColorDiffuse.R,
                            m.ColorDiffuse.G,
                            m.ColorDiffuse.B,
                            m.ColorDiffuse.A
                            );
                        uMaterial.color = color;
                    }

                    // Emission
                    if (m.HasColorEmissive)
                    {
                        Color color = new Color(
                            m.ColorEmissive.R,
                            m.ColorEmissive.G,
                            m.ColorEmissive.B,
                            m.ColorEmissive.A
                            );
                        uMaterial.SetColor("_EmissionColor", color);
                        uMaterial.EnableKeyword("_EMISSION");
                    }

                    // Reflectivity
                    if (m.HasReflectivity)
                    {
                        uMaterial.SetFloat("_Glossiness", m.Reflectivity);
                    }

                    // Texture
                    if (false && m.HasTextureDiffuse)
                    {
                        Texture2D uTexture    = new Texture2D(2, 2);
                        string    texturePath = Path.Combine(parentDir, m.TextureDiffuse.FilePath);

                        byte[] byteArray = File.ReadAllBytes(texturePath);
                        bool   isLoaded  = uTexture.LoadImage(byteArray);
                        if (!isLoaded)
                        {
                            throw new Exception("Cannot find texture file: " + texturePath);
                        }

                        uMaterial.SetTexture("_MainTex", uTexture);
                    }

                    uMaterials.Add(uMaterial);
                }
            }

            // Mesh
            List <MeshMaterialBinding> uMeshAndMats = new List <MeshMaterialBinding>();

            if (scene.HasMeshes)
            {
                foreach (var m in scene.Meshes)
                {
                    List <Vector3> uVertices = new List <Vector3>();
                    List <Vector3> uNormals  = new List <Vector3>();
                    List <Vector2> uUv       = new List <Vector2>();
                    List <int>     uIndices  = new List <int>();

                    // Vertices
                    if (m.HasVertices)
                    {
                        foreach (var v in m.Vertices)
                        {
                            uVertices.Add(new Vector3(-v.X, v.Y, v.Z));
                        }
                    }

                    // Normals
                    if (m.HasNormals)
                    {
                        foreach (var n in m.Normals)
                        {
                            uNormals.Add(new Vector3(-n.X, n.Y, n.Z));
                        }
                    }

                    // Triangles
                    if (m.HasFaces)
                    {
                        foreach (var f in m.Faces)
                        {
                            // Ignore degenerate faces
                            if (f.IndexCount == 1 || f.IndexCount == 2)
                            {
                                continue;
                            }

                            for (int i = 0; i < (f.IndexCount - 2); i++)
                            {
                                uIndices.Add(f.Indices[i + 2]);
                                uIndices.Add(f.Indices[i + 1]);
                                uIndices.Add(f.Indices[0]);
                            }
                        }
                    }

                    // Uv (texture coordinate)
                    if (m.HasTextureCoords(0))
                    {
                        foreach (var uv in m.TextureCoordinateChannels[0])
                        {
                            uUv.Add(new Vector2(uv.X, uv.Y));
                        }
                    }

                    UnityEngine.Mesh uMesh = new UnityEngine.Mesh();
                    uMesh.vertices  = uVertices.ToArray();
                    uMesh.normals   = uNormals.ToArray();
                    uMesh.triangles = uIndices.ToArray();
                    uMesh.uv        = uUv.ToArray();

                    uMeshAndMats.Add(new MeshMaterialBinding(m.Name, uMesh, uMaterials[m.MaterialIndex]));
                }
            }

            // Create GameObjects from nodes
            GameObject NodeToGameObject(Node node)
            {
                GameObject uOb = new GameObject(node.Name);

                // Set Mesh
                if (node.HasMeshes)
                {
                    foreach (var mIdx in node.MeshIndices)
                    {
                        var uMeshAndMat = uMeshAndMats[mIdx];

                        GameObject uSubOb = new GameObject(uMeshAndMat.MeshName);
                        uSubOb.AddComponent <MeshFilter>();
                        uSubOb.AddComponent <MeshRenderer>();
                        uSubOb.AddComponent <MeshCollider>();

                        uSubOb.GetComponent <MeshFilter>().mesh       = uMeshAndMat.Mesh;
                        uSubOb.GetComponent <MeshRenderer>().material = uMeshAndMat.Material;
                        uSubOb.transform.SetParent(uOb.transform, true);
                        uSubOb.transform.localScale = new Vector3(scaleX, scaleY, scaleZ);
                    }
                }

                // Transform
                // Decompose Assimp transform into scale, rot and translaction
                Assimp.Vector3D   aScale       = new Assimp.Vector3D();
                Assimp.Quaternion aQuat        = new Assimp.Quaternion();
                Assimp.Vector3D   aTranslation = new Assimp.Vector3D();
                node.Transform.Decompose(out aScale, out aQuat, out aTranslation);

                // Convert Assimp transfrom into Unity transform and set transformation of game object
                UnityEngine.Quaternion uQuat = new UnityEngine.Quaternion(aQuat.X, aQuat.Y, aQuat.Z, aQuat.W);
                var euler = uQuat.eulerAngles;

                uOb.transform.localScale    = new UnityEngine.Vector3(aScale.X, aScale.Y, aScale.Z);
                uOb.transform.localPosition = new UnityEngine.Vector3(aTranslation.X, aTranslation.Y, aTranslation.Z);
                uOb.transform.localRotation = UnityEngine.Quaternion.Euler(euler.x, -euler.y, euler.z);

                if (node.HasChildren)
                {
                    foreach (var cn in node.Children)
                    {
                        var uObChild = NodeToGameObject(cn);
                        uObChild.transform.SetParent(uOb.transform, false);
                    }
                }

                return(uOb);
            }

            return(NodeToGameObject(scene.RootNode));;
        }
Example #13
0
 public static OpenTK.Vector3 ToOpenTKVector3(this Assimp.Vector3D vec3)
 {
     return(new OpenTK.Vector3(vec3.X, vec3.Y, vec3.Z));
 }
Example #14
0
 /// <summary>
 /// Convert assimp 3D vector to opentk 2D vector.
 /// </summary>
 public static tk.Vector2 eAs2D_OpenTK(this ai.Vector3D v)
 {
     return(new tk.Vector2(v.X, v.Y));
 }
Example #15
0
 /// <summary>
 /// Convert assimp 3D vector to 2D System.Drawing.Point
 /// for drawing with Graphics object.
 /// </summary>
 public static Point eToPoint(this ai.Vector3D v)
 {
     return(new Point((int)v.X, (int)v.Y));
 }
Example #16
0
 public static Vector3 ToVector3(Assimp.Vector3D v)
 {
     return(new Vector3(v.X, v.Y, v.Z));
 }
Example #17
0
 static Vector3D getMyV3D(Assimp.Vector3D v)
 {
     return(new Vector3D(v.X, v.Y, v.Z));
 }
Example #18
0
 public static Vector3 ToSystemVector3(this Assimp.Vector3D v3)
 {
     return(new Vector3(v3.X, v3.Y, v3.Z));
 }
Example #19
0
        private GeometryModel3D ConvertMesh(Mesh mesh, SystemMaterial[] materials)
        {
            MeshGeometry3D m = new MeshGeometry3D();

            // set vertices
            for (int i = 0; i < mesh.VertexCount; ++i)
            {
                m.Positions.Add(ConvertVertice(mesh.Vertices[i]));
            }

            // set triangle-indices
            for (int i = 0; i < mesh.FaceCount; ++i)
            {
                for (int j = 0; j < mesh.Faces[i].IndexCount; ++j)
                {
                    m.TriangleIndices.Add((int)mesh.Faces[i].Indices[j]);
                }
            }

            // set normals
            for (int i = 0; i < mesh.Normals.Count; ++i)
            {
                m.Normals.Add(new System.Windows.Media.Media3D.Vector3D(
                    mesh.Normals[i].X, mesh.Normals[i].Y, mesh.Normals[i].Z));
            }

            // set texture-coordinates (if needed)
            Assimp.Vector3D[] texCoords = new Assimp.Vector3D[mesh.TextureCoordinateChannels[0].Capacity + 1];
            uint index = 0;
            foreach (Assimp.Vector3D tmp in mesh.TextureCoordinateChannels[0])
            {
                texCoords[index] = tmp;
                ++index;
            }
            if (null != texCoords)
            {
                for (int i = 0; i < texCoords.Length; ++i)
                {
                    m.TextureCoordinates.Add(new Point(texCoords[i].X, 1 - texCoords[i].Y));
                }
            }

            // set material
            System.Windows.Media.Media3D.Material material = null;
            if (mesh.MaterialIndex >= 0 && mesh.MaterialIndex < materials.Length)
            {
                material = materials[mesh.MaterialIndex];
            }
            return new GeometryModel3D(m, material);
        }
Example #20
0
        public Assimp.Quaternion GetAssimpRotation()
        {
            Matrix4x4 pos = converter.Matrix3DToAssimpMatrix4x4(Matrix[Session.CurrentSession.CurrentProject.CurrentModel3D.Animation.Tick]);

            Assimp.Vector3D posTranslation = new Assimp.Vector3D();
            Assimp.Quaternion posRot = new Assimp.Quaternion();

            pos.DecomposeNoScaling(out posRot, out posTranslation);
           
            return posRot;
        }
        /// <summary>
        /// Cherche les noeuds dans l'animation
        /// </summary>
        /// <param name="parentNode">Noeud parent</param>
        /// <param name="parentMatrix">Matrice de base</param>
        /// <param name="ticks">Ticks d'animation</param>
        private void ReadNodeHierarchy(Node parentNode, Matrix4x4 parentMatrix)
        {
            //On recupere le NodeAnim grace au node
            NodeAnimationChannel pNodeAnim = FindNodeByName(parentNode.Name);
            Matrix4x4 finMat = Matrix4x4.Identity;

            if (pNodeAnim != null)
            {
                if (parentNode.Name == "Bip001 Spine")
                    Console.WriteLine("Bip001 Spine");

                Matrix3D absoluteMatrix = this.GetAbsoluteMatrix(out finMat, pNodeAnim, parentMatrix);

                // TODO : Found the delta for saving data after modification
                
                var deltaX = finMat.A4 / pNodeAnim.PositionKeys[0].Value.X;
                var deltaY = finMat.B4 / pNodeAnim.PositionKeys[0].Value.Y;
                var deltaZ = finMat.C4 / pNodeAnim.PositionKeys[0].Value.Z;

                Assimp.Vector3D delta = new Assimp.Vector3D(deltaX, deltaY, deltaZ);

                //var test1 = finMat.C4 / deltaZ;
                //var test2 = pNodeAnim.PositionKeys[0].Value.Z * deltaZ;
                //var result1 = (test1 == pNodeAnim.PositionKeys[0].Value.Z);
                //var result2 = (test2 == finMat.C4);

                SetJoint(pNodeAnim.NodeName, absoluteMatrix, delta);
            }
            for (int i = 0; i < parentNode.ChildCount; i++)
            {
                ReadNodeHierarchy(parentNode.Children[i], finMat);
                if (parentNode.HasChildren)
                {
                    NodeAnimationChannel cNodeAnim = FindNodeByName(parentNode.Children[i].Name);

                    if (cNodeAnim != null)
                        SetBone(parentNode.Name, parentNode.Children[i].Name);
                }
            }
        }
Example #22
0
        public void Build(
            string filename,
            string intermediateDir,
            string outputDir,
            MyModelConfiguration configuration,
            byte[] havokCollisionShapes,
            bool checkOpenBoundaries,
            float[] lodDistances,
            bool overrideLods,
            Func <string, MyMaterialConfiguration> getMaterialByRef,
            IMyBuildLogger logger)
        {
            logger.LogMessage(MessageType.Info, "**FileName: " + filename);

            string withoutExtension = Path.GetFileNameWithoutExtension(filename);

            logger.LogMessage(MessageType.Info, "**Filename (without extension): " + withoutExtension);

            string directoryName = Path.GetDirectoryName(filename);

            logger.LogMessage(MessageType.Info, "**Directory Name: " + directoryName);

            //string contentDirectoryString = "content";
            // int numberOfPathCharactersToCull = directoryName.ToLower().LastIndexOf(contentDirectoryString) + contentDirectoryString.Length + 1;

            var numberOfPathCharactersToCull = filename.LastIndexOf("models\\", StringComparison.OrdinalIgnoreCase);

            if (numberOfPathCharactersToCull == -1)
            {
                throw new Exception("Couldn't find 'models\\' in path provided: " + filename);
            }

            logger.LogMessage(MessageType.Info, "**Number of characters to cull: " + numberOfPathCharactersToCull);
            string culledPath = directoryName.Substring(numberOfPathCharactersToCull, directoryName.Length - numberOfPathCharactersToCull); // Used to cull 'content' from path name to create relative pathing.

            logger.LogMessage(MessageType.Info, "**Culled Path: " + culledPath);

            directoryName.Substring(0, numberOfPathCharactersToCull);
            Path.Combine(directoryName, withoutExtension + ".FBX");
            AssimpContext assimpContext = new AssimpContext();

            assimpContext.SetConfig((PropertyConfig) new NormalSmoothingAngleConfig(66f));
            assimpContext.SetConfig((PropertyConfig) new FBXPreservePivotsConfig(false));
            Scene scene = assimpContext.ImportFile(filename,
                                                   PostProcessSteps.CalculateTangentSpace |
                                                   PostProcessSteps.JoinIdenticalVertices |
                                                   PostProcessSteps.Triangulate |
                                                   PostProcessSteps.GenerateSmoothNormals |
                                                   PostProcessSteps.SplitLargeMeshes |
                                                   PostProcessSteps.LimitBoneWeights |
                                                   PostProcessSteps.SortByPrimitiveType |
                                                   PostProcessSteps.FindInvalidData |
                                                   PostProcessSteps.GenerateUVCoords |
                                                   PostProcessSteps.FlipWindingOrder);

            string outputDir1 = outputDir;

            if (scene.MeshCount == 0 && scene.AnimationCount == 0)
            {
                throw new Exception("Number of meshes is 0 and no animation present!");
            }
            else
            {
                logger.LogMessage(MessageType.Info, "Found " + scene.MeshCount + " meshe(s).", "Meshes");
                logger.LogMessage(MessageType.Info, "Found " + scene.AnimationCount + " animation(s).", "Animations");
            }

            #region check UV for 0-sized faces
            if (scene.MeshCount > 0)
            {
                void LogUVError(Assimp.Mesh mesh, string message)
                {
                    //logger.LogMessage(MessageType.Error, $"Mesh '{mesh.Name}' {message}");
                    throw new Exception($"Mesh '{mesh.Name}' {message}");
                }

                for (int meshIdx = 0; meshIdx < scene.MeshCount; meshIdx++)
                {
                    Assimp.Mesh mesh = scene.Meshes[meshIdx];

                    if (mesh.TextureCoordinateChannels == null || mesh.TextureCoordinateChannels.Length == 0)
                    {
                        LogUVError(mesh, "has no UV map/channel!");
                        continue;
                    }

                    int channels = 1; // don't care about other channels; if you want to, replace with: mesh.TextureCoordinateChannels.Length;
                    for (int chIdx = 0; chIdx < channels; chIdx++)
                    {
                        if (!mesh.HasTextureCoords(0))
                        {
                            LogUVError(mesh, "has no UV map/channel!");
                            continue;
                        }

                        List <Assimp.Vector3D> vectors = mesh.TextureCoordinateChannels[chIdx];
                        if (vectors == null || vectors.Count == 0)
                        {
                            LogUVError(mesh, "has no UV vectors in first map/channel!");
                            continue;
                        }

                        //Console.WriteLine($"  channel={chIdx}");
                        //for (int v = 0; v < vectors.Count; v++)
                        //{
                        //    Console.WriteLine($"  {v} == {vectors[v]}");
                        //}

                        Assimp.Vector3D?lastVec       = null;
                        int             sameVecInARow = 1;

                        // these can be triangles, quads and prob more... so not safe to assume they're in pairs of 3.
                        for (int v = 0; v < vectors.Count; v++)
                        {
                            Assimp.Vector3D vec = vectors[v];

                            if (!lastVec.HasValue)
                            {
                                lastVec = vec;
                            }
                            else
                            {
                                if (lastVec.Value == vec)
                                {
                                    sameVecInARow++;

                                    if (sameVecInARow >= 3)
                                    {
                                        // Changed this to a warning instead of a LogUVError
                                        logger.LogMessage(MessageType.Warning, mesh.ToString() + "has UV with 3 identical vectors in a row, this likely means you have a face with an UV is 0-size which will cause SE to make the entire model shaderless.");
                                        break;
                                    }
                                }
                                else
                                {
                                    lastVec       = vec;
                                    sameVecInARow = 1;
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            if (scene.MaterialCount > 0)
            {
                List <MyMaterialConfiguration> materialConfigurationList = new List <MyMaterialConfiguration>();
                for (int index = 0; index < scene.MaterialCount; ++index)
                {
                    MyMaterialConfiguration materialConfiguration = getMaterialByRef(scene.Materials[index].Name);
                    if (materialConfiguration != null)
                    {
                        materialConfigurationList.Add(materialConfiguration);
                    }
                }
                if (materialConfigurationList.Count > 0)
                {
                    configuration.Materials = configuration.Materials != null ? ((IEnumerable <MyMaterialConfiguration>)configuration.Materials).Union <MyMaterialConfiguration>((IEnumerable <MyMaterialConfiguration>)materialConfigurationList.ToArray()).ToArray <MyMaterialConfiguration>() : materialConfigurationList.ToArray();
                }
            }

            MyModelProcessor processor = this.CreateProcessor(configuration);
            if (configuration.Materials != null)
            {
                foreach (MyMaterialConfiguration material in configuration.Materials)
                {
                    try
                    {
                        Dictionary <string, object> dictionary = new Dictionary <string, object>();
                        if (processor.MaterialProperties.Keys.Contains <string>(material.Name))
                        {
                            logger.LogMessage(MessageType.Warning, "Material: " + material.Name + " is already defined in the processor. Not adding it again..", filename);
                        }
                        else
                        {
                            processor.MaterialProperties.Add(material.Name, dictionary);
                            foreach (MyModelParameter parameter in material.Parameters)
                            {
                                dictionary.Add(parameter.Name, (object)parameter.Value);
                            }
                        }
                    }
                    catch (ArgumentException ex)
                    {
                        logger.LogMessage(MessageType.Warning, "Problem when processing materials: " + ex.Message, filename);
                    }
                }
            }
            int num2 = 999;
            List <MyLODDescriptor> myLodDescriptorList = new List <MyLODDescriptor>();
            for (int index = 0; index < num2; ++index)
            {
                string path = Path.Combine(directoryName, withoutExtension + "_LOD" + (object)(index + 1)) + ".fbx";
                string str2 = Path.Combine(culledPath, withoutExtension + "_LOD" + (object)(index + 1));

                if (File.Exists(path))
                {
                    if (overrideLods && lodDistances != null && (index < lodDistances.Length && (double)lodDistances[index] > 0.0))
                    {
                        MyLODDescriptor myLodDescriptor = new MyLODDescriptor()
                        {
                            Distance = lodDistances[index],
                            Model    = str2
                        };
                        myLodDescriptorList.Add(myLodDescriptor);
                    }
                    else if (configuration.LODs != null && index < configuration.LODs.Length)
                    {
                        MyLODConfiguration loD             = configuration.LODs[index];
                        MyLODDescriptor    myLodDescriptor = new MyLODDescriptor()
                        {
                            Distance      = loD.Distance,
                            Model         = str2,
                            RenderQuality = loD.RenderQuality
                        };


                        if (str2.ToLower() != loD.Model.ToLower())
                        {
                            logger.LogMessage(MessageType.Warning, "LOD" + (object)(index + 1) + " name differs " + str2 + " and " + loD.Model, filename);
                        }
                        myLodDescriptorList.Add(myLodDescriptor);
                    }
                    else
                    {
                        logger.LogMessage(MessageType.Warning, "LOD" + (object)(index + 1) + " model exists but configuration is missing", filename);
                    }
                }
                else if (configuration.LODs != null && index < configuration.LODs.Length)
                {
                    logger.LogMessage(MessageType.Warning, "LOD model " + configuration.LODs[index].Model + " is missing", filename);
                }
                else
                {
                    break;
                }
            }
            processor.LODs                 = myLodDescriptorList.ToArray();
            processor.BoneGridMapping      = configuration.BoneGridSize;
            processor.BoneMapping          = configuration.BoneMapping != null ? ((IEnumerable <MyModelVector>)configuration.BoneMapping).Select <MyModelVector, Vector3>((Func <MyModelVector, Vector3>)(s => new Vector3((float)s.X, (float)s.Y, (float)s.Z))).ToArray <Vector3>() : (Vector3[])null;
            processor.HavokCollisionShapes = havokCollisionShapes;
            processor.Process(scene, filename, outputDir1, checkOpenBoundaries, logger);
            if (configuration.BoneGridSize.HasValue)
            {
                configuration.BoneMapping = ((IEnumerable <Vector3>)processor.BoneMapping).Select <Vector3, MyModelVector>((Func <Vector3, MyModelVector>)(s => (MyModelVector)s)).ToArray <MyModelVector>();
            }
            List <MyMaterialConfiguration> materialConfigurationList1 = new List <MyMaterialConfiguration>();
            foreach (KeyValuePair <string, Dictionary <string, object> > materialProperty in processor.MaterialProperties)
            {
                materialConfigurationList1.Add(new MyMaterialConfiguration()
                {
                    Name       = materialProperty.Key,
                    Parameters = MyModelBuilder.GetParameters(materialProperty)
                });
            }
            configuration.Materials = materialConfigurationList1.Count <= 0 ? (MyMaterialConfiguration[])null : materialConfigurationList1.ToArray();
            if (processor.LODs == null)
            {
                return;
            }
            List <MyLODConfiguration> lodConfigurationList = new List <MyLODConfiguration>();
            foreach (MyLODDescriptor loD in processor.LODs)
            {
                lodConfigurationList.Add(new MyLODConfiguration()
                {
                    Distance      = loD.Distance,
                    Model         = loD.Model,
                    RenderQuality = loD.RenderQuality
                });
            }
            configuration.LODs = lodConfigurationList.ToArray();
        }
 public static Vector3 ToNumerics(this Ai.Vector3D value) =>
 new Vector3(value.X, value.Y, value.Z);
Example #24
0
 public OpenTK.Vector2 Cv2(Assimp.Vector3D o)
 {
     return(new OpenTK.Vector2(o.X, o.Y));
 }
Example #25
0
 /// <summary>
 /// Convert assimp 3D vector to 2D System.Drawing.PointF (floating point)
 /// for drawing with Graphics object.
 /// </summary>
 public static PointF eToPointFloat(this ai.Vector3D v)
 {
     return(new PointF(v.X, v.Y));
 }
Example #26
0
 public static ai.Matrix4x4 eSnapTranslation(this ai.Matrix4x4 m, ai.Vector3D vec)
 {
     throw new NotImplementedException("Either make this method for assimp use, or change to OpenTK matrices!");
 }
Example #27
0
 /// <summary>
 /// Convert assimp 3D vector to opentk 3D vector.
 /// </summary>
 public static tk.Vector3 eToOpenTK(this ai.Vector3D v)
 {
     return(new tk.Vector3(v.X, v.Y, v.Z));
 }
Example #28
0
        private void Convertobjwtexture(object sender, DoWorkEventArgs e)
        {
            try
            {
                Scene scene = new AssimpImporter().ImportFile(file, PostProcessSteps.Triangulate);

                coloredpoints = new Dictionary <Point3D, Point3D>();
                //List<Triangle> splittriangles = new List<Triangle>();
                //pointlist = new HashSet<Point3D>();


                //pointlist.ToDictionary<>
                int progress = 0;
                int total    = 0;

                foreach (Mesh m in scene.Meshes)
                {
                    foreach (Face face in m.Faces)
                    {
                        total++;
                    }
                }
                foreach (Mesh m in scene.Meshes)
                {
                    var texturecoords = m.GetTextureCoords(0);

                    foreach (Face face in m.Faces)
                    {
                        IList <Point3D> vertices      = new List <Point3D>();
                        IList <Point3D> texturepoints = new List <Point3D>();
                        foreach (uint i in face.Indices)
                        {
                            double          x = m.Vertices[i].X * scale;
                            double          y = m.Vertices[i].Y * scale;
                            double          z = m.Vertices[i].Z * scale;
                            Point3D         point;
                            Assimp.Vector3D texturep     = texturecoords[i];
                            Point3D         texturepoint = new Point3D(texturep.X, 1 - texturep.Y, texturep.Z);
                            if (flipyz)
                            {
                                if (flipxz)
                                {
                                    point = new Point3D(y, z, flipz * x);
                                }
                                else
                                {
                                    point = new Point3D(x, z, flipz * y);
                                }
                            }
                            else
                            {
                                if (flipxz)
                                {
                                    point = new Point3D(z, y, flipz * x);
                                }
                                else
                                {
                                    point = new Point3D(x, y, flipz * z);
                                }
                            }
                            vertices.Add(point);
                            texturepoints.Add(texturepoint);
                            Point3D flooredpoint = new Point3D((int)Math.Floor(point.X), (int)Math.Floor(point.Y), (int)Math.Floor(point.Z));
                            if (!coloredpoints.ContainsKey(flooredpoint))
                            {
                                coloredpoints.Add(flooredpoint, texturepoint);
                            }
                        }
                        if (vertices.Count == 3)
                        {
                            ColorTriangle triangle = new ColorTriangle(vertices, texturepoints);
                            if (!triangle.BoundsSmallerThan(bounds))
                            {
                                Splitcolortriangles(triangle);
                            }
                        }
                        else
                        {
                        }
                        progress++;
                        backgroundWorker.ReportProgress((progress * 100) / total);
                        if (backgroundWorker.CancellationPending)
                        {
                            e.Cancel = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!(ex is OperationCanceledException))
                {
                    System.Windows.MessageBox.Show(ex.Message, "Something went wrong converting the obj+texture");
                }
                else
                {
                    e.Cancel = true;
                }
            }

            try
            {
                if (backgroundWorker.CancellationPending)
                {
                    throw new OperationCanceledException();
                }

                dynamic blueprint = new JObject();
                try
                {
                    Bitmap texturemap = new Bitmap(this.texture);
                    HashSet <Tuple <Point3D, string> > pointswithcolor = new HashSet <Tuple <Point3D, string> >();
                    int width  = texturemap.Width;
                    int height = texturemap.Height;
                    foreach (var pair in coloredpoints)
                    {
                        int x = (int)(pair.Value.X * width);
                        int y = (int)(pair.Value.Y * height);
                        if (pair.Value.Y > 1)
                        {
                        }
                        while (y < 0)
                        {
                            y++;
                        }
                        while (x < 0)
                        {
                            x++;
                        }
                        if (Math.Abs(x) > width / 2)
                        {
                        }
                        while (x >= width)
                        {
                            x -= width;
                        }
                        while (y >= height)
                        {
                            y -= height;
                        }
                        System.Drawing.Color color = texturemap.GetPixel(x, y);
                        string c = color.Name.Substring(2);
                        pointswithcolor.Add(new Tuple <Point3D, string>(pair.Key, c));
                    }
                    coloredpoints.Clear();
                    blueprint = BlueprintOptimizer.CreateBlueprintFromPointsAndColor(pointswithcolor);
                }
                catch (Exception bpex)
                {
                    System.Windows.MessageBox.Show(bpex.Message, "Something went wrong building the blueprint");
                }
                int    amountgenerated = blueprint.bodies[0].childs.Count;
                string message         = "converted obj to blueprint with " + amountgenerated + " blocks !";
                //MessageBox.Show(message+"\n\nOptimized to: "+count+" shapes");
                Random  r             = new Random();
                string  blueprintpath = Database.User_ + "\\Blueprints\\Generatedblueprintobj-" + r.Next() + r.Next();
                dynamic description   = new JObject();
                description.description = "generated obj blueprint with " + amountgenerated + " block";
                description.name        = "generated blueprint" + r.Next();
                description.type        = "Blueprint";
                description.version     = 0;
                new Task(() =>
                {
                    System.Windows.MessageBox.Show(message + "\nPLEASE WAIT for the rendering to complete");
                }).Start();
                if (BP.Blueprintpath == null)
                {//no blueprint exists, initialize new one
                    new BP(blueprintpath, blueprint, description);
                }
                else
                {//overwrite current blueprint
                    BP.setblueprint(blueprint);
                    BP.Description.description += message;
                }
            }
            catch (Exception exc)
            {
                System.Windows.MessageBox.Show(exc.Message, "error");
            }
        }
Example #29
0
 public static OpenTK.Vector2 ToOpenTKVector2(this Assimp.Vector3D vec3)
 {
     return(new OpenTK.Vector2(vec3.X, vec3.Y));
 }
Example #30
0
 public bool BoundsSmallerThan(Assimp.Vector3D bounds)
 {
     return(Math.Abs(vertices[0].X - vertices[1].X) < bounds.X && Math.Abs(vertices[0].X - vertices[2].X) < bounds.X && Math.Abs(vertices[2].X - vertices[1].X) < bounds.X &&
            Math.Abs(vertices[0].Y - vertices[1].Y) < bounds.Y && Math.Abs(vertices[0].Y - vertices[2].Y) < bounds.Y && Math.Abs(vertices[2].Y - vertices[1].Y) < bounds.Y &&
            Math.Abs(vertices[0].Z - vertices[1].Z) < bounds.Z && Math.Abs(vertices[0].Z - vertices[2].Z) < bounds.Z && Math.Abs(vertices[2].Z - vertices[1].Z) < bounds.Z);
 }
Example #31
0
 public static Point AsUvPoint(this Vector3D self)
 {
     return(new Point(self.X, 1 - self.Y));
 }
Example #32
0
        private Mesh <Vertex> proccessMesh(ai.Mesh mesh, ai.Scene scene)
        {
            //Vertex[] vertices = new Vertex[mesh.VertexCount];
            //uint[] indices = new uint[mesh.FaceCount * 3];
            List <Vertex> vertices = new List <Vertex>();
            List <uint>   indices  = new List <uint>();

            ImageTexture[] textures;

            for (int i = 0; i < mesh.VertexCount; i++)
            {
                Vertex v = new Vertex();

                ai.Vector3D mvp = mesh.Vertices[i];
                v.Position = new vec3(mvp.X, mvp.Y, mvp.Z);

                ai.Vector3D mvn = mesh.Normals[i];
                v.Normal = new vec3(mvn.X, mvn.Y, mvn.Z);

                ai.Vector3D mvt = mesh.Tangents[i];
                v.Tangent = new vec3(mvt.X, mvt.Y, mvt.Z);

                ai.Vector3D mvb = mesh.BiTangents[i];
                v.Bitangent = new vec3(mvb.X, mvb.Y, mvb.Z);

                if (mesh.TextureCoordinateChannelCount > 0)
                {
                    ai.Vector3D mvc = mesh.TextureCoordinateChannels[0][i];
                    v.TexCoords = new vec2(mvc.X, mvc.Y);
                }
                else
                {
                    v.TexCoords = new vec2(0, 0);
                }

                vertices.Add(v);
            }

            for (int i = 0; i < mesh.FaceCount; i++)
            {
                for (int j = 0; j < mesh.Faces[i].IndexCount; j++)
                {
                    indices.Add((uint)mesh.Faces[i].Indices[j]);
                }
            }

            if (mesh.MaterialIndex >= 0)
            {
                ai.Material material = scene.Materials[mesh.MaterialIndex];

                List <ImageTexture> tempTextures = new List <ImageTexture>();

                ImageTexture[] diffuse = loadMaterialTextures(material, ai.TextureType.Diffuse, TextureType.Diffuse);
                tempTextures.AddRange(diffuse);

                ImageTexture[] specular = loadMaterialTextures(material, ai.TextureType.Specular, TextureType.Specular);
                tempTextures.AddRange(specular);

                ImageTexture[] normal = loadMaterialTextures(material, ai.TextureType.Height, TextureType.Normal);
                tempTextures.AddRange(normal);

                textures = tempTextures.ToArray();
            }
            else
            {
                textures = new ImageTexture[0];
            }

            return(new ModelMesh(vertices.ToArray(), indices.ToArray(), textures));
        }
Example #33
0
 public OpenTK.Vector3 Cv(Assimp.Vector3D o)
 {
     return(new OpenTK.Vector3(o.X, o.Y, o.Z));
 }
Example #34
0
 private Vector3 Vector3DToVector3(Assimp.Vector3D vec)
 {
     return(new Vector3(vec.X, vec.Y, vec.Z));
 }