public ImageWithCaption(string titleText, string captionText, string media)
     : this(titleText, captionText)
 {
     image = new Texture(media);
     imageVAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(904, 410));
     imageModelMatrix = Matrix4.CreateTranslation(new Vector3(72, 720 - 65 - 410, 0));
 }
 private Vector3 TransformNormal(Vector3 normal, OpenGL.Matrix4 matrix)
 {
     return(new Vector3(
                normal.X * matrix[0].X + normal.Y * matrix[1].X + normal.Z * matrix[2].X,
                normal.X * matrix[0].Y + normal.Y * matrix[1].Y + normal.Z * matrix[2].Y,
                normal.X * matrix[0].Z + normal.Y * matrix[1].Z + normal.Z * matrix[2].Z));
 }
 private Vector3 Transform(Vector3 position, OpenGL.Matrix4 matrix)
 {
     return(new Vector3(
                position.X * matrix[0].X + position.Y * matrix[1].X + position.Z * matrix[2].X + matrix[3].X,
                position.X * matrix[0].Y + position.Y * matrix[1].Y + position.Z * matrix[2].Y + matrix[3].Y,
                position.X * matrix[0].Z + position.Y * matrix[1].Z + position.Z * matrix[2].Z + matrix[3].Z));
 }
 public ImageAndText(string titleText, string media, string[] bulletText)
     : this(titleText, bulletText)
 {
     image = new Texture(media);
     imageVAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(441, 410));
     imageModelMatrix = Matrix4.CreateTranslation(new Vector3(72, 720 - 227 - 410, 0));
 }
Exemple #5
0
        public static void Draw3DPlotLeft(float[] data, float depth, Vector3 color, Matrix4 viewMatrix, bool log = false)
        {
            if (data.Length < 441) throw new ArgumentException("The argument data was not the correct length.");

            for (int i = 0; i < fftData.Length; i++)
                fftData[i] = new Vector3((log ? Math.Log10(i) * 166 : i) - 441 / 2f, Math.Max(-200, Math.Min(200, 200 * data[i])), depth);
                //fftData[i] = new Vector3(i - 441 / 2f, Math.Max(-200, Math.Min(200, 200 * data[i])), depth);

            if (fftVAO == null)
            {
                int[] array = new int[441];
                for (int i = 0; i < array.Length; i++) array[i] = i;

                fftHandle = GCHandle.Alloc(fftData, GCHandleType.Pinned);
                fftVBO = BufferData(fftVBO, fftData, fftHandle);
                fftVAO = new VAO<Vector3>(Shaders.SimpleColoredShader, fftVBO, "in_position", new VBO<int>(array, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticDraw));
                fftVAO.DrawMode = BeginMode.LineStrip;
            }
            else fftVBO = BufferData(fftVBO, fftData, fftHandle);

            Shaders.SimpleColoredShader.Use();
            Shaders.SimpleColoredShader["projectionMatrix"].SetValue(Program.uiProjectionMatrix);
            Shaders.SimpleColoredShader["viewMatrix"].SetValue(viewMatrix);
            Shaders.SimpleColoredShader["modelMatrix"].SetValue(Matrix4.CreateTranslation(new Vector3(72 + 441 / 2f, 288, 0)));
            Shaders.SimpleColoredShader["color"].SetValue(color);
            fftVAO.Draw();
        }
 private System.Numerics.Matrix4x4 FromMatrix4(OpenGL.Matrix4 matrix)
 {
     return(new System.Numerics.Matrix4x4(
                matrix[0].X, matrix[0].Y, matrix[0].Z, matrix[0].W,
                matrix[1].X, matrix[1].Y, matrix[1].Z, matrix[1].W,
                matrix[2].X, matrix[2].Y, matrix[2].Z, matrix[2].W,
                matrix[3].X, matrix[3].Y, matrix[3].Z, matrix[3].W));
 }
Exemple #7
0
 public static void DrawBox(Matrix4 modelMatrix, Vector3 color)
 {
     Shaders.SimpleColoredShader.Use();
     Shaders.SimpleColoredShader["modelMatrix"].SetValue(modelMatrix);
     Shaders.SimpleColoredShader["viewMatrix"].SetValue(Matrix4.Identity);
     Shaders.SimpleColoredShader["color"].SetValue(color);
     BoxQuad.Draw();
 }
        public void MatrixCreateFromArray()
        {
            Matrix4 matrix = new Matrix4(new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });

            Assert.AreEqual(matrix[0], new Vector4(0, 1, 2, 3));
            Assert.AreEqual(matrix[1], new Vector4(4, 5, 6, 7));
            Assert.AreEqual(matrix[2], new Vector4(8, 9, 10, 11));
            Assert.AreEqual(matrix[3], new Vector4(12, 13, 14, 15));
        }
        public void MatrixMultiply()
        {
            Matrix4 m1 = new Matrix4(new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });
            Matrix4 m2 = new Matrix4(new double[] { 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10 });
            Matrix4 mult = m1 * m2;

            Assert.AreEqual(mult[0], new Vector4(220, 230, 190, 100));
            Assert.AreEqual(mult[1], new Vector4(740, 710, 630, 500));
            Assert.AreEqual(mult[2], new Vector4(1260, 1190, 1070, 900));
            Assert.AreEqual(mult[3], new Vector4(1780, 1670, 1510, 1300));
        }
        public void MatrixSubtract()
        {
            Matrix4 m1 = new Matrix4(new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });
            Matrix4 m2 = new Matrix4(new double[] { 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10 });
            Matrix4 difference = m1 - m2;

            Assert.AreEqual(difference[0], m1[0] - m2[0]);
            Assert.AreEqual(difference[1], m1[1] - m2[1]);
            Assert.AreEqual(difference[2], m1[2] - m2[2]);
            Assert.AreEqual(difference[3], m1[3] - m2[3]);
        }
        public void MatrixAdd()
        {
            Matrix4 m1 = new Matrix4(new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });
            Matrix4 m2 = new Matrix4(new double[] { 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10 });
            Matrix4 sum = m1 + m2;

            Assert.AreEqual(sum[0], m1[0] + m2[0]);
            Assert.AreEqual(sum[1], m1[1] + m2[1]);
            Assert.AreEqual(sum[2], m1[2] + m2[2]);
            Assert.AreEqual(sum[3], m1[3] + m2[3]);
        }
