Exemple #1
0
        public static MeshData[] LoadModelFromFile(string filename)
        {
            var importer = new AssimpContext();

            if (!importer.IsImportFormatSupported(System.IO.Path.GetExtension(filename)))
            {
                throw new ArgumentException($"Model format {System.IO.Path.GetExtension(filename)} is not supported. Cannot load {filename}.", nameof(filename));
            }
            var             postProcessFlags = PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace;
            var             model            = importer.ImportFile(filename, postProcessFlags);
            List <MeshData> meshDatas        = new List <MeshData>(model.MeshCount);
            MeshData        meshData         = new MeshData();

            foreach (var mesh in model.Meshes)
            {
                List <MyVertex> myVertices = new List <MyVertex>(mesh.VertexCount);
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    var pos = mesh.HasVertices ? mesh.Vertices[i].ToVector3() : new Vector3();

                    var norm = mesh.HasNormals ? mesh.Normals[i] : new Vector3D();
                    var texC = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0][i] : new Vector3D(1, 1, 0);
                    var v    = new MyVertex(pos, norm.ToVector3(), texC.ToVector2());
                    myVertices.Add(v);
                }
                var indices = mesh.GetIndices().ToList();
                meshData.Vertices = myVertices.ToArray();
                meshData.Indices  = indices.ToArray();
                meshDatas.Add(meshData);
            }
            return(meshDatas.ToArray());
        }
Exemple #2
0
        public ModelUtil(string file)
        {
            AssimpContext importer = new AssimpContext();

            fileInfo = new FileInfo(file);

            if (fileInfo.Exists && importer.IsImportFormatSupported(fileInfo.Extension))
            {
                scene = importer.ImportFile(file,
                                            PostProcessSteps.GenerateNormals |
                                            PostProcessSteps.CalculateTangentSpace |
                                            PostProcessSteps.Triangulate);
            }
            else
            {
                Console.WriteLine("Extension <{0}> isn't supported!", fileInfo.Extension);
            }

            name = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf('.'));

            string outDir = fileInfo.DirectoryName + @"\" + name;

            if (!Directory.Exists(outDir))
            {
                outDirInfo = Directory.CreateDirectory(outDir);
            }
            else
            {
                outDirInfo = new DirectoryInfo(outDir);
            }
        }
        public void Create(Device1 device)
        {
            PrimitiveTopology = PrimitiveTopology.TriangleList;
            VertexStride      = Marshal.SizeOf <VertexPosColNormTex>();

            var verts = new List <VertexPosColNormTex>();

            var importer = new AssimpContext();
            var s        = importer.GetSupportedImportFormats();

            if (!importer.IsImportFormatSupported(Path.GetExtension(_FileName)))
            {
                throw new ArgumentException(
                          "Model format " + Path.GetExtension(_FileName) + " is not supported!  Cannot load {1}", "filename");
            }

            var model = importer.ImportFile(_FileName,
                                            PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace | PostProcessSteps.Triangulate);

            foreach (var mesh in model.Meshes)
            {
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    var pos   = new Vector3(mesh.Vertices[i].X, mesh.Vertices[i].Y, mesh.Vertices[i].Z);
                    var color = Color.AliceBlue;
                    var norm  = new Vector3(mesh.Normals[i].X, mesh.Normals[i].Y, mesh.Normals[i].Z);
                    var tx    = new Vector2(mesh.TextureCoordinateChannels[0][i].X, -mesh.TextureCoordinateChannels[0][i].Y);

                    verts.Add(new VertexPosColNormTex(pos, color, norm, tx));
                }
                var bufferDesc = new BufferDescription
                {
                    Usage          = ResourceUsage.Immutable,
                    BindFlags      = BindFlags.VertexBuffer,
                    SizeInBytes    = VertexStride * verts.Count,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags    = ResourceOptionFlags.None
                };
                VertexBuffer = new Buffer(device, DataStream.Create(verts.ToArray(), false, false), bufferDesc);

                IndexCount = mesh.GetIndices().Length;
                //buffer creations

                bufferDesc = new BufferDescription
                {
                    Usage          = ResourceUsage.Immutable,
                    BindFlags      = BindFlags.IndexBuffer,
                    SizeInBytes    = sizeof(uint) * IndexCount,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags    = ResourceOptionFlags.None
                };
                IndexBuffer = new Buffer(device, DataStream.Create(mesh.GetIndices(), false, false), bufferDesc);
            }
        }
