Inheritance: IDisposable
示例#1
0
        public static void FromAssimp(Module.Import.Assimp.Context context, aiScene scene)
        {
            if (scene.HasMaterials())
            {
                using (aiMaterialArray assimp_materials = scene.Materials)
                {
                    uint material_size = assimp_materials.Size();

                    // Reserve the right amount of memory
                    context.scene.materials = new Material[(int)material_size + 1];

                    // Create a material for lines
                    Material line_material = new Material();
                    line_material.name   = "Line";
                    line_material.shader = defaultAssimpLineShader;
                    line_material.floats = new Dictionary <string, float>();
                    line_material.colors = new Dictionary <string, Color>();
                    line_material.floats.Add(defaultAssimpLineShaderWidth, unityLineWidth);
                    line_material.colors.Add(Assimp.Convert.unityDiffuseColorName, Color.black);
                    context.scene.materials[(int)material_size] = line_material;

                    // Load all the materials
                    for (uint i = 0; i < material_size; i++)
                    {
                        aiMaterial material = assimp_materials.Get(i);

                        // LoadMaterial must dispose of the given material afterward
                        // We must use a proxy method for saving the result into the array because the index i is captured by the lambda otherwise and it's value is indefinite across multiple threads.
                        context.threads.ExecAndSaveToArray(context.scene.materials, (int)i, () => FromAssimp(context, scene, material));
                    }
                }
            }
        }
示例#2
0
        public aiExportDataBlob ExportToBlob(aiScene pScene, string pFormatId, aiPostProcessSteps pPreprocessing)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.Exporter_ExportToBlob__SWIG_1(swigCPtr, aiScene.getCPtr(pScene), pFormatId, (uint)pPreprocessing);
            aiExportDataBlob      ret  = (cPtr == global::System.IntPtr.Zero) ? null : new aiExportDataBlob(cPtr, false);

            return(ret);
        }
示例#3
0
        public static aiScene aiImportFile(string pFile, aiPostProcessSteps pFlags)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.aiImportFile(pFile, (uint)pFlags);
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#4
0
        public aiScene ReadFileFromMemory(byte[] pBuffer, uint pLength, aiPostProcessSteps pFlags)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.Importer_ReadFileFromMemory__SWIG_1(swigCPtr, pBuffer, pLength, (uint)pFlags);
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#5
0
        public aiExportDataBlob ExportToBlob(aiScene pScene, string pFormatId)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.Exporter_ExportToBlob__SWIG_2(swigCPtr, aiScene.getCPtr(pScene), pFormatId);
            aiExportDataBlob      ret  = (cPtr == global::System.IntPtr.Zero) ? null : new aiExportDataBlob(cPtr, false);

            return(ret);
        }
示例#6
0
        public aiScene GetOrphanedScene()
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.Importer_GetOrphanedScene(swigCPtr);
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#7
0
        public aiScene ApplyPostProcessing(aiPostProcessSteps pFlags)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.Importer_ApplyPostProcessing(swigCPtr, (uint)pFlags);
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#8
0
    public static aiScene aiImportFileFromMemory(string arg0, uint arg1, uint arg2, string arg3)
    {
        IntPtr  cPtr = AssimpPINVOKE.aiImportFileFromMemory(arg0, arg1, arg2, arg3);
        aiScene ret  = (cPtr == IntPtr.Zero) ? null : new aiScene(cPtr, false);

        return(ret);
    }
示例#9
0
        public aiScene ReadFile(byte[] pFilename, uint pSize, aiPostProcessSteps pFlags)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.Importer_ReadFile__SWIG_1(swigCPtr, pFilename, pSize, (uint)pFlags);
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#10
0
        public static aiScene aiApplyPostProcessing(aiScene pScene, aiPostProcessSteps pFlags)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.aiApplyPostProcessing(aiScene.getCPtr(pScene), (uint)pFlags);
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#11
0
        public static aiScene aiImportFileFromMemoryWithProperties(string pBuffer, uint pLength, aiPostProcessSteps pFlags, string pHint, aiPropertyStore pProps)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.aiImportFileFromMemoryWithProperties(pBuffer, pLength, (uint)pFlags, pHint, aiPropertyStore.getCPtr(pProps));
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#12
0
        public static aiScene aiImportFileExWithProperties(string pFile, aiPostProcessSteps pFlags, aiFileIO pFS, aiPropertyStore pProps)
        {
            global::System.IntPtr cPtr = assimp_swigPINVOKE.aiImportFileExWithProperties(pFile, (uint)pFlags, aiFileIO.getCPtr(pFS), aiPropertyStore.getCPtr(pProps));
            aiScene ret = (cPtr == global::System.IntPtr.Zero) ? null : new aiScene(cPtr, false);

            return(ret);
        }