Exemple #12
0
        public static void OnReshape()
        {
            uiProjectionMatrix = Matrix4.CreateTranslation(new Vector3(-Program.Width / 2, -Program.Height / 2, 0)) * Matrix4.CreateOrthographic(Program.Width, Program.Height, -500, 1000);

            // the uiProjectMatrix need only be set once (unless we reshape)
            Shaders.FontShader.Use();
            Shaders.FontShader["projectionMatrix"].SetValue(uiProjectionMatrix);

            Shaders.SimpleColoredShader.Use();
            Shaders.SimpleColoredShader["projectionMatrix"].SetValue(uiProjectionMatrix);
        }
        private VoxelChunkManager()
        {
            chunks = new Dictionary<Tuple<int, int>, VoxelChunk>();
            chunksToMesh = new Dictionary<Tuple<int, int>, VoxelChunk>();
            chunkLoadQueue = new Queue<Tuple<int, int>>();
            noise = new OpenSimplexNoise(2);
            frustum = new Frustum();
            chunkScalingMatrix = Matrix4.CreateScaling(new Vector3(ChunkWidth, ChunkHeight, ChunkDepth));

            chunkShader = new ShaderProgram(chunkvertexshader, chunkfragmentshader);
            chunkShader["lightDirection"].SetValue(new Vector3(-0.75, -0.5, -1).Normalize());
        }
Exemple #14
0
        public TwoImages(string titleText, string media1, string media2)
        {
            title = new Text(Text.FontSize._72pt, titleText, Common.TitleColor);
            title.ModelMatrix = Matrix4.CreateTranslation(new Vector3(80, 720 - 120, 0));

            image1 = new Texture(media1);
            image1VAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(441, 410));
            image1ModelMatrix = Matrix4.CreateTranslation(new Vector3(72, 720 - 227 - 410, 0));

            image2 = new Texture(media2);
            image2VAO = Utilities.CreateQuad(Shaders.SimpleTexturedShader, Vector2.Zero, new Vector2(441, 410));
            image2ModelMatrix = Matrix4.CreateTranslation(new Vector3(535, 720 - 227 - 410, 0));
        }
        public void MatrixCreateFromVectors()
        {
            Vector4 v4 = new Vector4(0, 1, 2, 3);
            Vector4 v3 = new Vector4(4, 5, 6, 7);
            Vector4 v2 = new Vector4(8, 9, 10, 11);
            Vector4 v1 = new Vector4(12, 13, 14, 15);

            Matrix4 matrix = new Matrix4(v1, v2, v3, v4);

            Assert.AreEqual(matrix[0], v1);
            Assert.AreEqual(matrix[1], v2);
            Assert.AreEqual(matrix[2], v3);
            Assert.AreEqual(matrix[3], v4);
        }
Exemple #16
0
        public VoxelChunk(int _chunkX, int _chunkZ, int _width, int _height, int _depth)
        {
            chunkX = _chunkX;
            chunkZ = _chunkZ;
            width = _width;
            height = _height;
            depth = _depth;

            bounds = new AxisAlignedBoundingBox(new Vector3(chunkX * width, 0, chunkZ * depth), new Vector3((chunkX + 1) * width, height, (chunkZ + 1) * depth));
            translationMatrix = Matrix4.CreateTranslation(new Vector3(chunkX * width, 0, chunkZ * depth));

            meshBuilt = false;
            data = new ushort[width, height, depth];
        }
        /// <summary>
        /// Builds the Planes so that they make up the left, right, up, down, front and back of the Frustum.
        /// </summary>
        /// <param name="clipMatrix">The combined projection and view matrix (usually from the camera).</param>
        public void UpdateFrustum(Matrix4 clipMatrix)
        {
            planes[0].Set(clipMatrix[3].w - clipMatrix[3].x, new Vector3(clipMatrix[0].w - clipMatrix[0].x, clipMatrix[1].w - clipMatrix[1].x, clipMatrix[2].w - clipMatrix[2].x));
            planes[1].Set(clipMatrix[3].w + clipMatrix[3].x, new Vector3(clipMatrix[0].w + clipMatrix[0].x, clipMatrix[1].w + clipMatrix[1].x, clipMatrix[2].w + clipMatrix[2].x));
            planes[2].Set(clipMatrix[3].w + clipMatrix[3].y, new Vector3(clipMatrix[0].w + clipMatrix[0].y, clipMatrix[1].w + clipMatrix[1].y, clipMatrix[2].w + clipMatrix[2].y));
            planes[3].Set(clipMatrix[3].w - clipMatrix[3].y, new Vector3(clipMatrix[0].w - clipMatrix[0].y, clipMatrix[1].w - clipMatrix[1].y, clipMatrix[2].w - clipMatrix[2].y));
            planes[4].Set(clipMatrix[3].w - clipMatrix[3].z, new Vector3(clipMatrix[0].w - clipMatrix[0].z, clipMatrix[1].w - clipMatrix[1].z, clipMatrix[2].w - clipMatrix[2].z));
            planes[5].Set(clipMatrix[3].w + clipMatrix[3].z, new Vector3(clipMatrix[0].w + clipMatrix[0].z, clipMatrix[1].w + clipMatrix[1].z, clipMatrix[2].w + clipMatrix[2].z));

            for (int i = 0; i < 6; i++)
            {
                float t_mag = planes[i].Normal.Length;
                planes[i].Scalar /= t_mag;
                planes[i].Normal /= t_mag;
            }
        }