Exemple #4
0
        public static ResourceType GetResourceTypeFromFile(string fullPath)
        {
            // Check if it's an image
            if (FreeImage.GetFileType(fullPath, 0) != FREE_IMAGE_FORMAT.FIF_UNKNOWN ||
                FreeImage.GetFIFFromFilename(fullPath) != FREE_IMAGE_FORMAT.FIF_UNKNOWN)
            {
                return(ResourceType.Texture);
            }
            // Check if it's a model
            var assimp = new AssimpContext();

            return(assimp.IsImportFormatSupported(Path.GetExtension(fullPath)) ? ResourceType.Model : ResourceType.Unknown);
            // Unknown resource type, out of luck
        }
        public void TestSupportedFormats()
        {
            AssimpContext importer = new AssimpContext();

            ExportFormatDescription[] exportDescs = importer.GetSupportedExportFormats();

            String[] importFormats = importer.GetSupportedImportFormats();

            Assert.IsNotNull(exportDescs);
            Assert.IsNotNull(importFormats);
            Assert.IsTrue(exportDescs.Length >= 1);
            Assert.IsTrue(importFormats.Length >= 1);

            Assert.IsTrue(importer.IsExportFormatSupported(exportDescs[0].FileExtension));
            Assert.IsTrue(importer.IsImportFormatSupported(importFormats[0]));
        }
Exemple #6
0
        public Model(string file, D3D11.Device device, Matrix transform)
        {
            AssimpContext ctx = new AssimpContext();

            if (!ctx.IsImportFormatSupported(Path.GetExtension(file)))
            {
                return;
            }

            modelPath = Path.GetDirectoryName(file);

            Scene scene = ctx.ImportFile(file);
            Node  node  = scene.RootNode;

            Meshes = new List <ModelMesh>();
            AddNode(scene, scene.RootNode, device, Matrix.Identity, transform);

            constants         = new Constants();
            SpecularColor     = Color.White;
            Shininess         = 200;
            SpecularIntensity = 1;
            EmissiveIntensity = 1;
        }
