Exemple #1
0
        //Transforms the root node of the scene and writes it back to the native structure
        private bool TransformScene(IntPtr scene)
        {
            BuildMatrix();

            try
            {
                if (!m_scaleRot.IsIdentity)
                {
                    AiScene aiScene = MemoryHelper.MarshalStructure <AiScene>(scene);
                    if (aiScene.RootNode == IntPtr.Zero)
                    {
                        return(false);
                    }

                    IntPtr matrixPtr = MemoryHelper.AddIntPtr(aiScene.RootNode, MemoryHelper.SizeOf <AiString>()); //Skip over Node Name

                    Matrix4x4 matrix = MemoryHelper.Read <Matrix4x4>(matrixPtr);                                   //Get the root transform
                    matrix = matrix * m_scaleRot;                                                                  //Transform

                    //Write back to unmanaged mem
                    MemoryHelper.Write <Matrix4x4>(matrixPtr, ref matrix);

                    return(true);
                }
            }
            catch (Exception)
            {
            }

            return(false);
        }
Exemple #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="aiScene"></param>
        /// <param name="TimeInSeconds"></param>
        /// <returns></returns>
        public static mat4[] GetBoneMatrixes(this AiScene aiScene, float TimeInSeconds, AllBoneInfos allBones)
        {
            if (!aiScene.HasAnimations)
            {
                return(null);
            }
            double ticksPerSecond = aiScene.Animations[0].TicksPerSecond;

            if (ticksPerSecond == 0)
            {
                ticksPerSecond = 25.0;
            }
            double timeInTicks   = TimeInSeconds * ticksPerSecond;
            float  animationTime = (float)(timeInTicks % aiScene.Animations[0].DurationInTicks);

            AiMatrix4x4 transform = aiScene.RootNode.Transform;

            transform.Inverse();
            ReadNodeHeirarchy(animationTime, aiScene.RootNode, aiScene.Animations[0], transform.ToMat4(), allBones);

            int boneCount = allBones.boneInfos.Length;
            var result    = new mat4[boneCount];

            for (int i = 0; i < boneCount; i++)
            {
                result[i] = allBones.boneInfos[i].finalTransformation;
            }

            return(result);
        }
Exemple #3
0
        //Transforms the root node of the scene and writes it back to the native structure
        private unsafe bool TransformScene(IntPtr scene)
        {
            BuildMatrix();

            try
            {
                if (m_scaleRot != Matrix.Identity)
                {
                    AiScene aiScene = MemoryHelper.MarshalStructure <AiScene>(scene);
                    if (aiScene.RootNode == IntPtr.Zero)
                    {
                        return(false);
                    }

                    IntPtr matrixPtr = IntPtr.Add(aiScene.RootNode, MemoryHelper.SizeOf <AiString>()); //Skip over Node Name

                    Matrix matrix = *((Matrix *)matrixPtr);                                            //Get the root transform
                    matrix = matrix * m_scaleRot;                                                      //Transform

                    //Write back to unmanaged mem
                    *((Matrix *)matrixPtr) = matrix;

                    return(true);
                }
            }
            catch (Exception)
            {
            }

            return(false);
        }
        private Texture[] InitTextures(AiScene aiScene, string filename)
        {
            var textures = new Texture[aiScene.MaterialCount];
            // Extract the directory part from the file name
            string directory = new FileInfo(filename).DirectoryName;

            // Initialize the materials
            for (uint i = 0; i < aiScene.MaterialCount; i++)
            {
                AiMaterial material = aiScene.Materials[i];

                if (material.GetTextureCount(AiTextureType.Diffuse) > 0)
                {
                    AiTextureSlot slot     = material.GetTexture(AiTextureType.Diffuse, 0);
                    string        fullname = Path.Combine(directory, slot.FilePath);
                    Bitmap        bitmap;
                    try
                    {
                        bitmap = new Bitmap(fullname);
                    }
                    catch (Exception ex)
                    {
                        var name = fullname.Substring(0, fullname.LastIndexOf('.')) + ".png";
                        bitmap = new Bitmap(name);
                    }
                    //bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
                    var storage = new TexImageBitmap(bitmap);
                    var texture = new Texture(storage,
                                              new TexParameteri(TexParameter.PropertyName.TextureWrapT, (int)GL.GL_REPEAT),
                                              new TexParameteri(TexParameter.PropertyName.TextureWrapS, (int)GL.GL_REPEAT),
                                              new TexParameteri(TexParameter.PropertyName.TextureMinFilter, (int)GL.GL_LINEAR),
                                              new TexParameteri(TexParameter.PropertyName.TextureMagFilter, (int)GL.GL_LINEAR));
                    texture.Initialize();
                    textures[i] = texture;
                }
            }

            return(textures);
        }
        private AllBoneInfos InitBonesInfo(AiScene aiScene)
        {
            List <BoneInfo> boneInfos     = new List <BoneInfo>();
            var             nameIndexDict = new Dictionary <string, uint>();

            for (int i = 0; i < aiScene.MeshCount; i++)
            {
                AiMesh mesh = aiScene.Meshes[i];
                for (int j = 0; j < mesh.BoneCount; j++)
                {
                    AiBone bone     = mesh.Bones[j];
                    string boneName = bone.Name;
                    if (!nameIndexDict.ContainsKey(boneName))
                    {
                        var boneInfo = new BoneInfo(bone);
                        boneInfos.Add(boneInfo);
                        nameIndexDict.Add(boneName, (uint)(boneInfos.Count - 1));
                    }
                }
            }

            return(new AllBoneInfos(boneInfos.ToArray(), nameIndexDict));
        }
        public void RenderBeforeChildren(RenderEventArgs arg)
        {
            ICamera camera        = arg.Camera;
            mat4    projectionMat = camera.GetProjectionMatrix();
            mat4    viewMat       = camera.GetViewMatrix();
            mat4    modelMat      = this.GetModelMatrix();

            ModernRenderUnit unit    = this.RenderUnit;
            RenderMethod     method  = unit.Methods[0];
            ShaderProgram    program = method.Program;

            program.SetUniform("mvpMat", projectionMat * viewMat * modelMat);
            program.SetUniform("normalMat", glm.transpose(glm.inverse(modelMat)));
            program.SetUniform("diffuseColor", this.diffuseColor);
            {
                Texture tex = this.model.Texture;
                if (tex != null)
                {
                    program.SetUniform("textureMap", tex);
                }
            }
            {
                angle += 0.01f;
                vec3 lightDirection = new vec3(
                    (float)Math.Cos(angle), (float)Math.Sin(angle), 1);
                program.SetUniform("lihtDirection", lightDirection);
            }
            if (this.model.container.aiScene.HasAnimations)
            {
                if (this.firstRun)
                {
                    lastTime      = DateTime.Now;
                    this.firstRun = false;
                }

                DateTime now           = DateTime.Now;
                float    timeInSeconds = (float)(now.Subtract(this.lastTime).TotalSeconds);

                AiScene scene        = this.model.container.aiScene;
                mat4[]  boneMatrixes = scene.GetBoneMatrixes(timeInSeconds, this.model.container.GetAllBoneInfos());
                if (boneMatrixes != null)
                {
                    // default pose.
                    program.SetUniform("animation", false);
                    program.SetUniform("transparent", true);
                    this.polygonModeSwitch.On();
                    method.Render();
                    this.polygonModeSwitch.Off();

                    // animation pose.
                    program.SetUniform("animation", boneMatrixes != null);
                    program.SetUniform("transparent", false);
                    program.SetUniform("bones", boneMatrixes);
                    this.polygonModeSwitch.On();
                    method.Render();
                    this.polygonModeSwitch.Off();
                }
                else
                {
                    // no animation found.
                    program.SetUniform("animation", false);

                    this.polygonModeSwitch.On();
                    method.Render();
                    this.polygonModeSwitch.Off();
                }
            }
            else
            {
                program.SetUniform("animation", false);

                this.polygonModeSwitch.On();
                method.Render();
                this.polygonModeSwitch.Off();
            }
        }
Exemple #7
0
    void Display(string filename, IntPtr ptr)
    {
        AiScene scene = Assimp.MemoryHelper.Read <AiScene>(ptr);

        Debug.Log(scene.NumMeshes + " meshes");
        Debug.Log(scene.NumMaterials + " materials");
        Debug.Log(scene.NumTextures + " internal textures");

        var texloader = new TextureLoader {
            scene = scene, basefilename = filename
        };

        materials = new Material[scene.NumMaterials];
        int materials_i = 0;

        foreach (var mat in Assimp.MemoryHelper.FromNativeArray <Assimp.Material, AiMaterial>(scene.Materials, (int)scene.NumMaterials, true))
        {
            var mat1 = new Material(material);
            mat1.color = ToColor(mat.ColorDiffuse);

            if (mat.HasTextureDiffuse)
            {
                var tex = texloader.Load(mat);
                if (tex != null)
                {
                    mat1.mainTexture = tex;
                }
            }

            materials[materials_i++] = mat1;
        }

        mesh2mat = new Material[scene.NumMeshes];
        meshes   = new Mesh[scene.NumMeshes];
        int meshes_i = 0;

        foreach (var mesh in ReadArrayOfPtr <AiMesh>(scene.Meshes, scene.NumMeshes))
        {
            //Debug.Log("   - " + mesh.Name);

            var mesh1 = new Mesh();
            mesh1.name = mesh.Name.GetString();

            var vertices = ReadArrayVector3(mesh.Vertices, mesh.NumVertices);
            mesh1.vertices = vertices;

            if (mesh.TextureCoords.Length > 0)
            {
                IntPtr texCoordsPtr = mesh.TextureCoords[0];
                if (texCoordsPtr != IntPtr.Zero)
                {
                    mesh1.uv = ReadArrayVector3_to_Vector2(texCoordsPtr, mesh.NumVertices);
                }
            }

            List <int> tris  = new List <int>();
            AiFace[]   faces = ReadArrayInline <AiFace>(mesh.Faces, mesh.NumFaces);
            foreach (var face in faces)
            {
                var triangle = ReadArrayInt(face.Indices, face.NumIndices);
                if (triangle.Length == 3)
                {
                    /* XXX for Unity to display meshes properly if they are used in a node with
                     * a negative-determinant transformation, we'd need to swap the orientation
                     * here. */
                    tris.Add(triangle[0]);
                    tris.Add(triangle[2]);
                    tris.Add(triangle[1]);
                }
                else
                {
                    string s = string.Join(", ", triangle.Select(i => vertices[i]));
                    Debug.Log("polygon with " + triangle.Length + " vertices: " + s);
                }
            }
            mesh1.SetTriangles(tris, 0);
            mesh1.RecalculateBounds();
            mesh1.RecalculateNormals();

            mesh2mat[meshes_i] = materials[mesh.MaterialIndex];
            meshes[meshes_i++] = mesh1;
        }

        AiNode root = Assimp.MemoryHelper.Read <AiNode>(scene.RootNode);

        Recurse(transform, root);
    }
 /// <summary>
 /// manage textures and bones.
 /// </summary>
 /// <param name="aiScene"></param>
 /// <param name="filename"></param>
 public AssimpSceneContainer(AiScene aiScene, string filename)
 {
     this.aiScene  = aiScene;
     this.textures = InitTextures(aiScene, filename);
 }