示例#13
0
    public aiScene GetOrphanedScene()
    {
        IntPtr  cPtr = AssimpPINVOKE.Importer_GetOrphanedScene(swigCPtr);
        aiScene ret  = (cPtr == IntPtr.Zero) ? null : new aiScene(cPtr, false);

        return(ret);
    }
示例#14
0
    public aiScene ReadFile(string pFile, aiPostProcessSteps pFlags)
    {
        IntPtr  cPtr = AssimpPINVOKE.Importer_ReadFile__SWIG_0(swigCPtr, pFile, (uint)pFlags);
        aiScene ret  = (cPtr == IntPtr.Zero) ? null : new aiScene(cPtr, false);

        return(ret);
    }
示例#15
0
文件: Assimp.cs 项目: clarte53/armine
            /// <summary>
            /// Clean the content of the structure fields to get ready for next export.
            /// </summary>
            public void Clean()
            {
                scene = null;

                meshes.Clear();

                progress.Clean();
            }
示例#16
0
文件: Mesh.cs 项目: clarte53/armine
        public static void FromAssimp(Module.Import.Assimp.Context context, aiScene scene)
        {
            if (scene.HasMeshes())
            {
                using (aiMeshArray meshes = scene.Meshes)
                {
                    uint meshes_size = meshes.Size();

                    // Reserve the right amount of memory
                    context.scene.meshes = new Mesh[(int)meshes_size];

                    // Load all the meshes
                    for (uint i = 0; i < meshes_size; i++)
                    {
                        aiMesh mesh = meshes.Get(i);

                        // LoadGeometry must dispose of the given mesh afterward
                        // We must use a proxy method for saving the result into the array because the index i is captured by the lambda otherwise and it's value is indefinite across multiple threads.
                        context.threads.ExecAndSaveToArray(context.scene.meshes, (int)i, () => FromAssimp(context, mesh));
                    }
                }
            }
        }