Exemple #18
0
        public void Vector3StaticMethods()
        {
            for (int i = 0; i < 1000000; i++)
            {
                Vector3    v1 = new Vector3(GetRandomFloat(), GetRandomFloat(), GetRandomFloat());
                Vector3    v2 = new Vector3(GetRandomFloat(), GetRandomFloat(), GetRandomFloat());
                Vector3    v3 = new Vector3(GetRandomFloat(), GetRandomFloat(), GetRandomFloat());
                float      f1 = GetRandomFloat();
                Quaternion q  = new Quaternion(GetRandomFloat(), GetRandomFloat(), GetRandomFloat(), GetRandomFloat());
                float[]    ma = new float[16];
                for (int j = 0; j < 16; j++)
                {
                    ma[j] = GetRandomFloat();
                }
                OpenGL.Matrix4 m = new OpenGL.Matrix4(ma);

                Assert.AreEqual(Vector3.Abs(v1), new Vector3(Math.Abs(v1.X), Math.Abs(v1.Y), Math.Abs(v1.Z)));
                Assert.AreEqual(Vector3.Add(v1, v2), new Vector3(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z));
                Assert.AreEqual(Vector3.Clamp(v1, v2, v3), new Vector3(Clamp(v1.X, v2.X, v3.X), Clamp(v1.Y, v2.Y, v3.Y), Clamp(v1.Z, v2.Z, v3.Z)));
                Assert.AreEqual(Vector3.Cross(v1, v2), new Vector3(v1.Y * v2.Z - v1.Z * v2.Y, v1.Z * v2.X - v1.X * v2.Z, v1.X * v2.Y - v1.Y * v2.X));
#if USE_NUMERICS
                Assert.IsTrue(CloseEnough(Vector3.Distance(v1, v2), (v1 - v2).Length()));
#else
                Assert.IsTrue(CloseEnough(Vector3.Distance(v1, v2), (v1 - v2).Length));
#endif
                Assert.IsTrue(CloseEnough(Vector3.DistanceSquared(v1, v2), (v1 - v2).LengthSquared()));
                Assert.AreEqual(Vector3.Divide(v1, f1), new Vector3(v1.X / f1, v1.Y / f1, v1.Z / f1));
                Assert.AreEqual(Vector3.Divide(v1, v2), new Vector3(v1.X / v2.X, v1.Y / v2.Y, v1.Z / v2.Z));
                Assert.IsTrue(CloseEnough(Vector3.Dot(v1, v2), v1.X * v2.X + v1.Y * v2.Y + v1.Z * v2.Z));
                Assert.IsTrue(CloseEnough(Vector3.Lerp(v1, v2, f1), v1 + (v2 - v1) * f1, 1e-02f));
                Assert.AreEqual(Vector3.Max(v1, v2), new Vector3(Math.Max(v1.X, v2.X), Math.Max(v1.Y, v2.Y), Math.Max(v1.Z, v2.Z)));
                Assert.AreEqual(Vector3.Min(v1, v2), new Vector3(Math.Min(v1.X, v2.X), Math.Min(v1.Y, v2.Y), Math.Min(v1.Z, v2.Z)));
                Assert.AreEqual(Vector3.Multiply(v1, f1), new Vector3(v1.X * f1, v1.Y * f1, v1.Z * f1));
                Assert.AreEqual(Vector3.Multiply(f1, v1), new Vector3(v1.X * f1, v1.Y * f1, v1.Z * f1));
                Assert.AreEqual(Vector3.Multiply(v1, v2), new Vector3(v1.X * v2.X, v1.Y * v2.Y, v1.Z * v2.Z));
                Assert.AreEqual(Vector3.Negate(v1), new Vector3(-v1.X, -v1.Y, -v1.Z));
#if USE_NUMERICS
                Assert.AreEqual(Vector3.Normalize(v1), v1 / v1.Length());
#else
                Assert.AreEqual(Vector3.Normalize(v1), v1 / v1.Length);
#endif
                Assert.IsTrue(CloseEnough(Vector3.Reflect(v1, v2), v1 - Vector3.Dot(v1, v2) * v2 * 2f));
                Assert.IsTrue(CloseEnough(Vector3.SquareRoot(v1), new Vector3((float)Math.Sqrt(v1.X), (float)Math.Sqrt(v1.Y), (float)Math.Sqrt(v1.Z))));
                Assert.AreEqual(Vector3.Subtract(v1, v2), new Vector3(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z));
                Assert.IsTrue(CloseEnough(Vector3.Transform(v1, q), Transform(v1, q), 1e-01f));
            }
        }
Exemple #19
0
        /// <summary>
        /// Builds the Planes so that they make up the left, right, up, down, front and back of the Frustum
        /// </summary>
        public void UpdateFrustum(Matrix4 projectionMatrix, Matrix4 modelviewMatrix)
        {
            Matrix4 clipMatrix = modelviewMatrix * projectionMatrix;

            planes[0] = new Plane(clipMatrix[0].w - clipMatrix[0].x, clipMatrix[1].w - clipMatrix[1].x, clipMatrix[2].w - clipMatrix[2].x, clipMatrix[3].w - clipMatrix[3].x);
            planes[1] = new Plane(clipMatrix[0].w + clipMatrix[0].x, clipMatrix[1].w + clipMatrix[1].x, clipMatrix[2].w + clipMatrix[2].x, clipMatrix[3].w + clipMatrix[3].x);
            planes[2] = new Plane(clipMatrix[0].w + clipMatrix[0].y, clipMatrix[1].w + clipMatrix[1].y, clipMatrix[2].w + clipMatrix[2].y, clipMatrix[3].w + clipMatrix[3].y);
            planes[3] = new Plane(clipMatrix[0].w - clipMatrix[0].y, clipMatrix[1].w - clipMatrix[1].y, clipMatrix[2].w - clipMatrix[2].y, clipMatrix[3].w - clipMatrix[3].y);
            planes[4] = new Plane(clipMatrix[0].w - clipMatrix[0].z, clipMatrix[1].w - clipMatrix[1].z, clipMatrix[2].w - clipMatrix[2].z, clipMatrix[3].w - clipMatrix[3].z);
            planes[5] = new Plane(clipMatrix[0].w + clipMatrix[0].z, clipMatrix[1].w + clipMatrix[1].z, clipMatrix[2].w + clipMatrix[2].z, clipMatrix[3].w + clipMatrix[3].z);

            for (int i = 0; i < 6; i++)
            {
                float t_mag = planes[i].Normal.Length;
                planes[i].Scalar /= t_mag;
                planes[i].Normal /= t_mag;
            }
        }
Exemple #20
0
 public void LoadViewMat(Matrix4 mat)
 {
     GL.UniformMatrix4(loc_view, false, ref mat);
 }
Exemple #21
0
 public void LoadTransformMat(Matrix4 mat)
 {
     GL.UniformMatrix4(loc_transformation, false, ref mat);
 }
        public void MatrixMultiplyByFloat()
        {
            Vector4 v4 = new Vector4(0, 1, 2, 3);
            Vector4 v3 = new Vector4(4, 5, 6, 7);
            Vector4 v2 = new Vector4(8, 9, 10, 11);
            Vector4 v1 = new Vector4(12, 13, 14, 15);

            Matrix4 matrix = new Matrix4(v1, v2, v3, v4);
            Matrix4 mult = matrix * 2f;

            Assert.AreEqual(mult[0], v1 * 2f);
            Assert.AreEqual(mult[1], v2 * 2f);
            Assert.AreEqual(mult[2], v3 * 2f);
            Assert.AreEqual(mult[3], v4 * 2f);
        }
        public void Render(Matrix4 test, bool outline)
        {
            chunkShader.Use();
            chunkShader["projectionMatrix"].SetValue(projectionMatrix);
            chunkShader["viewMatrix"].SetValue(viewMatrix);

            vertexCount = 0;
            renderedChunks = 0;

            frustum.UpdateFrustum(projectionMatrix, test);

            foreach (var kvp in chunks)
            {
                // frustum check
                var coords = kvp.Key;
                var chunk = kvp.Value;

                bool intersects = frustum.Intersects(chunk.AABB);
                if (outline)
                {
                    Gl.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
                    Gl.Disable(EnableCap.CullFace);
                    //VoxelChunk.ChunkBoundsShader.Use();
                    //VoxelChunk.ChunkBoundsShader["projectionViewMatrix"].SetValue(viewMatrix * projectionMatrix);
                    //VoxelChunk.ChunkBoundsShader["modelMatrix"].SetValue();
                    //Gl.BindBufferToShaderAttribute(intersects ? VoxelChunk.redColors : VoxelChunk.whiteColors, VoxelChunk.ChunkBoundsShader, "in_color");
                    //Gl.BindBufferToShaderAttribute(VoxelChunk.boundsVertices, VoxelChunk.ChunkBoundsShader, "in_position");
                    //Gl.BindBuffer(VoxelChunk.boundsInidices);

                    //Gl.DrawElements(BeginMode.Quads, VoxelChunk.boundsInidices.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
                    Cube.Render(projectionMatrix, viewMatrix, chunkScalingMatrix * chunk.TranslationMatrix, intersects?"ED1111" : "ffffff");
                }
                if (!intersects)
                    continue;

                Gl.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
                Gl.Enable(EnableCap.CullFace);
                chunkShader.Use();
                chunkShader["modelMatrix"].SetValue(chunk.TranslationMatrix);
                Gl.BindBufferToShaderAttribute(chunk.Vertices, chunkShader, "vertexPosition");
                Gl.BindBufferToShaderAttribute(chunk.Normals, chunkShader, "vertexNormal");
                Gl.BindBufferToShaderAttribute(chunk.Colors, chunkShader, "vertexColor");
                Gl.BindBuffer(chunk.Indices);

                Gl.DrawElements(BeginMode.Triangles, chunk.Indices.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

                vertexCount += chunk.Vertices.Count;
                renderedChunks++;
            }
        }
Exemple #24
0
        /// <summary>
        /// Project it on the screen
        /// </summary>
        /// <param name="objPos"></param>
        /// <param name="projection"></param>
        /// <param name="view"></param>
        /// <param name="viewport"></param>
        /// <returns>bad...</returns>
        public static Vector4 Project(OpenTK.Vector4 objPos, Matrix4 projection, Matrix4 view, Size viewport)
        {
            Vector4 vec = objPos;

            vec = Vector4.Transform(vec, Matrix4.Mult(projection, view));

            vec.X = (vec.X + 1) * (viewport.Width / 2);
            vec.Y = (vec.Y + 1) * (viewport.Height / 2);

            return vec;
        }
Exemple #25
0
        static void Main(string[] args)
        {
            timefromstart = System.Diagnostics.Stopwatch.StartNew();
            Console.WriteLine("Initializing GLUT - {0}s", getTimeFromStart().ToString());
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("kVoxGame");
            Console.WriteLine("GLUT window created - {0}s", getTimeFromStart().ToString());

            //Callbacks
            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            //Mouse
            Glut.glutMouseFunc(OnMouse);
            Glut.glutMotionFunc(OnMove);

            //Keyboard
            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Console.WriteLine("GLUT callbacks binded - {0}s", getTimeFromStart().ToString());

            Gl.Enable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.Enable(EnableCap.Multisample);
            Gl.Enable(EnableCap.SampleAlphaToCoverage);
            Gl.Enable(EnableCap.FragmentLightingSgix);
            Gl.Enable(EnableCap.CullFace);

            Console.WriteLine("GL Enables enabled :D - {0}s", getTimeFromStart().ToString());

            skydomeTexture = new Texture("skydome.jpg");

            //Gl.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
            // create main shader program
            terrainSP = new ShaderProgram(terrainVS, terrainFS);
            terrainSP.Use();
            terrainSP["color"].SetValue(new Vector3(0, 0.8, 0));
            projectionMatrix = Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f);
            terrainSP["projection_matrix"].SetValue(projectionMatrix);
            terrainSP["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)) * Matrix4.CreateRotation(new Vector3(0, 0, 0), 0.0f));
            Console.WriteLine("Shader program (main) compiled and data injected - {0}s", getTimeFromStart().ToString());

            // create main skybox program
            skyboxSP = new ShaderProgram(skyboxVS, skyboxFS);
            skyboxSP.Use();
            skyboxSP["color"].SetValue(new Vector3(0.2, 1.0, 1.0));
            skyboxSP["resolution"].SetValue(new Vector2(width, height));
            projectionMatrix = Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f);
            skyboxSP["projection_matrix"].SetValue(projectionMatrix);
            skyboxSP["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)) * Matrix4.CreateRotation(new Vector3(0, 0, 0), 0.0f));
            Console.WriteLine("Shader program (skybox) compiled and data injected - {0}s", getTimeFromStart().ToString());

            //Setup camera
            camera = new Camera(new Vector3(0, 0, 10), Quaternion.Identity);
            camera.SetDirection(new Vector3(0, 0, -1));

            Console.WriteLine("Cam setup complete - {0}s", getTimeFromStart().ToString());

            watch = System.Diagnostics.Stopwatch.StartNew();
            chunks = new VoxelChunk[4];
            //instance few voxel chunks
            chunks[0] = new VoxelChunk(0,0);
            chunks[1] = new VoxelChunk(0, 32);
            chunks[2] = new VoxelChunk(32, 0);
            chunks[3] = new VoxelChunk(32, 32);
            Console.WriteLine("Chunks added to array - {0}s", getTimeFromStart().ToString());

            //init frustum
            frustum = new Frustum();
            frustum.UpdateFrustum(projectionMatrix, camera.ViewMatrix);
            Console.WriteLine("starting main GLUT loop - {0}s", getTimeFromStart().ToString());

            Glut.glutMainLoop();
        }
 /// <summary>
 /// Creates an orientated bounding box of size min, max
 /// </summary>
 /// <param name="Min">Minimum x,y,z</param>
 /// <param name="Max">Maximum x,y,z</param>
 public OrientatedBoundingBox(Vector3 Min, Vector3 Max)
 {
     box = new AxisAlignedBoundingBox(Min, Max);
     modelMatrix = Matrix4.Identity;
 }
Exemple #27
0
 public void SetValue(Matrix4 param)
 {
     if (Type != typeof(Matrix4)) throw new Exception(string.Format("SetValue({0}) was given a Matrix4.", Type));
     Gl.UniformMatrix4fv(location, 1, false, param.ToFloat());
 }
Exemple #28
0
        public static void EnableStencil(Matrix4 modelMatrix)
        {
            // draw an outline around the chunk
            Gl.ClearStencil(0);
            Gl.Clear(ClearBufferMask.StencilBufferBit);
            Gl.Enable(EnableCap.StencilTest);

            Gl.StencilFunc(StencilFunction.Always, 1, 0xFFFF);
            Gl.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);

            Gl.ColorMask(false, false, false, false);

            Shaders.SimpleColoredShader.Use();
            Shaders.SimpleColoredShader["modelMatrix"].SetValue(modelMatrix);
            Shaders.SimpleColoredShader["viewMatrix"].SetValue(Matrix4.Identity);
            StencilQuad.Draw();

            Gl.ColorMask(true, true, true, true);
        }
        public static void Run()
        {
            using (var w = new GameWindow(720, 480, null, "ComGr", GameWindowFlags.Default, DisplayDevice.Default, 4, 0, OpenTK.Graphics.GraphicsContextFlags.ForwardCompatible))
            {
                int hProgram = 0;
                int hTexture = 0;
                int hHeight  = 0;

                int   vaoTriangle        = 0;
                int[] triangleIndices    = null;
                int   vboTriangleIndices = 0;

                byte[] imageData;
                byte[] heightData;

                double time     = 0;
                int    gridSize = 100;

                w.Load += (o, ea) =>
                {
                    //set up opengl
                    GL.ClearColor(0.5f, 0.5f, 0.5f, 0);
                    GL.ClearDepth(1);
                    GL.Enable(EnableCap.DepthTest);
                    GL.DepthFunc(DepthFunction.Less);
                    //GL.Enable(EnableCap.CullFace);

                    //load, compile and link shaders
                    //see https://www.khronos.org/opengl/wiki/Vertex_Shader
                    var VertexShaderSource = @"
#version 400 core

in vec3 pos;
in vec2 uvVertex;

uniform mat4 model;
uniform mat4 projection;
uniform sampler2D height;

out vec2 uvFragment;
out vec3 absolutePos;
out vec3 normalFragment;

float getHeight(in vec2 pos)
{
    float h = texture(height, pos).x;
    return log(h*30+1) * 8;
}

vec3 getNormal(in vec2 pos)
{
    float offset = 1.0/float(textureSize(height,0).x);
    vec2 xOff = vec2(offset, 0);
    vec2 zOff = vec2(0, offset);

    vec3 x = vec3(offset*2, getHeight(pos+xOff) - getHeight(pos-xOff), 0);
    vec3 z = vec3(0,        getHeight(pos+zOff) - getHeight(pos-zOff), offset*2);

    return normalize(cross(z, x));
}

void main()
{
    uvFragment = uvVertex;

    absolutePos = (model * vec4(pos, 1)).xyz;
    
    vec3 n = getNormal(uvVertex);
    normalFragment = normalize((model * vec4(n, 0)).xyz);

    vec3 p = pos;
    p.y = getHeight(uvVertex);

    gl_Position = projection * vec4(p,1);
}
                        ";
                    var hVertexShader      = GL.CreateShader(ShaderType.VertexShader);
                    GL.ShaderSource(hVertexShader, VertexShaderSource);
                    GL.CompileShader(hVertexShader);
                    GL.GetShader(hVertexShader, ShaderParameter.CompileStatus, out int status);
                    if (status != 1)
                    {
                        throw new Exception(GL.GetShaderInfoLog(hVertexShader));
                    }

                    //see https://www.khronos.org/opengl/wiki/Fragment_Shader
                    var FragmentShaderSource = @"
#version 400 core

uniform sampler2D tex;

in vec3 absolutePos;
in vec2 uvFragment;
in vec3 lightPos;
in vec3 normalFragment;

out vec4 color;

void main()
{
    vec4 col = texture(tex, uvFragment);

    vec3 lightPos = vec3(2, 7, 0);
    vec3 toLight = normalize(lightPos - absolutePos);
    float diffuse = max(0, dot(toLight, normalFragment));

    vec3 eye = vec3(0, 0, 0);
    vec3 viewDir = normalize(absolutePos - eye);
    vec3 specularDir = normalFragment * (2 * dot(normalFragment, toLight)) - toLight;
    specularDir = normalize(specularDir);
    vec3 specular = vec3(0.8) * pow(max(0.0, -dot(specularDir, viewDir)), 5);

    color = vec4(0.1)*col + diffuse * col + vec4(specular, 1);

}
                        ";
                    var hFragmentShader      = GL.CreateShader(ShaderType.FragmentShader);
                    GL.ShaderSource(hFragmentShader, FragmentShaderSource);
                    GL.CompileShader(hFragmentShader);
                    GL.GetShader(hFragmentShader, ShaderParameter.CompileStatus, out status);
                    if (status != 1)
                    {
                        throw new Exception(GL.GetShaderInfoLog(hFragmentShader));
                    }

                    //link shaders to a program
                    hProgram = GL.CreateProgram();
                    GL.AttachShader(hProgram, hFragmentShader);
                    GL.AttachShader(hProgram, hVertexShader);
                    GL.LinkProgram(hProgram);
                    GL.GetProgram(hProgram, GetProgramParameterName.LinkStatus, out status);
                    if (status != 1)
                    {
                        throw new Exception(GL.GetProgramInfoLog(hProgram));
                    }



                    var triangleVertices = new float[(gridSize + 1) * (gridSize + 1) * 3];
                    var uvs = new float[(gridSize + 1) * (gridSize + 1) * 2];
                    triangleIndices = new int[gridSize * gridSize * 2 * 3];

                    for (int i = 0; i < gridSize + 1; i++)
                    {
                        for (int j = 0; j < gridSize + 1; j++)
                        {
                            triangleVertices[((gridSize + 1) * i + j) * 3 + 0] = i;
                            triangleVertices[((gridSize + 1) * i + j) * 3 + 1] = 0;
                            triangleVertices[((gridSize + 1) * i + j) * 3 + 2] = j;

                            uvs[((gridSize + 1) * i + j) * 2 + 0] = i / (float)gridSize;
                            uvs[((gridSize + 1) * i + j) * 2 + 1] = j / (float)gridSize;
                        }
                    }

                    for (int i = 0; i < gridSize; i++)
                    {
                        for (int j = 0; j < gridSize; j++)
                        {
                            triangleIndices[(gridSize * i + j) * 6 + 0] = ((gridSize + 1) * i + j) + (gridSize + 1) * 0 + 0;
                            triangleIndices[(gridSize * i + j) * 6 + 1] = ((gridSize + 1) * i + j) + (gridSize + 1) * 0 + 1;
                            triangleIndices[(gridSize * i + j) * 6 + 2] = ((gridSize + 1) * i + j) + (gridSize + 1) * 1 + 0;

                            triangleIndices[(gridSize * i + j) * 6 + 3] = ((gridSize + 1) * i + j) + (gridSize + 1) * 1 + 0;
                            triangleIndices[(gridSize * i + j) * 6 + 4] = ((gridSize + 1) * i + j) + (gridSize + 1) * 0 + 1;
                            triangleIndices[(gridSize * i + j) * 6 + 5] = ((gridSize + 1) * i + j) + (gridSize + 1) * 1 + 1;
                        }
                    }


                    //upload model vertices to a vbo
                    var vboTriangleVertices = GL.GenBuffer();
                    GL.BindBuffer(BufferTarget.ArrayBuffer, vboTriangleVertices);
                    GL.BufferData(BufferTarget.ArrayBuffer, triangleVertices.Length * sizeof(float), triangleVertices, BufferUsageHint.StaticDraw);


                    // upload model indices to a vbo
                    vboTriangleIndices = GL.GenBuffer();
                    GL.BindBuffer(BufferTarget.ElementArrayBuffer, vboTriangleIndices);
                    GL.BufferData(BufferTarget.ElementArrayBuffer, triangleIndices.Length * sizeof(int), triangleIndices, BufferUsageHint.StaticDraw);



                    var vboUvs = GL.GenBuffer();
                    GL.BindBuffer(BufferTarget.ArrayBuffer, vboUvs);
                    GL.BufferData(BufferTarget.ArrayBuffer, uvs.Length * sizeof(float), uvs, BufferUsageHint.StaticDraw);



                    //set up a vao
                    vaoTriangle = GL.GenVertexArray();
                    GL.BindVertexArray(vaoTriangle);

                    GL.EnableVertexAttribArray(GL.GetAttribLocation(hProgram, "pos"));
                    GL.BindBuffer(BufferTarget.ArrayBuffer, vboTriangleVertices);
                    GL.VertexAttribPointer(GL.GetAttribLocation(hProgram, "pos"), 3, VertexAttribPointerType.Float, false, 0, 0);



                    GL.EnableVertexAttribArray(GL.GetAttribLocation(hProgram, "uvVertex"));
                    GL.BindBuffer(BufferTarget.ArrayBuffer, vboUvs);
                    GL.VertexAttribPointer(GL.GetAttribLocation(hProgram, "uvVertex"), 2, VertexAttribPointerType.Float, false, 0, 0);


                    var image  = new Bitmap("./stones.bmp");
                    var imageW = image.Width;
                    var h      = image.Height;
                    imageData = new byte[imageW * h * 3];
                    BitmapData data = image.LockBits(new Rectangle(0, 0, imageW, h), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    unsafe
                    {
                        byte *p = (byte *)data.Scan0;
                        for (int i = 0; i < imageW * h * 3; i += 3)
                        {
                            imageData[i]     = *(p++); //r
                            imageData[i + 1] = *(p++); //g
                            imageData[i + 2] = *(p++); //b
                        }

                        image.UnlockBits(data);
                    }

                    GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1);
                    GL.GenTextures(1, out hTexture);
                    GL.BindTexture(TextureTarget.Texture2D, hTexture);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Srgb8, image.Width, image.Height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Rgb, PixelType.UnsignedByte, imageData);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

                    image      = new Bitmap("./height.bmp");
                    imageW     = image.Width;
                    h          = image.Height;
                    heightData = new byte[imageW * h * 3];
                    data       = image.LockBits(new Rectangle(0, 0, imageW, h), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    unsafe
                    {
                        byte *p = (byte *)data.Scan0;
                        for (int i = 0; i < imageW * h * 3; i += 3)
                        {
                            heightData[i]     = *(p++); //r
                            heightData[i + 1] = *(p++); //g
                            heightData[i + 2] = *(p++); //b
                        }

                        image.UnlockBits(data);
                    }

                    GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1);
                    GL.GenTextures(1, out hHeight);
                    GL.BindTexture(TextureTarget.Texture2D, hHeight);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Srgb8, image.Width, image.Height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Rgb, PixelType.UnsignedByte, heightData);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
                    {
                        //check for errors during all previous calls
                        var error = GL.GetError();
                        if (error != ErrorCode.NoError)
                        {
                            throw new Exception(error.ToString());
                        }
                    }
                };

                w.UpdateFrame += (o, fea) =>
                {
                    //perform logic

                    time += fea.Time;
                };

                w.RenderFrame += (o, fea) =>
                {
                    //clear screen and z-buffer
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    //switch to our shader
                    GL.UseProgram(hProgram);

                    GL.ActiveTexture(TextureUnit.Texture0);
                    GL.BindTexture(TextureTarget.Texture2D, hTexture);
                    GL.Uniform1(GL.GetUniformLocation(hProgram, "tex"), 0);

                    GL.ActiveTexture(TextureUnit.Texture1);
                    GL.BindTexture(TextureTarget.Texture2D, hHeight);
                    GL.Uniform1(GL.GetUniformLocation(hProgram, "height"), 1);

                    var scale       = Matrix4.CreateScale(5f / gridSize);
                    var transCenter = Matrix4.CreateTranslation(-gridSize / 2, 0f, -gridSize / 2);
                    var rotate      = Matrix4x4.CreateFromYawPitchRoll((float)time / 2, 0, 0).ToGlMatrix();
                    var tilt        = Matrix4x4.CreateFromYawPitchRoll(0, 0.2f, 0).ToGlMatrix();

                    var translate   = Matrix4.CreateTranslation(0f, -1.5f, -5f);
                    var perspective = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 2, 1, 1, 100);

                    var allTransforms = transCenter * scale * rotate * tilt * translate;

                    GL.UniformMatrix4(GL.GetUniformLocation(hProgram, "model"), false, ref allTransforms);
                    allTransforms = allTransforms * perspective;
                    GL.UniformMatrix4(GL.GetUniformLocation(hProgram, "projection"), false, ref allTransforms);



                    //render our model
                    GL.BindVertexArray(vaoTriangle);
                    GL.BindBuffer(BufferTarget.ElementArrayBuffer, vboTriangleIndices);
                    GL.DrawElements(PrimitiveType.Triangles, triangleIndices.Length, DrawElementsType.UnsignedInt, 0);


                    //display
                    w.SwapBuffers();

                    var error = GL.GetError();
                    if (error != ErrorCode.NoError)
                    {
                        throw new Exception(error.ToString());
                    }
                };

                w.Resize += (o, ea) =>
                {
                    GL.Viewport(w.ClientRectangle);
                };

                w.Run();
            }
        }
Exemple #30
0
        public static void DrawXPlotter(Matrix4 modelMatrix)
        {
            DrawBox(modelMatrix, SubtitleColor);
            Shaders.SimpleColoredShader["color"].SetValue(TextColor);

            CrosshairVAO.VertexCount = 2;
            CrosshairVAO.Draw();
            CrosshairVAO.VertexCount = 4;
        }
Exemple #31
0
        /// <summary>
        /// This is the frustum.
        /// </summary>
        /// <param name="normalize">Normalize the vectors</param>
        /// <returns>0-3 is left,right,top,bottom, 4-5 is the near/far plane</returns>
        public static Vector4[] GetFrustum(bool normalize)
        {
            // Get bounds of view.
            float[] viewport = new float[4];
            float[] projectiofM = new float[16];
            float[] modelviewfM = new float[16];
            Matrix4 projectionM = new Matrix4();
            Matrix4 modelviewM = new Matrix4();
            Matrix4 projMultimodel;// = new Matrix4();
            Matrix4 ScreenFrustum = new Matrix4(); // all 4 used
            Vector4[] NearFarFrustum = new Vector4[2]; // only 0-1 used, 2-3 is zero
            Vector4[] RetArr = new Vector4[6]; // only 0-1 used, 2-3 is zero
            GL.GetFloat(GetPName.Viewport, viewport);
            GL.GetFloat(GetPName.ProjectionMatrix, out projectionM);
            GL.GetFloat(GetPName.ModelviewMatrix, out modelviewM);
            projMultimodel = Matrix4.Mult(projectionM, modelviewM);

            // Got the wrong order used columns when it should have been rows.....
            /*Vector4 rPlane = new Vector4(projMultimodel.Column0.W - projMultimodel.Column0.X,
                projMultimodel.Column1.W - projMultimodel.Column1.X,
                projMultimodel.Column2.W - projMultimodel.Column2.X,
                projMultimodel.Column3.W - projMultimodel.Column3.X);*/
            Vector4 rPlane = new Vector4(projMultimodel.Column3.X - projMultimodel.Column0.X,
                projMultimodel.Column3.Y - projMultimodel.Column1.X,
                projMultimodel.Column3.Z - projMultimodel.Column2.X,
                projMultimodel.Column3.W - projMultimodel.Column3.X);
            if (normalize)
            {
                rPlane.Normalize();
            }

            Vector4 rPlaneManual = new Vector4(projMultimodel.M14 - projMultimodel.M11,
                projMultimodel.M24 - projMultimodel.M21,
                projMultimodel.M34 - projMultimodel.M31,
                projMultimodel.M44 - projMultimodel.M41);
            if (normalize)
            {
                rPlaneManual.Normalize();
            }

            /*Vector4 rPlaneManual2;
            unsafe
            {
                float* clip1 = (float*)(&projMultimodel);
                rPlaneManual2 = new Vector4(clip1[3] - clip1[0], clip1[7] - clip1[4], clip1[11] - clip1[8], clip1[15] - clip1[12]);
                rPlaneManual2.Normalize();
            }
            */

            /*Vector4 lPlane = new Vector4(projMultimodel.Column0.W + projMultimodel.Column0.X,
                projMultimodel.Column1.W + projMultimodel.Column1.X,
                projMultimodel.Column2.W + projMultimodel.Column2.X,
                projMultimodel.Column3.W + projMultimodel.Column3.X);*/
            /*
            Vector4 lPlane = new Vector4(projMultimodel.Column3.X + projMultimodel.Column0.X,
                projMultimodel.Column3.Y + projMultimodel.Column1.X,
                projMultimodel.Column3.Z + projMultimodel.Column2.X,
                projMultimodel.Column3.W + projMultimodel.Column3.X);*/
            Vector4 row = projMultimodel.Row0;
            Vector4 lPlane = new Vector4(projMultimodel.Column3.X + row.X,
               projMultimodel.Column3.Y + row.Y,
               projMultimodel.Column3.Z + row.Z,
               projMultimodel.Column3.W + row.W);
            if (normalize)
            {
                lPlane.Normalize();
            }
            /*Vector4 bPlane = new Vector4(projMultimodel.Column0.W - projMultimodel.Column0.Y,
                projMultimodel.Column1.W - projMultimodel.Column1.Y,
                projMultimodel.Column2.W - projMultimodel.Column2.Y,
                projMultimodel.Column3.W - projMultimodel.Column3.Y);*/
            Vector4 bPlane = new Vector4(projMultimodel.Column3.X - projMultimodel.Column0.Y,
                projMultimodel.Column3.Y - projMultimodel.Column1.Y,
                projMultimodel.Column3.Z - projMultimodel.Column2.Y,
                projMultimodel.Column3.W - projMultimodel.Column3.Y);
            if (normalize)
            {
                bPlane.Normalize();
            }
            /*Vector4 tPlane = new Vector4(projMultimodel.Column0.W + projMultimodel.Column0.Y,
                projMultimodel.Column1.W + projMultimodel.Column1.Y,
                projMultimodel.Column2.W + projMultimodel.Column2.Y,
                projMultimodel.Column3.W + projMultimodel.Column3.Y);*/
            Vector4 tPlane = new Vector4(projMultimodel.Column3.X + projMultimodel.Column0.Y,
                projMultimodel.Column3.Y + projMultimodel.Column1.Y,
                projMultimodel.Column3.Z + projMultimodel.Column2.Y,
                projMultimodel.Column3.W + projMultimodel.Column3.Y);
            if (normalize)
            {
                tPlane.Normalize();
            }
            ScreenFrustum = new Matrix4(rPlane, lPlane, bPlane, tPlane);

            /*NearFarFrustum[0] = new Vector4(projMultimodel.Column0.W + projMultimodel.Column0.Z,
                projMultimodel.Column1.W + projMultimodel.Column1.Z,
                projMultimodel.Column2.W + projMultimodel.Column2.Z,
                projMultimodel.Column3.W + projMultimodel.Column3.Z);*/
            NearFarFrustum[0] = new Vector4(projMultimodel.Column3.X + projMultimodel.Column0.Z,
                projMultimodel.Column3.Y + projMultimodel.Column1.Z,
                projMultimodel.Column3.Z + projMultimodel.Column2.Z,
                projMultimodel.Column3.W + projMultimodel.Column3.Z);
            if (normalize)
            {
                NearFarFrustum[0].Normalize();
            }
            /*NearFarFrustum[1] = new Vector4(projMultimodel.Column0.W - projMultimodel.Column0.Z,
                projMultimodel.Column1.W - projMultimodel.Column1.Z,
                projMultimodel.Column2.W - projMultimodel.Column2.Z,
                projMultimodel.Column3.W - projMultimodel.Column3.Z);*/
            NearFarFrustum[1] = new Vector4(projMultimodel.Column3.X - projMultimodel.Column0.Z,
                projMultimodel.Column3.Y - projMultimodel.Column1.Z,
                projMultimodel.Column3.Z - projMultimodel.Column2.Z,
                projMultimodel.Column3.W - projMultimodel.Column3.Z);
            if (normalize)
            {
                NearFarFrustum[1].Normalize();
            }

            RetArr[0] = ScreenFrustum.Row0;
            RetArr[1] = ScreenFrustum.Row1;
            RetArr[2] = ScreenFrustum.Row2;
            RetArr[3] = ScreenFrustum.Row3;
            RetArr[4] = NearFarFrustum[0];
            RetArr[5] = NearFarFrustum[1];

            return RetArr;
        }
Exemple #32
0
        // new test for get max with...
        /// <summary>
        /// UnProject the projection ie. flatten it on the screen
        /// </summary>
        /// <param name="projection"></param>
        /// <param name="view"></param>
        /// <param name="viewport"></param>
        /// <param name="mouse"></param>
        /// <returns>bad...</returns>
        public static Vector4 UnProject(Matrix4 projection, Matrix4 view, Size viewport, Vector3 mouse)
        {
            Vector4 vec;

            vec.X = 2.0f * mouse.X / (float)viewport.Width - 1;
            vec.Y = -(2.0f * mouse.Y / (float)viewport.Height - 1);
            vec.Z = 1.0f;
            vec.W = 1.0f;

            Matrix4 viewInv = Matrix4.Invert(view);
            Matrix4 projInv = Matrix4.Invert(projection);

            Vector4.Transform(ref vec, ref projInv, out vec);
            Vector4.Transform(ref vec, ref viewInv, out vec);

            if (vec.W > float.Epsilon || vec.W < float.Epsilon)
            {
                vec.X /= vec.W;
                vec.Y /= vec.W;
                vec.Z /= vec.W;
            }

            return vec;
        }
 /// <summary>
 /// Builds the Planes so that they make up the left, right, up, down, front and back of the Frustum.
 /// </summary>
 public void UpdateFrustum(Matrix4 projectionMatrix, Matrix4 modelviewMatrix)
 {
     UpdateFrustum(modelviewMatrix * projectionMatrix);
 }
Exemple #34
0
 public static void DrawBullet(Matrix4 modelMatrix)
 {
     Shaders.SimpleTexturedShader.Use();
     Shaders.SimpleTexturedShader["modelMatrix"].SetValue(modelMatrix);
     Gl.BindTexture(BulletTexture);
     BulletQuad.Draw();
 }
Exemple #35
0
        public static void Render(Matrix4 proj, Matrix4 view, Matrix4 model, string color)
        {
            Shader.Use();
            Shader["projectionMatrix"].SetValue(proj);
            Shader["viewMatrix"].SetValue(view);
            Shader["modelMatrix"].SetValue(model);
            Gl.BindBufferToShaderAttribute(Vertices, Shader, "vertexPosition");
            Gl.BindBufferToShaderAttribute(Colors(color), Shader, "vertexColor");
            Gl.BindBuffer(Indices);

            Gl.DrawElements(BeginMode.Quads, Indices.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
        }
        /// <summary>
        /// Transforms the box by a Matrix4.  Will maintain the axis-alignment even during rotations.
        /// </summary>
        /// <param name="TranformMatrix">The Matrix4 to transform by</param>
        public void Transform(Matrix4 TranformMatrix)
        {
            Vector3 t_min = min, t_max = max, t_corner;
            min = max = Vector3.Zero;
            // Compute corners in the order of 0, 6, 5, 1, 2, 4, 7, 3
            // Allows the code to change only one member at a time to get to all corners

            t_corner = t_min;       // min min min
            AddPoint(TranformMatrix * t_corner);
            t_corner.z = t_max.z;   // min min max
            AddPoint(TranformMatrix * t_corner);
            t_corner.y = t_max.y;   // min max max
            AddPoint(TranformMatrix * t_corner);
            t_corner.z = t_min.z;   // min max min
            AddPoint(TranformMatrix * t_corner);
            t_corner.x = t_max.x;   // max max min
            AddPoint(TranformMatrix * t_corner);
            t_corner.z = t_max.z;   // max max max
            AddPoint(TranformMatrix * t_corner);
            t_corner.y = t_min.y;   // max min max
            AddPoint(TranformMatrix * t_corner);
            t_corner.z = t_min.z;   // max min min
            AddPoint(TranformMatrix * t_corner);
        }
Exemple #37
0
        /// <summary>
        /// Get the Viewport matrix
        /// </summary>
        /// <returns>Matrix4 of the viewport</returns>
        public static Matrix4 GetMVP()
        {
            /*//float[] viewport = new float[4];
            //float[] projectiofM = new float[16];
            //float[] modelviewfM = new float[16];
            Matrix4 projectionM = new Matrix4();
            Matrix4 modelviewM = new Matrix4();
            Matrix4 projMultimodel;

            //GL.GetFloat(GetPName.Viewport, viewport);
            GL.GetFloat(GetPName.ProjectionMatrix, out projectionM);
            GL.GetFloat(GetPName.ModelviewMatrix, out modelviewM);
            //projMultimodel = Matrix4.Mult(projectionM, modelviewM);
            projMultimodel = Matrix4.Mult(modelviewM, projectionM);
            return projMultimodel;*/
            if (MVP_changed)
            {
                Matrix4 projectionM = new Matrix4();
                Matrix4 modelviewM = new Matrix4();
                GL.GetFloat(GetPName.ProjectionMatrix, out projectionM);
                GL.GetFloat(GetPName.ModelviewMatrix, out modelviewM);
                MVPMatrix = Matrix4.Mult(modelviewM, projectionM);
                MVP_changed = false;
            }
            return MVPMatrix;
        }
Exemple #38
0
 public void LoadProjectionMat(Matrix4 mat)
 {
     GL.UniformMatrix4(loc_projection, false, ref mat);
 }