Exemple #7
0
        public static void LoadSource(this RMesh rmesh, string filename)
        {
            AssimpContext context = new AssimpContext();

            context.SetConfig(new Assimp.Configs.FBXImportAllMaterialsConfig(true));
            context.SetConfig(new Assimp.Configs.FBXImportAllGeometryLayersConfig(true));
            context.SetConfig(new Assimp.Configs.MultithreadingConfig(2));
            context.SetConfig(new Assimp.Configs.FBXStrictModeConfig(false));
            if (!context.IsImportFormatSupported(Path.GetExtension(filename)))
            {
                throw new ReactorException("Attempted to load a model that Assimp doesn't know how to load");
            }
            LogStream log = new LogStream((msg, user) => {
                RLog.Info(msg.Remove(msg.Length - 2));
            });

            log.Attach();
            int   platform = (int)Environment.OSVersion.Platform;
            Scene scene    = context.ImportFile(filename,
                                                PostProcessSteps.FindInvalidData |
                                                PostProcessSteps.GenerateSmoothNormals |
                                                PostProcessSteps.Triangulate |
                                                PostProcessSteps.GenerateUVCoords |
                                                PostProcessSteps.CalculateTangentSpace |
                                                PostProcessSteps.PreTransformVertices);

            if (scene.HasMeshes)
            {
                foreach (Mesh mesh in scene.Meshes)
                {
                    if (!mesh.HasVertices)
                    {
                        continue;
                    }
                    RMeshPart rmeshpart = RMeshPart.Create <RMeshPart> ();


                    RVertexData [] data = new RVertexData [mesh.VertexCount];

                    List <int> indicesList = new List <int> ();

                    if (mesh.HasFaces)
                    {
                        foreach (Face face in mesh.Faces)
                        {
                            indicesList.AddRange(face.Indices.ToArray());
                            foreach (int index in face.Indices)
                            {
                                Vector3D p = mesh.Vertices [index];
                                data [index].Position = new Vector3(p.X, p.Y, p.Z);
                                if (mesh.HasTextureCoords(0))
                                {
                                    Vector3D t = mesh.TextureCoordinateChannels [0] [index];
                                    data [index].TexCoord = new Vector2(t.X, -t.Y);
                                }

                                if (mesh.HasNormals)
                                {
                                    Vector3D n = mesh.Normals [index];
                                    data [index].Normal = new Vector3(n.X, n.Y, n.Z);
                                }

                                if (mesh.HasTangentBasis)
                                {
                                    Vector3D b = mesh.BiTangents [index];
                                    Vector3D t = mesh.Tangents [index];
                                    data [index].Bitangent = new Vector3(b.X, b.Y, b.Z);
                                    data [index].Tangent   = new Vector3(t.X, t.Y, t.Z);
                                }
                            }
                        }
                    }



                    RVertexBuffer vbuffer = new RVertexBuffer(typeof(RVertexData), mesh.VertexCount, RBufferUsage.WriteOnly, true);


                    RIndexBuffer ibuffer = new RIndexBuffer(typeof(int), indicesList.Count, RBufferUsage.WriteOnly);
                    ibuffer.SetData(indicesList.ToArray());

                    vbuffer.SetData <RVertexData> (data);

#if WINDOWS
                    var separator = "\\";
#else
                    var separator = "/";
#endif

                    rmeshpart.VertexBuffer = vbuffer;
                    rmeshpart.IndexBuffer  = ibuffer;

                    RMaterial material = new RMaterial(rmesh.Name + ":Material");

                    if (scene.HasMaterials)
                    {
                        Material mat = scene.Materials[mesh.MaterialIndex];
                        material.Shininess = mat.Shininess;
                        material.SetColor(RMaterialColor.DIFFUSE, new RColor(mat.ColorDiffuse.R, mat.ColorDiffuse.G, mat.ColorDiffuse.B, mat.ColorDiffuse.A));
                        if (mat.HasTextureDiffuse)
                        {
                            var        texFileName = Path.GetFileName(mat.TextureDiffuse.FilePath.Replace("\\", separator).Replace("/", separator));
                            RTexture2D tex         = (RTexture2D)RTextures.Instance.CreateTexture <RTexture2D>(texFileName, "/textures/" + texFileName.ToLower());
                            tex.Bind();
                            tex.GenerateMipmaps();
                            tex.SetTextureMagFilter(RTextureMagFilter.Linear);
                            tex.SetTextureMinFilter(RTextureMinFilter.LinearMipmapLinear);
                            tex.SetTextureWrapMode(RTextureWrapMode.Repeat, RTextureWrapMode.Repeat);
                            tex.Unbind();
                            material.SetTexture(RTextureLayer.DIFFUSE, tex);
                        }
                        if (mat.HasTextureNormal)
                        {
                            var        texFileName = Path.GetFileName(mat.TextureNormal.FilePath.Replace("\\", separator).Replace("/", separator));
                            RTexture2D tex         = (RTexture2D)RTextures.Instance.CreateTexture <RTexture2D>(texFileName, "/textures/" + texFileName.ToLower());
                            tex.Bind();
                            tex.GenerateMipmaps();
                            tex.SetTextureMagFilter(RTextureMagFilter.Linear);
                            tex.SetTextureMinFilter(RTextureMinFilter.LinearMipmapLinear);
                            tex.SetTextureWrapMode(RTextureWrapMode.Repeat, RTextureWrapMode.Repeat);
                            tex.Unbind();
                            material.SetTexture(RTextureLayer.NORMAL, tex);
                        }
                        if (mat.HasTextureAmbient)
                        {
                            var        texFileName = Path.GetFileName(mat.TextureAmbient.FilePath.Replace("\\", separator).Replace("/", separator));
                            RTexture2D tex         = (RTexture2D)RTextures.Instance.CreateTexture <RTexture2D>(texFileName, "/textures/" + texFileName.ToLower());
                            tex.SetTextureMagFilter(RTextureMagFilter.Linear);
                            tex.SetTextureMinFilter(RTextureMinFilter.LinearMipmapLinear);
                            tex.SetTextureWrapMode(RTextureWrapMode.Repeat, RTextureWrapMode.Repeat);
                            material.SetTexture(RTextureLayer.AMBIENT, tex);
                        }
                        if (mat.HasTextureHeight)
                        {
                            var        texFileName = Path.GetFileName(mat.TextureHeight.FilePath.Replace("\\", separator).Replace("/", separator));
                            RTexture2D tex         = (RTexture2D)RTextures.Instance.CreateTexture <RTexture2D>(texFileName, "/textures/" + texFileName.ToLower());
                            tex.SetTextureMagFilter(RTextureMagFilter.Linear);
                            tex.SetTextureMinFilter(RTextureMinFilter.LinearMipmapLinear);
                            tex.SetTextureWrapMode(RTextureWrapMode.Repeat, RTextureWrapMode.Repeat);
                            material.SetTexture(RTextureLayer.HEIGHT, tex);
                        }
                        if (mat.HasTextureEmissive)
                        {
                            var        texFileName = Path.GetFileName(mat.TextureEmissive.FilePath.Replace("\\", separator).Replace("/", separator));
                            RTexture2D tex         = (RTexture2D)RTextures.Instance.CreateTexture <RTexture2D>(texFileName, "/textures/" + texFileName.ToLower());
                            tex.SetTextureMagFilter(RTextureMagFilter.Linear);
                            tex.SetTextureMinFilter(RTextureMinFilter.LinearMipmapLinear);
                            tex.SetTextureWrapMode(RTextureWrapMode.Repeat, RTextureWrapMode.Repeat);
                            material.SetTexture(RTextureLayer.GLOW, tex);
                        }
                        if (mat.HasTextureSpecular)
                        {
                            var        texFileName = Path.GetFileName(mat.TextureSpecular.FilePath.Replace("\\", separator).Replace("/", separator));
                            RTexture2D tex         = (RTexture2D)RTextures.Instance.CreateTexture <RTexture2D>(texFileName, "/textures/" + texFileName.ToLower());
                            tex.SetTextureMagFilter(RTextureMagFilter.Linear);
                            tex.SetTextureMinFilter(RTextureMinFilter.LinearMipmapLinear);
                            tex.SetTextureWrapMode(RTextureWrapMode.Repeat, RTextureWrapMode.Repeat);
                            material.SetTexture(RTextureLayer.SPECULAR, tex);
                        }
                    }
                    rmeshpart.Material = material;
                    rmesh.Parts.Add(rmeshpart);
                }
                //return rmesh;
            }
            //return null;
            if (rmesh.Parts.Count == 0)
            {
                throw new ReactorException("Attempted to load a model when Assimp couldn't find any verticies!");
            }

            context.Dispose();
        }
Exemple #8
0
        public void ReadFromFile(string filename)
        {
            var file = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), filename);

            //Create new importer
            var importer = new AssimpContext();

            //Check if model is supported
            if (!importer.IsImportFormatSupported(Path.GetExtension(file)))
            {
                throw new ArgumentException("Model format " + Path.GetExtension(file) + " is not supported!  Cannot load {1}", "filename");
            }

            //Configs
            importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));

            var model = importer.ImportFile(file, PostProcessPreset.TargetRealTimeMaximumQuality);

            importer.Dispose();


            MeshData      = new MeshData();
            AnimationData = new AnimationData();
            foreach (var mesh in model.Meshes)
            {
                MeshData.Indices     = mesh.GetIndices().ToList();
                MeshData.IndexCount  = MeshData.Indices.Count;
                MeshData.Name        = mesh.Name;
                MeshData.VertexCount = mesh.VertexCount;

                foreach (var v in mesh.Vertices)
                {
                    MeshData.VertexPositions.Add(new Vector3(v.X, v.Y, v.Z));
                }

                foreach (var v in mesh.Normals)
                {
                    MeshData.VertexNormals.Add(new Vector3(v.X, v.Y, v.Z));
                }

                foreach (var v in mesh.TextureCoordinateChannels[0])
                {
                    MeshData.VertexTextureCoordinates.Add(new Vector2(v.X, v.Y));
                }

                AnimationData.BoneCount = mesh.BoneCount;

                foreach (var b in mesh.Bones)
                {
                    var j = new AnimationJoint();

                    j.Name = b.Name;
                    //j.OffsetMatrix = b.OffsetMatrix;

                    AnimationData.Bones.Add(j);
                }
            }

            return;

            //TO DO STILL BONES ARE DONE IN A DIFFERENT WAY

            AnimationData.HasAnimations = model.HasAnimations;


            foreach (var a in model.Animations)
            {
                //Clip
                var clip = new AnimationClip()
                {
                    Name           = a.Name,
                    Duration       = (float)a.DurationInTicks,
                    TicksPerSecond = (float)a.TicksPerSecond
                };

                //KeyFrames
                foreach (var m in a.NodeAnimationChannels)
                {
                    var key = new AnimationKey();

                    for (var i = 0; i < m.PositionKeyCount; ++i)
                    {
                        var time = m.PositionKeys[i].Time;
                        var pos  = m.PositionKeys[i].Value.ToVector3();
                        var rot  = m.RotationKeys[i].Value;
                        var s    = m.ScalingKeys[i].Value.ToVector3();
                    }



                    //clip.Keys.Add(key);
                }
            }
            // AnimationData.Animations.Add(clip);
            //}
        }
Exemple #9
0
        public override bool CanLoadExt(string Extension)
        {
            bool Can = AssimpCtx.IsImportFormatSupported(Extension);

            return(Can);
        }
        public void TestSupportedFormats()
        {
            AssimpContext importer = new AssimpContext();
            ExportFormatDescription[] exportDescs = importer.GetSupportedExportFormats();

            String[] importFormats = importer.GetSupportedImportFormats();

            Assert.IsNotNull(exportDescs);
            Assert.IsNotNull(importFormats);
            Assert.IsTrue(exportDescs.Length >= 1);
            Assert.IsTrue(importFormats.Length >= 1);

            Assert.IsTrue(importer.IsExportFormatSupported(exportDescs[0].FileExtension));
            Assert.IsTrue(importer.IsImportFormatSupported(importFormats[0]));
        }
Exemple #11
0
        private BasicModel(Device device, TextureManager11 textureManager, string filename, string texturePath, bool autoLoadTextures, bool flipUv, bool tex1By1)
        {
            var importer = new AssimpContext();

            if (!importer.IsImportFormatSupported(Path.GetExtension(filename)))
            {
                throw new ArgumentException($"Model format {Path.GetExtension(filename)} is not supported. Cannot load {filename}.", nameof(filename));
            }
#if DEBUG
            var logStream = new ConsoleLogStream();
            logStream.Attach();
#endif
            var postProcessFlags = PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace;
            if (flipUv)
            {
                postProcessFlags |= PostProcessSteps.FlipUVs;
            }
            var model = importer.ImportFile(filename, postProcessFlags);

            var min = new Vector3(float.MaxValue);
            var max = new Vector3(float.MinValue);

            _meshCount = model.Meshes.Count;

            foreach (var mesh in model.Meshes)
            {
                var verts  = new List <VertPosNormTexTan>();
                var subset = new MeshSubset()
                {
                    VertexCount = mesh.VertexCount,
                    VertexStart = Vertices.Count,
                    FaceStart   = Indices.Count / 3,
                    FaceCount   = mesh.FaceCount
                };
                Subsets.Add(subset);
                // bounding box corners

                for (var i = 0; i < mesh.VertexCount; i++)
                {
                    var pos = mesh.HasVertices ? mesh.Vertices[i].ToVector3() : new Vector3();
                    min = MathF.Minimize(min, pos);
                    max = MathF.Maximize(max, pos);

                    var norm = mesh.HasNormals ? mesh.Normals[i] : new Vector3D();
                    var texC = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0][i] : (tex1By1 ? new Vector3D(1, 1, 0) : new Vector3D());
                    var tan  = mesh.HasTangentBasis ? mesh.Tangents[i] : new Vector3D();
                    var v    = new VertPosNormTexTan(pos, norm.ToVector3(), texC.ToVector2(), tan.ToVector3());
                    verts.Add(v);
                }

                Vertices.AddRange(verts);

                var indices = mesh.GetIndices().Select(i => i + subset.VertexStart).ToList();
                Indices.AddRange(indices);

                var mat      = model.Materials[mesh.MaterialIndex];
                var material = mat.ToMaterial();

                Materials.Add(material);

                if (autoLoadTextures)
                {
                    TextureSlot diffuseSlot;
                    mat.GetMaterialTexture(TextureType.Diffuse, 0, out diffuseSlot);
                    var diffusePath = diffuseSlot.FilePath;
                    if (Path.GetExtension(diffusePath) == ".tga")
                    {
                        // DirectX doesn't like to load tgas, so you will need to convert them to pngs yourself with an image editor
                        diffusePath = diffusePath.Replace(".tga", ".png");
                    }
                    var fullDiffusePath = diffusePath == null ? null : Path.Combine(texturePath, diffusePath);
                    if (File.Exists(fullDiffusePath))
                    {
                        DiffuseMapSRV.Add(textureManager.CreateTexture(fullDiffusePath));
                    }
                    else
                    {
                        DiffuseMapSRV.Add(textureManager.CreateColor1By1(material.Diffuse.ToColor()));
                    }
                    TextureSlot normalSlot;
                    mat.GetMaterialTexture(TextureType.Normals, 0, out normalSlot);
                    var    normalPath     = normalSlot.FilePath;
                    var    fullNormalPath = normalPath == null ? null : Path.Combine(texturePath, normalPath);
                    string textureName;
                    if (File.Exists(fullNormalPath))
                    {
                        textureName = fullNormalPath;
                    }
                    else
                    {
                        if (File.Exists(fullDiffusePath))
                        {
                            var normalExt = Path.GetExtension(fullDiffusePath);
                            normalPath     = Path.GetFileNameWithoutExtension(diffusePath) + "_nmap" + normalExt;
                            fullNormalPath = Path.Combine(texturePath, normalPath);
                            if (File.Exists(fullNormalPath))
                            {
                                textureName = fullNormalPath;
                            }
                            else
                            {
                                textureName = TextureManager11.TexDefaultNorm;
                            }
                        }
                        else
                        {
                            textureName = TextureManager11.TexDefaultNorm;
                        }
                    }
                    NormalMapSRV.Add(textureManager.CreateTexture(textureName));
                }
            }

            BoundingBox = new BoundingBox(min, max);
            ModelMesh.SetSubsetTable(Subsets);
            ModelMesh.SetVertices(device, Vertices);
            ModelMesh.SetIndices(device, Indices);
        }
Exemple #12
0
        public BasicModel(Device device, TextureManager texMgr, string filename, string texturePath, bool flipUv = false)
        {
            var importer = new AssimpContext();

            if (!importer.IsImportFormatSupported(Path.GetExtension(filename)))
            {
                throw new ArgumentException("Model format " + Path.GetExtension(filename) + " is not supported!  Cannot load {1}", "filename");
            }
#if DEBUG
            var logStream = new ConsoleLogStream();
            logStream.Attach();
            //importer.  .AttachLogStream(new ConsoleLogStream());
            //importer.VerboseLoggingEnabled = true;
#endif
            var postProcessFlags = PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace;
            if (flipUv)
            {
                postProcessFlags |= PostProcessSteps.FlipUVs;
            }
            var model = importer.ImportFile(filename, postProcessFlags);


            var min = new Vector3(float.MaxValue);
            var max = new Vector3(float.MinValue);

            foreach (var mesh in model.Meshes)
            {
                var verts  = new List <PosNormalTexTan>();
                var subset = new MeshGeometry.Subset {
                    VertexCount = mesh.VertexCount,
                    VertexStart = Vertices.Count,
                    FaceStart   = Indices.Count / 3,
                    FaceCount   = mesh.FaceCount
                };
                Subsets.Add(subset);
                // bounding box corners


                for (var i = 0; i < mesh.VertexCount; i++)
                {
                    var pos = mesh.HasVertices ? mesh.Vertices[i].ToVector3() : new Vector3();
                    min = Vector3.Minimize(min, pos);
                    max = Vector3.Maximize(max, pos);

                    var norm = mesh.HasNormals ? mesh.Normals[i] : new Vector3D();
                    var texC = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0][i] : new Vector3D();
                    var tan  = mesh.HasTangentBasis ? mesh.Tangents[i] : new Vector3D();
                    var v    = new PosNormalTexTan(pos, norm.ToVector3(), texC.ToVector2(), tan.ToVector3());
                    verts.Add(v);
                }

                Vertices.AddRange(verts);

                var indices = mesh.GetIndices().Select(i => ((int)i + subset.VertexStart)).ToList();
                Indices.AddRange(indices);

                var mat      = model.Materials[mesh.MaterialIndex];
                var material = mat.ToMaterial();

                Materials.Add(material);
                TextureSlot diffuseSlot;
                mat.GetMaterialTexture(TextureType.Diffuse, 0, out diffuseSlot);
                var diffusePath = diffuseSlot.FilePath;
                if (Path.GetExtension(diffusePath) == ".tga")
                {
                    // DirectX doesn't like to load tgas, so you will need to convert them to pngs yourself with an image editor
                    diffusePath = diffusePath.Replace(".tga", ".png");
                }
                if (!string.IsNullOrEmpty(diffusePath))
                {
                    DiffuseMapSRV.Add(texMgr.CreateTexture(Path.Combine(texturePath, diffusePath)));
                }
                TextureSlot normalSlot;
                mat.GetMaterialTexture(TextureType.Normals, 0, out normalSlot);
                var normalPath = normalSlot.FilePath;
                if (!string.IsNullOrEmpty(normalPath))
                {
                    NormalMapSRV.Add(texMgr.CreateTexture(Path.Combine(texturePath, normalPath)));
                }
                else
                {
                    var normalExt = Path.GetExtension(diffusePath);
                    normalPath = Path.GetFileNameWithoutExtension(diffusePath) + "_nmap" + normalExt;

                    NormalMapSRV.Add(texMgr.CreateTexture(Path.Combine(texturePath, normalPath)));
                }
            }
            BoundingBox = new BoundingBox(min, max);
            ModelMesh.SetSubsetTable(Subsets);
            ModelMesh.SetVertices(device, Vertices);
            ModelMesh.SetIndices(device, Indices);
        }
        public void Create(Device1 device, GenericShader effect)
        {
            PrimitiveTopology = PrimitiveTopology.TriangleList;
            VertexStride      = effect.VertexStride;


            List <int> indices = new List <int>();

            var   importer = new AssimpContext();
            Scene scene    = importer.ImportFile(_fileName, PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace | PostProcessSteps.Triangulate);

            if (!importer.IsImportFormatSupported(Path.GetExtension(_fileName)))
            {
                throw new Exception("File Format not supported");
            }

            long vertCount = 0;

            foreach (var model in scene.Meshes)
            {
                vertCount += model.VertexCount;
            }
            var verts = new float[VertexStride * vertCount];

            int meshOffset = 0;

            foreach (var model in scene.Meshes)
            {
                for (var i = 0; i < model.VertexCount; ++i)
                {
                    var pos = model.Vertices[i];
                    var nor = model.Normals[i];
                    var uv  = model.TextureCoordinateChannels[0][i];
                    uv.Y = -uv.Y;
                    var col = model.HasVertexColors(0) ? model.VertexColorChannels[0][i] : new Color4D(1, 0, 1);
                    var tan = model.Tangents[i];

                    var inputOffset = 0;
                    foreach (var inputParam in effect.InputParameters)
                    {
                        if (inputParam.SemanticName == "POSITION")
                        {
                            Array.Copy(pos.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 3);
                            inputOffset += 3;
                        }
                        else if (inputParam.SemanticName == "NORMAL")
                        {
                            Array.Copy(nor.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 3);
                            inputOffset += 3;
                        }
                        else if (inputParam.SemanticName == "COLOR")
                        {
                            Array.Copy(col.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 4);
                            inputOffset += 4;
                        }
                        else if (inputParam.SemanticName == "TEXCOORD" || inputParam.SemanticName == "TEXCOORD0")
                        {
                            Array.Copy(uv.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 2);
                            inputOffset += 2;
                        }
                        else if (inputParam.SemanticName == "TANGENT")
                        {
                            Array.Copy(tan.ToArray(), 0, verts, i * (VertexStride / sizeof(float)) + inputOffset + meshOffset, 3);
                            inputOffset += 3;
                        }
                        else
                        {
                            MessageBox.Show("AssimpModel::Create() > Unsupported Semantic type! ({inputParam.SemanticName})");
                        }
                    }
                }

                meshOffset += model.VertexCount * VertexStride;

                indices.AddRange(model.GetIndices().ToList());
            }

            IndexCount = indices.Count;

            BufferDescription bd = new BufferDescription(
                (int)(verts.Length),
                ResourceUsage.Immutable,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None);

            VertexBuffer = new Buffer(device, DataStream.Create(verts, false, false), bd);

            bd = new BufferDescription(
                sizeof(int) * IndexCount,
                ResourceUsage.Immutable,
                BindFlags.IndexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None);
            IndexBuffer = new Buffer(device, DataStream.Create(indices.ToArray(), false, false), bd);
        }
Exemple #14
0
        public Mesh(string FileName, bool flipUv = false)
        {
            Vertices = new List <Vertex>();

            Indices = new List <int>();

            AssimpContext importer = new AssimpContext();

            if (!importer.IsImportFormatSupported(Path.GetExtension(FileName)))
            {
                throw new ArgumentException("Model format " + Path.GetExtension(FileName) + " is not supported!  Cannot load {1}", "filename");
            }


            ConsoleLogStream logStream = new ConsoleLogStream();

            logStream.Attach();

            PostProcessSteps postProcessFlags = PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.CalculateTangentSpace;

            if (flipUv)
            {
                postProcessFlags |= PostProcessSteps.FlipUVs;
            }


            Scene model = importer.ImportFile(FileName, postProcessFlags);

            int[] indices = new int[model.Meshes.Sum(m => m.FaceCount * 3)];

            int vertexOffSet = 0;

            int indexOffSet = 0;

            foreach (Assimp.Mesh mesh in model.Meshes)
            {
                List <Vertex> verts = new List <Vertex>();

                List <Face> faces = mesh.Faces;

                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    Vector3 pos = mesh.HasVertices ? new Vector3(mesh.Vertices[i].X, mesh.Vertices[i].Y, mesh.Vertices[i].Z) : new Vector3();

                    Vector3D texC = mesh.HasTextureCoords(0) ? mesh.TextureCoordinateChannels[0][i] : new Vector3D();
                    Vector2  TeC  = new Vector2(texC.X, texC.Y);
                    Vertex   v    = new Vertex(pos, TeC);
                    verts.Add(v);
                }

                Vertices.AddRange(verts);

                for (int i = 0; i < mesh.FaceCount; i++)
                {
                    indices[i * 3 + 0] = (int)faces[i].Indices[2];
                    indices[i * 3 + 1] = (int)faces[i].Indices[1];
                    indices[i * 3 + 2] = (int)faces[i].Indices[0];
                    Indices.Add(indices[i * 3 + 2] + vertexOffSet);
                    Indices.Add(indices[i * 3 + 1] + vertexOffSet);
                    Indices.Add(indices[i * 3 + 0] + vertexOffSet);
                }
                vertexOffSet += mesh.VertexCount;
                indexOffSet  += mesh.FaceCount * 3;
            }



            VertexCount = Vertices.Count();

            IndexCount = Indices.Count();

            Size = Utilities.SizeOf <Vertex>();

            SizeInBytes = Utilities.SizeOf <Vertex>() * Vertices.Count();

            IndexSize = Utilities.SizeOf <int>();

            IndexSizeInBytes = Utilities.SizeOf <int>() * Indices.Count();
        }
Exemple #15
0
 public static bool CanLoad(string filePath)
 => Context.IsImportFormatSupported(Path.GetExtension(filePath));