示例#17
0
 internal static HandleRef getCPtr(aiScene obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
示例#18
0
        public static void FromAssimp(Module.Import.Assimp.Context context, Material material, aiScene scene, aiMaterial material_data, string texture_key, aiTextureType texture_type, float reflectivity)
        {
            if (texture_type != aiTextureType.aiTextureType_NONE && material_data.GetTextureCount(texture_type) > 0)
            {
                using (aiString texture_name = new aiString())
                {
                    if (material_data.GetTexturePath(texture_type, 0, texture_name))
                    {
                        string filename = texture_name.C_Str();

                        uint index = context.scene.GetAssimpTexture(filename, () => new Texture(context, filename, scene)).Item2;

                        material.AddTextureParams(texture_key, new Material.TextureParams(index));

                        context.progress.Update(ASSIMP_PROGRESS_FACTOR);
                    }
                }
            }

            Color default_color;

            // Add textures as alpha channel of existing textures, or compute normal map from heightmap if not defined.
            switch (texture_key)
            {
            case Assimp.Convert.unityMainTexName:
                default_color = Color.white;

                Color?diffuse = material.GetColor(Assimp.Convert.unityDiffuseColorName);

                if (diffuse.HasValue)
                {
                    default_color = diffuse.Value;
                }

                // Opacity as main texture alpha channel
                FromAssimpAlphaTexture(context, material, material_data, scene, Assimp.Convert.unityMainTexName, aiTextureType.aiTextureType_OPACITY, default_color, c => c.grayscale);
                break;

            case Assimp.Convert.unityMetallicGlossName:
                default_color = Color.black;

                float?metallic = material.GetFloat(Assimp.Convert.unityMetallicValueName);

                if (metallic.HasValue)
                {
                    default_color = new Color(metallic.Value, metallic.Value, metallic.Value, 1f);
                }

                // Shininess as alpha channel of metallic gloss map
                FromAssimpAlphaTexture(context, material, material_data, scene, Assimp.Convert.unityMetallicGlossName, aiTextureType.aiTextureType_SHININESS, default_color, c => Material.Smoothness(c.grayscale, reflectivity));
                break;

            case Assimp.Convert.unitySpecGlossName:
                default_color = Color.black;

                Color?specular = material.GetColor(Assimp.Convert.unitySpecularColorName);

                if (specular.HasValue)
                {
                    default_color = specular.Value;
                }

                // Shininess as alpha channel of specular gloss map
                FromAssimpAlphaTexture(context, material, material_data, scene, Assimp.Convert.unitySpecGlossName, aiTextureType.aiTextureType_SHININESS, default_color, c => Material.Smoothness(c.grayscale, reflectivity));
                break;

            case Assimp.Convert.unityBumpName:
                // Bump mapping from heightmap if not defined from normals
                FromAssimpNormalsFromHeightmap(context, material, material_data, scene);
                break;
            }
        }
示例#19
0
 private Texture(Module.Import.Assimp.Context context, string filename, aiScene scene)
 {
     LoadFromAssimp(context, filename, scene);
 }
示例#20
0
        private static void FromAssimpAlphaTexture(Module.Import.Assimp.Context context, Material material, aiMaterial material_data, aiScene scene, string unity_property, aiTextureType texture_type, Color default_color, Func <Color, float> op)
        {
            if (material_data.GetTextureCount(texture_type) > 0)
            {
                using (aiString texture_name = new aiString())
                {
                    if (material_data.GetTexturePath(texture_type, 0, texture_name))
                    {
                        Texture alpha    = new Texture(context, texture_name.ToString(), scene);
                        Texture base_tex = null;

                        Material.TextureParams param = material.GetTextureParams(unity_property);

                        if (param != null)
                        {
                            CLARTE.Backport.Tuple <Texture, uint> res = context.scene.GetAssimpTexture(param.index);

                            if (res != null)
                            {
                                base_tex = res.Item1;
                            }
                            else
                            {
                                Debug.LogErrorFormat("Invalid texture index. '{0}' was registered for material '{1}' as texture with index '{2}'. However no texture was found with this index.", unity_property, material.Name, param.index);
                            }
                        }
                        else
                        {
                            CLARTE.Backport.Tuple <Texture, uint> assimp_tex = context.scene.GetAssimpTexture(Guid.NewGuid().ToString(), () => new Texture("**E", alpha.width, alpha.height, default_color));

                            material.AddTextureParams(unity_property, new Material.TextureParams(assimp_tex.Item2));

                            base_tex = assimp_tex.Item1;
                        }

                        if (base_tex != null)
                        {
                            base_tex.AddToAlpha(alpha, op);

                            base_tex.filename = string.Format("**A{0}|{1}", base_tex.filename, texture_name.C_Str());
                        }
                    }
                }
            }
        }
示例#21
0
        private void LoadFromAssimp(Module.Import.Assimp.Context context, string filename, aiScene scene)
        {
            if (!string.IsNullOrEmpty(filename))
            {
                byte[] tex;

                if (filename[0] == '*')
                {
                    // Embeded texture
                    string index_str = filename.Remove(0, 1);

                    uint index;
                    if (uint.TryParse(index_str, out index))
                    {
                        using (aiTextureArray array = scene.Textures)
                        {
                            if (index < array.Size())
                            {
                                using (aiTexture texture = array.Get(index))
                                {
                                    DecodeTexture(filename, texture.data);
                                }
                            }
                            else
                            {
                                Debug.LogError("Invalid embeded texture index \"" + index + "\" (out of bound).");
                            }
                        }
                    }
                    else
                    {
                        Debug.LogError("Invalid embeded texture name \"" + filename + "\" (not an index).");
                    }
                }
                else if (context.importer != null && (tex = context.importer.GetTexture(filename)) != null)
                {
                    DecodeTexture(filename, tex);
                }
                else
                {
                    LoadFromFile(context.path, filename);
                }
            }
        }
示例#22
0
文件: Scene.cs 项目: clarte53/armine
        public static IEnumerator FromAssimp(Module.Import.Assimp.Context context, global::Assimp.Importer importer, Func <aiScene> loader, Module.ImporterReturnCallback return_callback, Module.ProgressCallback progress_callback)
        {
            if (progress_callback != null)
            {
                progress_callback(0.01f);
            }

            aiScene scene = null;

            // Async loading does not work in editor when not in play mode
            context.threads.AddTask(() => scene = loader());

            IEnumerator it = context.threads.WaitForTasksCompletion();

            while (it.MoveNext())
            {
                context.progress.Display();

                yield return(it.Current);
            }

            if (scene != null)
            {
                InitProgress(context, progress_callback, scene);

                context.progress.Update((uint)(assimpNativeLoadingPrecentage * context.progress.TotalSteps));

                context.scene = new Scene();

                context.scene.assimpTextures = new Dictionary <string, CLARTE.Backport.Tuple <Texture, uint> >();

                context.threads.AddTask(() => Mesh.FromAssimp(context, scene));
                context.threads.AddTask(() => Material.FromAssimp(context, scene));
                context.threads.AddTask(() => context.scene.root_node = Node.FromAssimp(context, scene, scene.mRootNode));

                it = context.threads.WaitForTasksCompletion();
                while (it.MoveNext())
                {
                    context.progress.Display();

                    yield return(it.Current);
                }

                // Assign materials to meshes now that all data is available
                context.threads.AddTask(() => Node.SetAssimpMeshesMaterials(context.scene, context.scene.root_node));
                // Assign textures to final array
                context.threads.AddTask(() =>
                {
                    context.scene.textures = new Texture[context.scene.assimpTextures.Count];

                    foreach (KeyValuePair <string, CLARTE.Backport.Tuple <Texture, uint> > pair in context.scene.assimpTextures)
                    {
                        context.scene.textures[pair.Value.Item2] = pair.Value.Item1;
                    }
                });

                // We can safelly dispose of the scene because all tasks must have been completed to reach this point, therefore we do not risque deallocating data used in another thread.
                // this method can take a few hundred milliseconds, therefore, we do it async and wait for it to complete before allowing new imports.
                context.threads.AddTask(scene.Dispose);
                context.threads.AddTask(importer.FreeScene);

                it = context.threads.WaitForTasksCompletion();
                while (it.MoveNext())
                {
                    context.progress.Display();

                    yield return(it.Current);
                }

                // Clean up
                context.scene.assimpTextures = null;

                if (return_callback != null)
                {
                    return_callback(context.scene);
                }

                context.Clean();
            }
            else
            {
                Debug.LogErrorFormat("Failed to open file: {0}{1}{2}.\nThe importer reported the following error: {3}", context.path, System.IO.Path.PathSeparator, context.filename, importer.GetErrorString());
            }
        }
示例#23
0
文件: Scene.cs 项目: clarte53/armine
        private static void InitProgress(Module.Import.Assimp.Context context, Module.ProgressCallback callback, aiScene scene)
        {
            uint nb_textures = 0;

            using (aiMaterialArray assimp_materials = scene.Materials)
            {
                uint nb_materials = assimp_materials.Size();

                for (uint i = 0; i < nb_materials; i++)
                {
                    using (aiMaterial material = assimp_materials.Get(i))
                    {
                        foreach (KeyValuePair <string, aiTextureType> pair in Assimp.Convert.textureTypes)
                        {
                            using (aiString texture_name = new aiString())
                            {
                                if (material.GetTexturePath(pair.Value, 0, texture_name))
                                {
                                    nb_textures++;
                                }
                            }
                        }
                    }
                }
            }

            uint nb_steps = Node.ASSIMP_PROGRESS_FACTOR * CountNodes(scene.mRootNode);

            nb_steps += Mesh.ASSIMP_PROGRESS_FACTOR * scene.Meshes.Size();
            nb_steps += Material.ASSIMP_PROGRESS_FACTOR * scene.Materials.Size();
            nb_steps += Texture.ASSIMP_PROGRESS_FACTOR * nb_textures;
            nb_steps  = (uint)(nb_steps / (1f - assimpNativeLoadingPrecentage));

            context.progress.Init(nb_steps, callback);
        }
示例#24
0
        private static void FromAssimpNormalsFromHeightmap(Module.Import.Assimp.Context context, Material material, aiMaterial material_data, aiScene scene)
        {
            if (material_data.GetTextureCount(Assimp.Convert.textureTypes[Assimp.Convert.unityBumpName]) <= 0)
            {
                using (aiString texture_name = new aiString())
                {
                    if (material_data.GetTexturePath(aiTextureType.aiTextureType_HEIGHT, 0, texture_name))
                    {
                        string filename = string.Format("**N{0}", texture_name.C_Str());

                        material.AddTextureParams(Assimp.Convert.unityBumpName, new Material.TextureParams(context.scene.GetAssimpTexture(filename, () =>
                        {
                            Texture texture = new Texture(context, texture_name.C_Str(), scene).HeightmapToNormals(0.5).Blur(0.5);

                            texture.filename = filename;

                            return(texture);
                        }).Item2));
                    }
                }
            }
        }
示例#25
0
文件: Scene.cs 项目: clarte53/armine
        public IEnumerator ToAssimp(Module.Export.Assimp.Context context, string filename, aiPostProcessSteps steps, Module.ExporterSuccessCallback return_callback, Module.ProgressCallback progress_callback)
        {
            bool success = false;

            string extension = System.IO.Path.GetExtension(filename).Remove(0, 1).ToLower();

            uint export_format_count = context.exporter.GetExportFormatCount();

            bool found_exporter = false;

            for (uint i = 0; i < export_format_count; i++)
            {
                using (aiExportFormatDesc desc = context.exporter.GetExportFormatDescription(i))
                {
                    if (extension == desc.fileExtension.ToLower())
                    {
                        using (aiScene scene = new aiScene())
                        {
                            InitProgress(context, progress_callback, this);

                            context.scene = scene;

                            // Export nodes
                            IResult nodes_result = context.threads.AddTask(() =>
                            {
                                using (aiNode root = root_node.ToAssimp(context, this, null))
                                {
                                    scene.mRootNode = root.Unmanaged();
                                }
                            });

                            // Export materials.
                            context.threads.AddTask(() => Material.ToAssimp(context, this));

                            // We must wait for all the nodes to be processed before exporting meshes because indexes are computed during parsing.
                            while (!nodes_result.Done)
                            {
                                context.progress.Display();

                                yield return(null);
                            }

                            // Export meshes
                            context.threads.AddTask(() => Mesh.ToAssimp(context, this));

                            // Wait for all tasks to be completed
                            IEnumerator it = context.threads.WaitForTasksCompletion();
                            while (it.MoveNext())
                            {
                                context.progress.Display();

                                yield return(it.Current);
                            }

                            // Do the final export using Assimp now that we created the complete structure in the C++ DLL.
                            Result <aiReturn> status = context.threads.AddTask(() => context.exporter.Export(scene, desc.id, filename, steps));

                            // Wait for export to complete
                            while (!status.Done)
                            {
                                context.progress.Display();

                                yield return(null);
                            }

                            if (progress_callback != null)
                            {
                                progress_callback(1f);
                            }

                            context.Clean();

                            // Check export status
                            if (status.Success && status.Value == aiReturn.aiReturn_SUCCESS)
                            {
                                success = true;
                            }
                            else
                            {
                                Debug.LogErrorFormat("Failed to export to: {0}. \nThe exporter reported the following error: {1}", filename, context.exporter.GetErrorString());
                            }
                        }

                        found_exporter = true;

                        break;
                    }
                }
            }

            if (!found_exporter)
            {
                Debug.LogErrorFormat("No exporter for format '{0}' was found in Assimp.", extension);
            }

            if (return_callback != null)
            {
                return_callback(success);
            }
        }
示例#26
0
文件: Node.cs 项目: clarte53/armine
        public static Node FromAssimp(Module.Import.Assimp.Context context, aiScene scene, aiNode assimp_node)
        {
            // Create new node object
            Node node = new Node();

            // Get node ID
            node.id = context.id++;

            // Get node name
            node.name = Assimp.Convert.Name(assimp_node.mName, "node");

            // Get node metadata
            using (aiMetadata meta = assimp_node.mMetaData)
            {
                UnityComponent metadata = UnityComponent.FromAssimpMetadata(meta);

                if (metadata != null)
                {
                    node.components = new UnityComponent[] { metadata };
                }
            }

            // Parse children recursively
            using (aiNodeArray children = assimp_node.Children)
            {
                uint children_size = children.Size();

                if (children_size > 0)
                {
                    node.children = new Node[children_size];

                    for (uint i = 0; i < children_size; i++)
                    {
                        aiNode child = children.Get(i);

                        // ParseNode must dispose of the given node afterward
                        // We must use a proxy method for saving the result into the array because the index i is captured by the lambda otherwise and it's value is indefinite across multiple threads.
                        context.threads.ExecAndSaveToArray(node.children, (int)i, () => FromAssimp(context, scene, child));
                    }
                }
            }

            // Parse meshes associated to this node
            using (aiUIntArray meshes = assimp_node.Meshes)
            {
                uint meshes_size = meshes.Size();

                if (meshes_size > 0)
                {
                    int global_meshes_size = (int)scene.Meshes.Size();

                    node.meshes = new GraphicMesh[meshes_size];

                    for (uint j = 0; j < meshes_size; j++)
                    {
                        node.meshes[j] = new GraphicMesh();

                        if (j < global_meshes_size)
                        {
                            uint mesh_index = meshes.Get(j);

                            node.meshes[j].meshIndex = (int)mesh_index;
                        }
                    }
                }
            }

            // Get the transform of this node
            using (aiVector3D position = new aiVector3D())
            {
                using (aiVector3D scaling = new aiVector3D())
                {
                    using (aiQuaternion rotation = new aiQuaternion())
                    {
                        assimp_node.mTransformation.Decompose(scaling, rotation, position);

                        node.position = Assimp.Convert.AssimpToUnity.Vector3(position);
                        node.rotation = Assimp.Convert.AssimpToUnity.Quaternion(rotation);
                        node.scale    = Assimp.Convert.AssimpToUnity.Vector3(scaling);
                    }
                }
            }

            // We must dispose of the given parameter to avoid memory leaks
            assimp_node.Dispose();

            context.progress.Update(ASSIMP_PROGRESS_FACTOR);

            return(node);
        }
示例#27
0
        public aiReturn Export(aiScene pScene, string pFormatId, string pPath)
        {
            aiReturn ret = (aiReturn)assimp_swigPINVOKE.Exporter_Export__SWIG_2(swigCPtr, aiScene.getCPtr(pScene), pFormatId, pPath);

            return(ret);
        }
示例#28
0
        public aiReturn Export(aiScene pScene, string pFormatId, string pPath, aiPostProcessSteps pPreprocessing)
        {
            aiReturn ret = (aiReturn)assimp_swigPINVOKE.Exporter_Export__SWIG_1(swigCPtr, aiScene.getCPtr(pScene), pFormatId, pPath, (uint)pPreprocessing);

            return(ret);
        }
示例#29
0
 internal static HandleRef getCPtr(aiScene obj)
 {
     return((obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr);
 }
示例#30
0
        private static Material FromAssimp(Module.Import.Assimp.Context context, aiScene scene, aiMaterial material_data)
        {
            Material material = new Material();

            // Initialize dictionaries before hand because we do not know in advance wich ones we will need
            material.floats   = new Dictionary <string, float>();
            material.colors   = new Dictionary <string, Color>();
            material.textures = new Dictionary <string, TextureParams>();

            // Name
            using (aiString material_name = new aiString())
            {
                if (material_data.GetName(material_name))
                {
                    material.name = material_name.ToString();
                }
            }

            // shader
            material.shader = Constants.defaultAssimpShader;

            // Shininess
            float shininess;

            if (material_data.GetShininess(out shininess))
            {
                aiShadingMode shading;

                if (material_data.GetShadingModel(out shading))
                {
                    if (shading != aiShadingMode.aiShadingMode_Blinn && shading != aiShadingMode.aiShadingMode_Phong)
                    {
                        // Unsupported shading model
                        Debug.LogWarningFormat("The shading model for material {0} is not supported. The value for the shininess is likely to be incorrect.", material.name);
                    }
                }

                const int factor = 128;                 // unity shader factor
                shininess /= factor;
            }

            // Gloss
            float gloss;

            if (material_data.GetShininessStrength(out gloss))
            {
                shininess *= gloss;
            }

            // Reflectivity
            float reflectivity;

            if (material_data.GetReflectivity(out reflectivity))
            {
                material.floats.Add(Assimp.Convert.unityMetallicValueName, reflectivity);
            }

            material.floats.Add(Assimp.Convert.unityGlossinessValueName, Smoothness(shininess, reflectivity));

            // Colors
            foreach (KeyValuePair <string, Assimp.Convert.GetColor> pair in Assimp.Convert.GetColors(material_data))
            {
                using (aiColor4D color = new aiColor4D())
                {
                    if (pair.Value(color))
                    {
                        Color unity_color = Assimp.Convert.AssimpToUnity.Color(color);

                        bool set_color = true;

                        switch (pair.Key)
                        {
                        case Assimp.Convert.unityDiffuseColorName:
                            // Global opacity
                            float opacity;

                            if (material_data.GetOpacity(out opacity) && opacity < 1.0f)
                            {
                                unity_color.a = opacity;

                                material.floats.Add(Assimp.Convert.unityRenderModeName, (float)CLARTE.Shaders.Standard.Utility.BlendMode.TRANSPARENT);
                            }

                            break;

                        case Assimp.Convert.unitySpecularColorName:
                            // Specular color must be very close to black
                            unity_color = 0.1f * unity_color;

                            break;

                        case Assimp.Convert.unityEmissiveColorName:
                            if (!CLARTE.Shaders.Standard.Utility.ShouldEmissionBeEnabled(unity_color))
                            {
                                set_color = false;
                            }

                            break;
                        }

                        if (set_color)
                        {
                            material.colors.Add(pair.Key, unity_color);
                        }
                    }
                }
            }

            // Textures
            foreach (KeyValuePair <string, aiTextureType> pair in Assimp.Convert.textureTypes)
            {
                // Make a copy to avoid problem of loop variable captured by reference by lambda expression
                string        texture_key  = pair.Key;
                aiTextureType texture_type = pair.Value;

                context.threads.AddTask(() => Texture.FromAssimp(context, material, scene, material_data, texture_key, texture_type, reflectivity));
            }

            // We must dispose of the given parameter to free unused memory. However other tasks may still be using this material (i.e. textures), so we will let the garbage collector do it's job.
            //material_data.Dispose();

            context.progress.Update(ASSIMP_PROGRESS_FACTOR);

            return(material);
        }
示例#31
0
        public void InitializeAssimp()
        {
            var flags = ( ppsteps |
                aiPostProcessSteps.aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing
                aiPostProcessSteps.aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes
                aiPostProcessSteps.aiProcess_Triangulate | // triangulate polygons with more than 3 edges
                aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
                aiPostProcessSteps.aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
                (aiPostProcessSteps)0);

            // default model
            var path = "../../../../../../test/models/3DS/test1.3ds";

            importer = new Importer();
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1) {
                path = args[1];
            }

            //var path = "man.3ds";
            scene = importer.ReadFile(path, flags);
            if (scene != null)
            {
                directory = Path.GetDirectoryName(path);
                CacheMaterials(scene.mMaterials);
                CacheMeshes(scene.mMeshes);
                SetupCamera(scene.mCameras);
            }
            else {
                MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid.");
                Application.Exit();
            }
        }
示例#32
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample");


            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount     = 3,
                ModeDescription =
                    new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Sequential,
                Usage             = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            Device    device;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            var factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);


            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            Texture2DDescription depthBufferDesc;

            depthBufferDesc.Width     = form.Width;
            depthBufferDesc.Height    = form.Height;
            depthBufferDesc.MipLevels = 1;
            depthBufferDesc.ArraySize = 1;
            depthBufferDesc.Format    = Format.D24_UNorm_S8_UInt;
            depthBufferDesc.SampleDescription.Count   = 1;
            depthBufferDesc.SampleDescription.Quality = 0;
            depthBufferDesc.Usage          = ResourceUsage.Default;
            depthBufferDesc.BindFlags      = BindFlags.DepthStencil;
            depthBufferDesc.CpuAccessFlags = CpuAccessFlags.None;
            depthBufferDesc.OptionFlags    = ResourceOptionFlags.None;

            Texture2D DepthStencilTexture = new Texture2D(device, depthBufferDesc);

            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription();

            depthStencilViewDesc.Format             = Format.D24_UNorm_S8_UInt;
            depthStencilViewDesc.Dimension          = DepthStencilViewDimension.Texture2D;
            depthStencilViewDesc.Texture2D.MipSlice = 0;
            DepthStencilView depthStencilView = new DepthStencilView(device, DepthStencilTexture, depthStencilViewDesc);

            context.OutputMerger.SetTargets(depthStencilView, renderView);


            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };
            DepthStencilState depthStencilState = new DepthStencilState(device, depthDesc);

            RasterizerStateDescription rasdesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias            = 0,
                DepthBiasClamp       = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled   = true,
                IsMultisampleEnabled = true,
            };

            context.Rasterizer.State = new RasterizerState(device, rasdesc);


            //////////////////////////////

            var flags = (ppsteps |
                         aiPostProcessSteps.aiProcess_GenSmoothNormals |    // generate smooth normal vectors if not existing
                         aiPostProcessSteps.aiProcess_SplitLargeMeshes |    // split large, unrenderable meshes into submeshes
                         aiPostProcessSteps.aiProcess_Triangulate |         // triangulate polygons with more than 3 edges
                         aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
                         aiPostProcessSteps.aiProcess_SortByPType |         // make 'clean' meshes which consist of a single typ of primitives
                         (aiPostProcessSteps)0);

            // default model
            var path = @"jeep1.ms3d";

            Importer importer = new Importer();

            //var path = "man.3ds";
            aiScene scene     = importer.ReadFile(path, flags);
            String  directory = null;

            if (scene != null)
            {
                directory = Path.GetDirectoryName(path);
            }
            else
            {
                MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid.");
                Application.Exit();
            }

            SceneLoader  SceneLoader = new SceneLoader();
            List <model> models      = new List <model>();

            for (int i = 0; i < scene.mNumMeshes; i++)
            {
                models.Add(SceneLoader.CreateMesh(device, scene.mMeshes[i], scene.mMaterials, directory));
            }


            //////////////////////////////

            // Compile Vertex and Pixel shaders
            var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect         = new Effect(device, effectByteCode);
            var technique      = effect.GetTechniqueByIndex(0);
            var pass           = technique.GetPassByIndex(0);

            // Layout from VertexShader input signature
            var passSignature = pass.Description.Signature;

            // Layout from VertexShader input signature
            var layout = new InputLayout(
                device,
                passSignature,
                new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
            });

            // Prepare All the stages
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.OutputMerger.DepthStencilState = depthStencilState;

            Input input = new Input(form);
            //FreeLook FreeLook = new SharpExamples.FreeLook(input, (float)form.Width / (float)form.Height);
            CameraFirstPerson FreeLook = new CameraFirstPerson(input, 0, 0, Vector3.Zero, form.Width, form.Height);
            //FreeLook.SetEyeTarget(new Vector3(300), Vector3.Zero);
            Clock Clock = new SharpExamples.Clock();

            Clock.Start();

            effect.GetVariableByName("projection").AsMatrix().SetMatrix(FreeLook.Projection);

            // Main loop
            RenderLoop.Run(form, () =>
            {
                foreach (var item in models)
                {
                    context.InputAssembler.InputLayout       = layout;
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                    int SizeInBytes = Marshal.SizeOf(typeof(VertexPostitionTexture));
                    context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(item.vertex, SizeInBytes, 0));
                    context.InputAssembler.SetIndexBuffer(item.indices, Format.R32_UInt, 0);

                    float elapsed = Clock.Update();
                    FreeLook.Update(elapsed);

                    effect.GetVariableByName("view").AsMatrix().SetMatrix(FreeLook.View);
                    effect.GetVariableByName("World").AsMatrix().SetMatrix(Matrix.Scaling(5));
                    effect.GetVariableByName("tex0").AsShaderResource().SetResource(item.ShaderResourceView);
                    context.ClearRenderTargetView(renderView, Colors.Black);
                    context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);

                    for (int i = 0; i < technique.Description.PassCount; ++i)
                    {
                        pass.Apply(context);
                        context.DrawIndexed(item.numberIndices, 0, 0);
                    }
                    swapChain.Present(0, PresentFlags.None);
                }
            });

            // Release all resources
            foreach (var item in models)
            {
                item.vertex.Dispose();
                item.indices.Dispose();
                item.ShaderResourceView.Dispose();
            }

            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }