Пример #1
0
        /// <summary>
        /// Initialises the scene.
        /// </summary>
        /// <param name="gl">The OpenGL instance.</param>
        /// <param name="width">The width of the screen.</param>
        /// <param name="height">The height of the screen.</param>
        public void Initialise(OpenGL gl, float width, float height)
        {
            //  Set a blue clear colour.
            gl.ClearColor(0.4f, 0.6f, 0.9f, 0.0f);

            //  Create the shader program.
            var vertexShaderSource = ManifestResourceLoader.LoadTextFile("Shader.vert");
            var fragmentShaderSource = ManifestResourceLoader.LoadTextFile("Shader.frag");
            shaderProgram = new ShaderProgram();
            shaderProgram.Create(gl, vertexShaderSource, fragmentShaderSource, null);
            shaderProgram.BindAttributeLocation(gl, attributeIndexPosition, "in_Position");
            shaderProgram.BindAttributeLocation(gl, attributeIndexColour, "in_Color");
            shaderProgram.AssertValid(gl);

            //  Create a perspective projection matrix.
            const float rads = (60.0f / 360.0f) * (float)Math.PI * 2.0f;
            projectionMatrix = glm.perspective(rads, width / height, 0.1f, 100.0f);

            //  Create a view matrix to move us back a bit.
            viewMatrix = glm.translate(new mat4(1.0f), new vec3(0.0f, 0.0f, -5.0f));

            //  Create a model matrix to make the model a little bigger.
            modelMatrix = glm.scale(new mat4(1.0f), new vec3(2.5f));

            //  Now create the geometry for the square.
            CreateVerticesForSquare(gl);
        }
Пример #2
0
 /// <summary>
 /// Creates the projection matrix for the given screen size.
 /// </summary>
 /// <param name="screenWidth">Width of the screen.</param>
 /// <param name="screenHeight">Height of the screen.</param>
 public void CreateProjectionMatrix(float screenWidth, float screenHeight)
 {
     //  Create the projection matrix for our screen size.
     const float S = 0.46f;
     float H = S * screenHeight / screenWidth;
     projectionMatrix = glm.pfrustum(-S, S, -H, H, 1, 100);
 }
Пример #3
0
 public DragParam(mat4 projectionMatrix, mat4 viewMatrix, vec4 viewport, Point lastMousePositionOnScreen)
 {
     this.projectionMatrix = projectionMatrix;
     this.viewMatrix = viewMatrix;
     this.lastMousePositionOnScreen = lastMousePositionOnScreen;
     this.viewport = viewport;
 }
 public EntityRenderer(StaticShader shader,mat4 projectionMatrix)
 {
     this.shader = shader;
     shader.start();
     shader.loadProjectionMatrix(projectionMatrix);
     shader.stop();
 }
Пример #5
0
 public static mat4 createTransformationMatrix(GlmNet.vec3 translation, vec3 rot, float scale)
 {
     mat4 matrix = new mat4(4);
     matrix = glm.translate(matrix, translation);
     mat4 rotMatrix = glm.rotate(rot.x, new vec3(0, 0, 1)) * glm.rotate(rot.y, new vec3(0, 1, 0)) * glm.rotate(rot.z, new vec3(1, 0, 0));
     mat4 scaleMatrix = new mat4(4);
     scaleMatrix = glm.scale(scaleMatrix, new vec3(scale, scale, scale));
     return matrix * rotMatrix * scaleMatrix;
 }
Пример #6
0
        public static mat4 ScaleMatrix(ref vec3 s)
        {
            mat4 r = new mat4(s.x, 0, 0, 0,
                0, s.y, 0, 0,
                0, 0, s.z, 0,
                0, 0, 0, 1);

            return r;
        }
Пример #7
0
        /// <summary>
        /// Gets the inversed matrix.
        /// <para>获取逆矩阵。</para>
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static mat4 inverse(mat4 m)
        {
            float Coef00 = m[2][2] * m[3][3] - m[3][2] * m[2][3];
            float Coef02 = m[1][2] * m[3][3] - m[3][2] * m[1][3];
            float Coef03 = m[1][2] * m[2][3] - m[2][2] * m[1][3];

            float Coef04 = m[2][1] * m[3][3] - m[3][1] * m[2][3];
            float Coef06 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
            float Coef07 = m[1][1] * m[2][3] - m[2][1] * m[1][3];

            float Coef08 = m[2][1] * m[3][2] - m[3][1] * m[2][2];
            float Coef10 = m[1][1] * m[3][2] - m[3][1] * m[1][2];
            float Coef11 = m[1][1] * m[2][2] - m[2][1] * m[1][2];

            float Coef12 = m[2][0] * m[3][3] - m[3][0] * m[2][3];
            float Coef14 = m[1][0] * m[3][3] - m[3][0] * m[1][3];
            float Coef15 = m[1][0] * m[2][3] - m[2][0] * m[1][3];

            float Coef16 = m[2][0] * m[3][2] - m[3][0] * m[2][2];
            float Coef18 = m[1][0] * m[3][2] - m[3][0] * m[1][2];
            float Coef19 = m[1][0] * m[2][2] - m[2][0] * m[1][2];

            float Coef20 = m[2][0] * m[3][1] - m[3][0] * m[2][1];
            float Coef22 = m[1][0] * m[3][1] - m[3][0] * m[1][1];
            float Coef23 = m[1][0] * m[2][1] - m[2][0] * m[1][1];

            vec4 Fac0 = new vec4(Coef00, Coef00, Coef02, Coef03);
            vec4 Fac1 = new vec4(Coef04, Coef04, Coef06, Coef07);
            vec4 Fac2 = new vec4(Coef08, Coef08, Coef10, Coef11);
            vec4 Fac3 = new vec4(Coef12, Coef12, Coef14, Coef15);
            vec4 Fac4 = new vec4(Coef16, Coef16, Coef18, Coef19);
            vec4 Fac5 = new vec4(Coef20, Coef20, Coef22, Coef23);

            vec4 Vec0 = new vec4(m[1][0], m[0][0], m[0][0], m[0][0]);
            vec4 Vec1 = new vec4(m[1][1], m[0][1], m[0][1], m[0][1]);
            vec4 Vec2 = new vec4(m[1][2], m[0][2], m[0][2], m[0][2]);
            vec4 Vec3 = new vec4(m[1][3], m[0][3], m[0][3], m[0][3]);

            vec4 Inv0 = new vec4(Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2);
            vec4 Inv1 = new vec4(Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4);
            vec4 Inv2 = new vec4(Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5);
            vec4 Inv3 = new vec4(Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5);

            vec4 SignA = new vec4(+1, -1, +1, -1);
            vec4 SignB = new vec4(-1, +1, -1, +1);
            mat4 Inverse = new mat4(Inv0 * SignA, Inv1 * SignB, Inv2 * SignA, Inv3 * SignB);

            vec4 Row0 = new vec4(Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0]);

            vec4 Dot0 = new vec4(m[0] * Row0);
            float Dot1 = (Dot0.x + Dot0.y) + (Dot0.z + Dot0.w);

            float OneOverDeterminant = (1f) / Dot1;

            return Inverse * OneOverDeterminant;
        }
Пример #8
0
 public static mat4 createViewMatrix(Camera camera)
 {
     mat4 viewMatrix = new mat4();
     viewMatrix = glm.rotate((float)ToRadiansExtension.ToRadians(camera.getRotation().y), new vec3(1, 0, 0));
     viewMatrix = glm.rotate(viewMatrix,(float)ToRadiansExtension.ToRadians(camera.getRotation().z), new vec3(0, 1, 0));
     viewMatrix = glm.rotate(viewMatrix,(float)ToRadiansExtension.ToRadians(camera.getRotation().x), new vec3(0, 0, 1));
     vec3 negativeCameraPos = new vec3(-camera.getPosition().x, -camera.getPosition().y, -camera.getPosition().z);
     viewMatrix = glm.translate(viewMatrix, negativeCameraPos);
     return viewMatrix;
 }
Пример #9
0
 /// <summary>
 /// Creates the modelview and normal matrix. Also rotates the sceen by a specified amount.
 /// </summary>
 /// <param name="rotationAngle">The rotation angle, in radians.</param>
 public void CreateModelviewAndNormalMatrix(float rotationAngle)
 {
     //  Create the modelview and normal matrix. We'll also rotate the scene
     //  by the provided rotation angle, which means things that draw it
     //  can make the scene rotate easily.
     mat4 rotation = glm.rotate(mat4.identity(), rotationAngle, new vec3(0, 1, 0));
     mat4 translation = glm.translate(mat4.identity(), new vec3(0, 0, -4));
     modelviewMatrix = rotation * translation;
     normalMatrix = modelviewMatrix.to_mat3();
 }
Пример #10
0
        /// <summary>
        /// Creates the projection matrix for the given screen size.
        /// </summary>
        /// <param name="gl">The OpenGL instance.</param>
        /// <param name="screenWidth">Width of the screen.</param>
        /// <param name="screenHeight">Height of the screen.</param>
        public void CreateProjectionMatrix(OpenGL gl, float screenWidth, float screenHeight)
        {
            //  Create the projection matrix for our screen size.
            const float S = 0.46f;
            float H = S * screenHeight / screenWidth;
            projectionMatrix = glm.pfrustum(-S, S, -H, H, 1, 100);

            //  When we do immediate mode drawing, OpenGL needs to know what our projection matrix
            //  is, so set it now.
            gl.MatrixMode(OpenGL.GL_PROJECTION);
            gl.LoadIdentity();
            gl.MultMatrix(projectionMatrix.to_array());
            gl.MatrixMode(OpenGL.GL_MODELVIEW);
        }
Пример #11
0
        /// <summary>
        /// Concatenates every value in this matrix with it's corresponding value in the other one.
        /// </summary>
        /// <param name="m">This matrix</param>
        /// <param name="m2">Other matrix</param>
        /// <returns>The concatenated result.</returns>
        public static mat4 Concat(this mat4 m, mat4 m2)
        {
            vec4[] vecs = new vec4[4];

            for (int i = 0; i < vecs.Length; i++)
            {
                vecs[i] = new vec4();
                for (int j = 0; j < vecs.Length; j++)
                {
                    vecs[i][j] = m[i][j] + m2[i][j];
                }
            }

            return new mat4(vecs);
        }
Пример #12
0
        /// <summary>
        /// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite.
        /// </summary>
        /// <param name="fovy">The fovy.</param>
        /// <param name="aspect">The aspect.</param>
        /// <param name="zNear">The z near.</param>
        /// <returns></returns>
        public static mat4 infinitePerspective(float fovy, float aspect, float zNear)
        {
            float range = tan(fovy/(2f))*zNear;

            float left = -range*aspect;
            float right = range*aspect;
            float bottom = -range;
            float top = range;

            var result = new mat4(0);
            result[0, 0] = ((2f)*zNear)/(right - left);
            result[1, 1] = ((2f)*zNear)/(top - bottom);
            result[2, 2] = - (1f);
            result[2, 3] = - (1f);
            result[3, 2] = - (2f)*zNear;
            return result;
        }
Пример #13
0
        public void RenderBeforeChildren(RenderEventArgs arg)
        {
            RenderMethod  method     = this.RenderUnit.Methods[0];
            ShaderProgram program    = method.Program;
            ICamera       camera     = arg.Camera;
            mat4          projection = camera.GetProjectionMatrix();
            mat4          view       = camera.GetViewMatrix();
            mat4          model      = this.GetModelMatrix();
            mat4          normal     = glm.transpose(glm.inverse(view * model));

            program.SetUniform(projectionMatrix, projection);
            program.SetUniform(viewMatrix, view);
            program.SetUniform(modelMatrix, model);
            program.SetUniform(normalMatrix, normal);
            program.SetUniform(lightPosition, new vec3(view * new vec4(this.light.Position, 1.0f)));
            program.SetUniform(lightColor, this.light.Diffuse);

            method.Render();
        }
Пример #14
0
        public void RenderBeforeChildren(RenderEventArgs arg)
        {
            if (!this.IsInitialized)
            {
                this.Initialize();
            }

            var  camera = arg.Camera;
            mat4 p      = camera.GetProjectionMatrix();
            mat4 v      = camera.GetViewMatrix();
            mat4 m      = this.GetModelMatrix();

            var method  = this.RenderUnit.Methods[0];
            var program = method.Program;

            program.SetUniform("MVP", p * v * m);

            method.Render();
        }
Пример #15
0
        public void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ)
        {
            float[] forward  = new float[4];
            float[] up       = new float[4];
            float[] left     = new float[4];
            float[] position = new float[4];
            float   invLength;

            forward[0] = posX - targetX;    // x
            forward[1] = posY - targetY;    // y
            forward[2] = posZ - targetZ;    // z
            forward[3] = 0.0f;              // w

            // Нормализация
            invLength   = 1.0f / (float)Math.Sqrt(forward[0] * forward[0] + forward[1] * forward[1] + forward[2] * forward[2]);
            forward[0] *= invLength;
            forward[1] *= invLength;
            forward[2] *= invLength;

            up[0] = 0.0f;                                      // x
            up[1] = 1.0f;                                      // y
            up[2] = 0.0f;                                      // z
            up[3] = 0.0f;                                      // w

            left[0] = up[1] * forward[2] - up[2] * forward[1]; // x
            left[1] = up[2] * forward[0] - up[0] * forward[2]; // y
            left[2] = up[0] * forward[1] - up[1] * forward[0]; // z
            left[3] = 1.0f;                                    // w

            // Вычисление ортогонального вектора
            up[0] = forward[1] * left[2] - forward[2] * left[1]; // x
            up[1] = forward[2] * left[0] - forward[0] * left[2]; // y
            up[2] = forward[0] * left[1] - forward[1] * left[0]; // z
            up[3] = 0.0f;                                        // w

            // Позиция камеры
            position[0] = -posX;
            position[1] = -posY;
            position[2] = -posZ;
            position[3] = 1.0f;

            matrixView = new mat4(CreateVec4FromArray(left), CreateVec4FromArray(up), CreateVec4FromArray(forward), CreateVec4FromArray(position));
        }
Пример #16
0
        void pyramidElement_BeforeRendering(object sender, Objects.RenderEventArgs e)
        {
            rotation += 3.0f;
            mat4 modelMatrix = glm.rotate(rotation, new vec3(0, 1, 0));

            const float distance = 0.7f;

            viewMatrix = glm.lookAt(new vec3(-distance, distance, -distance), new vec3(0, 0, 0), new vec3(0, -1, 0));

            int[] viewport = new int[4];
            GL.GetInteger(GetTarget.Viewport, viewport);
            projectionMatrix = glm.perspective(60.0f, (float)viewport[2] / (float)viewport[3], 0.01f, 100.0f);

            mat4 mvp = projectionMatrix * viewMatrix * modelMatrix;

            IMVP element = sender as IMVP;

            element.SetShaderProgram(mvp);
        }
Пример #17
0
        void glCanvas1_OpenGLDraw(object sender, PaintEventArgs e)
        {
            GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

            var  arg = new RenderEventArgs(RenderModes.Render, this.camera);
            mat4 projectionMatrix = camera.GetProjectionMat4();
            mat4 viewMatrix       = camera.GetViewMat4();
            mat4 modelMatrix      = glm.rotate(rotationAngle, new vec3(0, 1, 0)); //mat4.identity();

            //mat4 mvp = projectionMatrix * viewMatrix * modelMatrix;

            this.pyramidRenderer.projectionMatrix = projectionMatrix;
            this.pyramidRenderer.viewMatrix       = viewMatrix;
            this.pyramidRenderer.modelMatrix      = modelMatrix;

            this.pyramidRenderer.Render(arg);

            this.Text = string.Format("FormModernOpenGL FPS: {0}", this.glCanvas1.FPS);
        }
Пример #18
0
        private void glCanvas1_OpenGLDraw(object sender, PaintEventArgs e)
        {
            GL.ClearColor(0x87 / 255.0f, 0xce / 255.0f, 0xeb / 255.0f, 0xff / 255.0f);
            GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

            var arg = new RenderEventArgs(RenderModes.Render, this.camera);

            {
                mat4 modelMatrix      = mat4.identity();
                mat4 viewMatrix       = this.camera.GetViewMat4();
                mat4 projectionMatrix = this.camera.GetProjectionMat4();
                element.projectionMatrix = projectionMatrix;
                element.viewMatrix       = viewMatrix;
                element.modelMatrix      = modelMatrix;
            }

            element.Render(arg);
            uiAxis.Render(arg);
        }
        void glCanvas1_OpenGLDraw(object sender, PaintEventArgs e)
        {
            mat4 projectionMatrix = camera.GetProjectionMat4();

            projectionMatrix = glm.translate(projectionMatrix, new vec3(translateX, translateY, translateZ));//
            mat4 viewMatrix  = camera.GetViewMat4();
            mat4 modelMatrix = mat4.identity();
            mat4 mvp         = projectionMatrix * viewMatrix * modelMatrix;

            pyramidElement.mvp = mvp;
            textElement.mvp    = mvp;

            GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

            var arg = new RenderEventArgs(RenderModes.Render, this.camera);

            pyramidElement.Render(arg);
            textElement.Render(arg);
        }
Пример #20
0
        public void RenderBeforeChildren(RenderEventArgs arg)
        {
            int current = this.CurrentConfig;

            if (current < 0)
            {
                current = 0;
            }
            if (current >= this.configs.Length)
            {
                current = this.configs.Length - 1;
            }
            var config = this.configs[current];

            uint inputUnit = 0, outputUnit = 1;
            {
                RenderMethod  method         = this.RenderUnit.Methods[config.computeShaderIndex];
                ShaderProgram computeProgram = method.Program;
                // Activate the compute program and bind the output texture image
                computeProgram.Bind();
                glBindImageTexture(inputUnit, this.inTexture.Id, 0, false, 0, GL.GL_READ_WRITE, GL.GL_RGBA32F);
                glBindImageTexture(outputUnit, this.outTexture.Id, 0, false, 0, GL.GL_READ_WRITE, GL.GL_RGBA32F);
                // Dispatch
                glDispatchCompute(config.groupXCount, config.gropuYCount, 1);
                glMemoryBarrier(GL.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
                computeProgram.Unbind();
            }
            {
                ICamera camera     = arg.Camera;
                mat4    projection = camera.GetProjectionMatrix();
                mat4    view       = camera.GetViewMatrix();
                mat4    model      = this.GetModelMatrix();

                var           method  = this.RenderUnit.Methods[this.configs.Length]; // the only render unit in this node.
                ShaderProgram program = method.Program;
                program.SetUniform(tex, this.outTexture);
                program.SetUniform(projectionMat, projection);
                program.SetUniform(viewMat, view);
                program.SetUniform(modelMat, model);

                method.Render();
            }
        }
Пример #21
0
        private void GeneratePositions(Assimp.Scene scene)
        {
            var lstPosition = new List <vec3>();
            var lstColor    = new List <vec3>();
            var lstNode     = new List <Assimp.Node>();

            if (scene.RootNode != null && scene.RootNode.HasChildren)
            {
                mat4 mat = scene.RootNode.Transform.ToMat4();
                foreach (Assimp.Node child in scene.RootNode.Children)
                {
                    ParseNode(child, lstPosition, lstColor, lstNode, mat);
                }
            }

            this.positions = lstPosition.ToArray();
            this.colors    = lstColor.ToArray();
            this.nodes     = lstNode.ToArray();
        }
Пример #22
0
        public override void RenderBeforeChildren(RenderEventArgs arg)
        {
            RenderUnit    unit       = this.RenderUnits[0];
            ShaderProgram program    = unit.Program;
            ICamera       camera     = arg.CameraStack.Peek();
            mat4          projection = camera.GetProjectionMatrix();
            mat4          view       = camera.GetViewMatrix();
            mat4          model      = this.GetModelMatrix();
            mat4          normal     = glm.transpose(glm.inverse(view * model));

            program.SetUniform(projectionMatrix, projection);
            program.SetUniform(viewMatrix, view);
            program.SetUniform(modelMatrix, model);
            program.SetUniform(normalMatrix, normal);
            program.SetUniform(lightPosition, new vec3(view * new vec4(light.Position, 1.0f)));
            program.SetUniform(spotDirection, new vec3(view * new vec4(-light.Position, 0.0f)));

            unit.Render();
        }
Пример #23
0
        public void RenderBeforeChildren(RenderEventArgs arg)
        {
            ICamera camera     = arg.Camera;
            mat4    projection = camera.GetProjectionMatrix();
            mat4    view       = camera.GetViewMatrix();
            mat4    model      = this.GetModelMatrix();

            var           method  = this.RenderUnit.Methods[0];
            ShaderProgram program = method.Program;

            program.SetUniform("mvpMatrix", projection * view * model);
            program.SetUniform("tex", this.texture);
            var viewport = new int[4];

            GL.Instance.GetIntegerv((uint)GetTarget.Viewport, viewport);
            program.SetUniform("screenWidth", (float)viewport[2]);
            program.SetUniform("screenHeight", (float)viewport[3]);
            method.Render();
        }
Пример #24
0
        /// <summary>
        /// Handles the OpenGLInitialized event of the openGLControl1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void openGLControl1_OpenGLInitialized(object sender, EventArgs e)
        {
            //  Get the OpenGL object.
            OpenGL gl = openGLControl1.OpenGL;

            //  Set the clear color.
            gl.ClearColor(0, 0, 0, 0);

            //  Create a perspective projection matrix.
            const float rads = (60.0f / 360.0f) * (float)Math.PI * 2.0f;

            projectionMatrix = glm.perspective(rads, Width / Height, 0.1f, 100.0f);

            //  Create a view matrix to move us back a bit.
            viewMatrix = glm.translate(new mat4(1.0f), new vec3(0.0f, 0.0f, -5.0f));

            cube.Initialise(gl);
            tube.Initialise(gl);
        }
Пример #25
0
 public void Rotate(KeyCode code)
 {
     if (code == KeyCode.Left)
     {
         _model = glm.rotate(_model, glm.radians(20), new vec3(0.0f, 1.0f, 0.0f));
     }
     if (code == KeyCode.Right)
     {
         _model = glm.rotate(_model, glm.radians(-20), new vec3(0.0f, 1.0f, 0.0f));
     }
     if (code == KeyCode.Up)
     {
         _model = glm.rotate(_model, glm.radians(20), new vec3(1.0f, 0.0f, 0.0f));
     }
     if (code == KeyCode.Down)
     {
         _model = glm.rotate(_model, glm.radians(-20), new vec3(1.0f, 0.0f, 0.0f));
     }
 }
Пример #26
0
        /// <summary>
        /// Slightly edited formula!
        /// </summary>
        public void BuildPerspectiveProjection()
        {
            var a = Height / Width;
            var n = Near;
            var f = Far;
            var e = 1 / (float)Math.Tan(FovRadians / 2);


            var mat = new mat4(
                new vec4[]
            {
                new vec4(e, 0, 0, 0),
                new vec4(0, e / a, 0, 0),
                new vec4(0, 0, -(2 * f * n) / (f - n), -1),
                new vec4(0, 0, -(f + n) / (f - n), 0),
            });

            ProjectionMatrix = mat;
        }
Пример #27
0
        public void ExtrudeShadow(ShadowVolumeExtrudeEventArgs arg)
        {
            ICamera camera     = arg.Camera;
            mat4    projection = camera.GetProjectionMatrix();
            mat4    view       = camera.GetViewMatrix();
            mat4    model      = this.GetModelMatrix();

            var           method  = this.RenderUnit.Methods[(int)MethodName.extrudeShadow];
            ShaderProgram program = method.Program;

            program.SetUniform("vpMat", projection * view);
            program.SetUniform("modelMat", model);
            if (arg.Light is DirectionalLight)
            {
                var light = arg.Light as DirectionalLight;
                program.SetUniform("lightPosition", light.Direction);
                program.SetUniform("farAway", true);
            }
            else
            {
                program.SetUniform("lightPosition", arg.Light.Position);
                program.SetUniform("farAway", false);
            }

            // light info.
            directionalLight.SetBlinnPhongUniforms(program);
            // material.
            program.SetUniform("material.diffuse", new vec3(1, 0, 0));  //this.Color);
            program.SetUniform("material.specular", new vec3(1, 0, 0)); //this.Color);
            program.SetUniform("material.shiness", this.Shiness);

            fillFarOffsetSwitch.On();
            program.SetUniform("wireframe", false);
            method.Render();
            fillFarOffsetSwitch.Off();

            polygonModeSwitch.On();
            lineWidthSwitch.On();
            program.SetUniform("wireframe", true);
            method.Render();
            lineWidthSwitch.Off();
            polygonModeSwitch.Off();
        }
Пример #28
0
        /// <summary>
        /// Creates the Inverse of the matrix.
        /// </summary>
        /// <param name="mat">A 4x4 matrix.</param>
        /// <returns>The inversed matrix.</returns>
        public static mat4 Inverse(this mat4 a)
        {
            int n = 4;

            float[][] arrA = new float[n][];
            float[][] arrInverse;
            mat4      inverse = mat4.identity();

            for (int i = 0; i < n; i++)
            {
                arrA[i] = new float[n];
                for (int j = 0; j < n; j++)
                {
                    arrA[i][j] = a[j][i];
                }
            }

            var d = Determinant(arrA, n);

            if (d != 0)
            {
                arrInverse = Cofactor(arrA, n);

                //float[][] to mat4
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        inverse[i, j] = arrInverse[i][j];
                    }
                }

                //test if result == I
                var res = a * inverse;


                return(inverse);
            }
            else
            {
                throw new Exception("Matrix can't be inverted, determinant == 0.");
            }
        }
Пример #29
0
        protected void BeforeRendering(OpenGL gl, RenderMode renderMode)
        {
            IScientificCamera camera = this.camera;

            if (camera != null)
            {
                if (camera.CameraType == CameraTypes.Perspecitive)
                {
                    IPerspectiveViewCamera perspective = camera;
                    this.projectionMatrix = perspective.GetProjectionMat4();
                    this.viewMatrix       = perspective.GetViewMat4();
                }
                else if (camera.CameraType == CameraTypes.Ortho)
                {
                    IOrthoViewCamera ortho = camera;
                    this.projectionMatrix = ortho.GetProjectionMat4();
                    this.viewMatrix       = ortho.GetViewMat4();
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            gl.Enable(OpenGL.GL_TEXTURE_2D);
            this.texture.Bind(gl);

            modelMatrix = glm.scale(mat4.identity(), new vec3(1, 1, this.ZAxisScale));
            ShaderProgram shaderProgram = this.shaderProgram;

            //  Bind the shader, set the matrices.
            shaderProgram.Bind(gl);
            shaderProgram.SetUniformMatrix4(gl, "projectionMatrix", projectionMatrix.to_array());
            shaderProgram.SetUniformMatrix4(gl, "viewMatrix", viewMatrix.to_array());
            shaderProgram.SetUniformMatrix4(gl, "modelMatrix", modelMatrix.to_array());

            shaderProgram.SetUniform1(gl, "tex", this.texture.TextureName);
            shaderProgram.SetUniform1(gl, "brightness", this.Brightness);
            shaderProgram.SetUniform1(gl, "opacity", this.Opacity);

            gl.Enable(OpenGL.GL_POLYGON_SMOOTH);
            gl.Hint(OpenGL.GL_POLYGON_SMOOTH_HINT, OpenGL.GL_NICEST);
        }
Пример #30
0
        protected override void DoRender(RenderEventArgs arg)
        {
            mat4 projection = arg.Camera.GetProjectionMatrix();
            mat4 view       = arg.Camera.GetViewMatrix();

            this.SetUniform("projectionMatrix", projection);
            this.SetUniform("viewMatrix", view);
            MarkableStruct <mat4> model = this.GetModelMatrix();

            if (this.modelTicks != model.UpdateTicks)
            {
                this.SetUniform("modelMatrix", model.Value);
                this.modelTicks = model.UpdateTicks;
            }

            //this.glUniform("uniformColor", this.uniformColor);

            base.DoRender(arg);
        }
Пример #31
0
        protected override void DoRender(RenderEventArgs arg)
        {
            this.SetUniform("ambientLight", this.AmbientLightColor);
            this.SetUniform("directionalLightColor", this.DirectionalLightColor);
            this.SetUniform("directionalLightDirection", this.DirectionalLightDirection.normalize());
            this.SetUniform("halfVector", this.DirectionalLightDirection.normalize());
            //this.SetUniform("halfVector", this.HalfVector.normalize());
            this.SetUniform("shininess", this.Shininess);
            this.SetUniform("strength", this.Strength);

            mat4 projection = arg.Camera.GetProjectionMatrix();
            mat4 view       = arg.Camera.GetViewMatrix();
            mat4 model      = this.GetModelMatrix().Value;

            this.SetUniform("mvpMatrix", projection * view * model);
            this.SetUniform("normalMatrix", glm.transpose(glm.inverse(model)).to_mat3());

            base.DoRender(arg);
        }
Пример #32
0
        private void glCanvas1_OpenGLDraw(object sender, PaintEventArgs e)
        {
            OpenGL.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT | OpenGL.GL_STENCIL_BUFFER_BIT);

            RenderEventArgs arg = new RenderEventArgs(RenderModes.Render, this.glCanvas1.ClientRectangle, this.camera);

            {
                mat4 projection        = arg.Camera.GetProjectionMat4();
                mat4 view              = arg.Camera.GetViewMat4();
                vec4 translationColumn = view[3];
                translationColumn.x += this.position.x;
                translationColumn.y += this.position.y;
                translationColumn.z += this.position.z;
                view[3]              = translationColumn;
                mat4 model = glm.scale(mat4.identity(), new vec3(0.3f, 0.3f, 0.3f));
                this.cubeRenderer.SetUniform("projectionMatrix", projection);
                this.cubeRenderer.SetUniform("viewMatrix", view);
                this.cubeRenderer.SetUniform("modelMatrix", model);
                this.cubeRenderer.Render(arg);
            }
            {
                mat4 projection = arg.Camera.GetProjectionMat4();
                mat4 view       = arg.Camera.GetViewMat4();
                mat4 model      = mat4.identity();
                this.billboardRenderer.SetUniform("CameraRight_worldspace", new vec3(
                                                      view[0][0], view[1][0], view[2][0]));
                this.billboardRenderer.SetUniform("CameraUp_worldspace", new vec3(
                                                      view[0][1], view[1][1], view[2][1]));
                this.billboardRenderer.SetUniform("BillboardPos", new vec3(
                                                      (float)Math.Cos(currentTime), 1f, (float)Math.Sin(currentTime)));
                this.billboardRenderer.SetUniform("BillboardSize", new vec2(1.0f, 0.125f));
                float lifeLevel = (float)(Math.Sin(currentTime) * 0.4 + 0.5); currentTime += 0.1f;
                this.billboardRenderer.SetUniform("LifeLevel", lifeLevel);
                this.billboardRenderer.SetUniform("VP", projection * view);
                this.billboardRenderer.Render(arg);
            }
            UIRenderersDraw(arg);

            // Cross cursor shows where the mouse is.
            OpenGL.DrawText(this.lastMousePosition.X - offset.X,
                            this.glCanvas1.Height - (this.lastMousePosition.Y + offset.Y) - 1,
                            Color.Red, "Courier New", crossCursorSize, "o");
        }
Пример #33
0
        void control_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseDownFlag && ((e.Button & this.lastBindingMouseButtons) != MouseButtons.None))
            {
                this._endPosition = GetArcBallPosition(e.X, e.Y);
                var cosAngle = _startPosition.dot(_endPosition) / (_startPosition.length() * _endPosition.length());
                if (cosAngle > 1.0f)
                {
                    cosAngle = 1.0f;
                }
                else if (cosAngle < -1)
                {
                    cosAngle = -1.0f;
                }

                var angle = MouseSensitivity * (float)(Math.Acos(cosAngle) / Math.PI * 180);
                _normalVector = _startPosition.cross(_endPosition).normalize();
                if (!
                    ((_normalVector.x == 0 && _normalVector.y == 0 && _normalVector.z == 0) ||
                     float.IsNaN(_normalVector.x) || float.IsNaN(_normalVector.y) || float.IsNaN(_normalVector.z)))
                {
                    _startPosition = _endPosition;

                    mat4 newRotation = glm.rotate(angle, _normalVector);
                    this.finalMat = newRotation * finalMat;
                    callBackAction(this.finalMat);

                    //控制台瞄一眼
                    float[]       debugA = this.finalMat.to_array();
                    StringBuilder sb     = new StringBuilder();
                    sb.Append("finalMat[");
                    for (int i = 0; i < 16; i++)
                    {
                        sb.Append($"{debugA[i]} ,");
                        if ((i + 1) % 4 == 0)
                        {
                            sb.Append("\n");
                        }
                    }
                }
            }
        }
Пример #34
0
        public md2LOL(string fileName)
        {
            AnimationSpeed = 0.001f;
            animlist       = new List <anim_t>();
            anim_t a1 = new anim_t();

            a1.first_frame = 0; a1.last_frame = 30; a1.fps = 30;
            animlist.Add(a1);
            a1             = new anim_t();
            a1.first_frame = 31; a1.last_frame = 60; a1.fps = 30;
            animlist.Add(a1);
            a1             = new anim_t();
            a1.first_frame = 61; a1.last_frame = 90; a1.fps = 30;
            animlist.Add(a1);
            a1             = new anim_t();
            a1.first_frame = 91; a1.last_frame = 120; a1.fps = 30;
            animlist.Add(a1);
            a1             = new anim_t();
            a1.first_frame = 121; a1.last_frame = 150; a1.fps = 30;
            animlist.Add(a1);
            a1             = new anim_t();
            a1.first_frame = 151; a1.last_frame = 178; a1.fps = 30;
            animlist.Add(a1);
            a1             = new anim_t();
            a1.first_frame = 181; a1.last_frame = 210; a1.fps = 30;
            animlist.Add(a1);

            LOLMD2AnimationNames = new List <string>();
            LOLMD2AnimationNames.Add("Stand");
            LOLMD2AnimationNames.Add("Attack1");
            LOLMD2AnimationNames.Add("Attack2");
            LOLMD2AnimationNames.Add("Run");
            LOLMD2AnimationNames.Add("Death");
            LOLMD2AnimationNames.Add("Spell1");
            LOLMD2AnimationNames.Add("Spell2");

            TranslationMatrix = new mat4(1);
            rotationMatrix    = new mat4(1);
            scaleMatrix       = new mat4(1);

            LoadModel(fileName);
        }
Пример #35
0
        internal void Draw()
        {
            if (!CycleMode)
            {
                return;
            }
            if (Cycle.Count == 0)
            {
                throw new ApplicationException("Skybox cycle is empty.");
            }

            var gl     = XEngineContext.Graphics;
            var shader = XEngineContext.SkyboxShader;
            var scene  = SceneManager.CurrentScene;
            var camera = scene.MainCamera;

            transform = camera.WorldToView.copy_to(transform);
            transform = quaternion.euler(transform, 0.0f, Rotation, 0.0f);
            transform.serialize(transform_cache);
            transform_cache[12] = transform_cache[13] = transform_cache[14] = 0.0f;

            shader.Use();

            gl.UniformMatrix4(shader.Project, 1, false, camera.ViewToProjectData);
            gl.UniformMatrix4(shader.View, 1, false, transform_cache);
            shader.SetScalar("scale", Scale);
            shader.SetScalar("transition", Transition);

            var sky1 = Cycle.Peek();
            var sky2 = Cycle.Count == 1 ? sky1 : Cycle.Second();

            sky1.texture.Activate(0u);
            sky2.texture.Activate(1u);

            shader.SetVec4("sky1_color", sky1.SkyColor.r, sky1.SkyColor.g, sky1.SkyColor.b, sky1.SkyColor.a);
            shader.SetScalar("sky1_map", 0);
            shader.SetVec4("sky2_color", sky2.SkyColor.r, sky2.SkyColor.g, sky2.SkyColor.b, sky2.SkyColor.a);
            shader.SetScalar("sky2_map", 1);

            Skybox.mesh.Activate();
            gl.DrawArrays(OpenGL.GL_TRIANGLES, 0, Skybox.SkyboxShape.Geometry.VertexCount);
        }
Пример #36
0
        void axisElement2_BeforeRendering(object sender, Objects.RenderEventArgs e)
        {
            AxisElement2 element = sender as AxisElement2;

            mat4 projectionMatrix = camera.GetProjectionMat4();

            projectionMatrix = glm.translate(projectionMatrix, new vec3(translateX, translateY, translateZ));//

            mat4 viewMatrix = camera.GetViewMat4();

            mat4 modelMatrix = mat4.identity();

            ShaderProgram shaderProgram = element.shaderProgram;

            shaderProgram.Bind();

            shaderProgram.SetUniformMatrix4(AxisElement2.strprojectionMatrix, projectionMatrix.to_array());
            shaderProgram.SetUniformMatrix4(AxisElement2.strviewMatrix, viewMatrix.to_array());
            shaderProgram.SetUniformMatrix4(AxisElement2.strmodelMatrix, modelMatrix.to_array());
        }
Пример #37
0
        public void render(mat4 viewProjection)
        {
            if (!initialized)
            {
                return;
            }
            if (_verticesCount == 0)
            {
                return;
            }

            mat4 mvp = viewProjection * _model;

            ToolBox.gl.UniformMatrix4(3, 1, false, mvp.ToArray());

            ToolBox.gl.BindVertexArray(_vaoID);
            ToolBox.gl.DrawArrays(GL_TRIANGLES, 0, _verticesCount);
//			This unbind is unnecessary
//			ToolBox.gl.BindVertexArray(0);
        }
Пример #38
0
        public override void RenderBeforeChildren(CSharpGL.RenderEventArgs arg)
        {
            if (!this.IsInitialized)
            {
                this.Initialize();
            }

            ICamera camera           = arg.CameraStack.Peek();
            mat4    projectionMatrix = camera.GetProjectionMatrix();
            mat4    viewMatrix       = camera.GetViewMatrix();
            mat4    modelMatrix      = this.GetModelMatrix();

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

            program.SetUniform(mvpMatrix, projectionMatrix * viewMatrix * modelMatrix);
            program.SetUniform(skybox, this.texture);

            method.Render();
        }
Пример #39
0
        protected override void DoRender(RenderEventArgs e)
        {
            mat4 projectionMatrix, viewMatrix, modelMatrix;

            {
                IUILayout element = this as IUILayout;
                element.GetMatrix(out projectionMatrix, out viewMatrix, out modelMatrix, e.Camera);
            }

            this.mvp = projectionMatrix * viewMatrix * modelMatrix;
            this.shaderProgram.Bind();
            this.shaderProgram.SetUniformMatrix4(strMVP, mvp.to_array());

            GL.BindVertexArray(vao[0]);

            GL.DrawArrays(this.axisPrimitiveMode, 0, this.axisVertexCount);

            GL.BindVertexArray(0);
            this.shaderProgram.Unbind();
        }
Пример #40
0
        /// <summary>
        /// Puts the values from the matrix in a readable 4 line string, where each line defines 1 vector.
        /// BEWARE: if m contains null vectors, it will throw an exception. This exception is being caught here, but this might create performance issues.
        /// If exception is caught, this method will return an empty string( = "").
        /// </summary>
        /// <param name="m">The matrix.</param>
        /// <param name="round">Used for calling Math.Round(m[i][j], round)</param>
        /// <returns>A readable 4 line string, where each line defines 1 vector </returns>
        public static string ToValueString(this mat4 m, int round = 3)
        {
            var txt = "";

            try
            {
                for (int i = 0; i < 4; i++)
                {
                    var arr = m.to_array();
                    var mi  = m[i];
                    txt += mi.ToValueString(round);
                    txt += "\n";
                }
            }
            catch (Exception)
            {
                txt = "";
            }
            return(txt);
        }
        protected override void DoRender(RenderEventArgs arg)
        {
            // setup uniforms
            var   now  = DateTime.Now;
            float time = (float)now.Subtract(this.lastTime).TotalMilliseconds * 0.001f;

            this.SetUniform("time", time * timeElapsingSpeed);
            this.SetUniform("rainDrop", this.rainDrop);
            this.SetUniform("granularity", this.granularity);

            mat4 projection = arg.Camera.GetProjectionMat4();
            mat4 view       = arg.Camera.GetViewMat4();
            mat4 model      = mat4.identity();

            this.SetUniform("projectionMatrix", projection);
            this.SetUniform("viewMatrix", view);
            this.SetUniform("modelMatrix", model);

            base.DoRender(arg);
        }
Пример #42
0
        private void glCanvas1_OpenGLDraw(object sender, PaintEventArgs e)
        {
            OpenGL.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT | OpenGL.GL_STENCIL_BUFFER_BIT);

            RenderEventArgs       arg      = new RenderEventArgs(RenderModes.Render, this.glCanvas1.ClientRectangle, this.camera);
            RaycastVolumeRenderer renderer = this.renderer;

            if (renderer != null)
            {
                mat4 mvp = arg.Camera.GetProjectionMat4() * arg.Camera.GetViewMat4();
                renderer.SetMVP(mvp);

                renderer.Render(arg);
            }

            // Cross cursor shows where the mouse is.
            OpenGL.DrawText(this.lastMousePosition.X - offset.X,
                            this.glCanvas1.Height - (this.lastMousePosition.Y + offset.Y) - 1,
                            Color.Red, "Courier New", crossCursorSize, "o");
        }
Пример #43
0
        /// <summary>
        /// Build a look at view matrix.
        /// </summary>
        /// <param name="eye">The eye.</param>
        /// <param name="center">The center.</param>
        /// <param name="up">Up.</param>
        /// <returns></returns>
        public static mat4 lookAt(vec3 eye, vec3 center, vec3 up)
        {
            vec3 f = new vec3(normalize(center - eye));
            vec3 s = new vec3(normalize(cross(f, up)));
            vec3 u = new vec3(cross(s, f));

            mat4 Result = new mat4(1);
            Result[0, 0] = s.x;
            Result[1, 0] = s.y;
            Result[2, 0] = s.z;
            Result[0, 1] = u.x;
            Result[1, 1] = u.y;
            Result[2, 1] = u.z;
            Result[0, 2] = -f.x;
            Result[1, 2] = -f.y;
            Result[2, 2] = -f.z;
            Result[3, 0] = -dot(s, eye);
            Result[3, 1] = -dot(u, eye);
            Result[3, 2] = dot(f, eye);
            return Result;
        }
        public static void ApplyTransArrayParameters(OpenGL gl, ExtShaderProgram esp, mat4[] mats)
        {
            var prms = esp.Parameters as ITransformableParameters;
            var p = esp.Program;

            // Set the transformation matrix.
            if (prms.TransformationMatrixId != null)
            {
                var m = new float[mats.Length][];

                for (int i = 0; i < mats.Length; i++)
                {
                    var mat = mats[i];
                    m[i] = new float[16];
                    m[i] = mat.to_array();
                }

                throw new NotImplementedException();
                //p.set
                //p.SetUniformMatrix4(gl, prms.TransformationMatrixId, m);
            }
        }
Пример #45
0
        /// <summary>
        /// Multiplies a 4x1 vector with a 4x4 transformation matrix.
        /// </summary>
        /// <param name="vec">The 4x1 vector.</param>
        /// <param name="mat">The 4x4 matrix.</param>
        /// <returns></returns>
        public static vec4 Multiply(this vec4 vec, mat4 mat)
        {
            var pos = new vec4();
            for (int i = 0; i < 4; i++)
            {
                float newPosVal = 0.0f;
                for (int j = 0; j < 4; j++)
                {
                    newPosVal += vec[j] * mat[j][i];
                }
                pos[i] = newPosVal;
            }

            return pos;
        }
Пример #46
0
 /// <summary>
 /// Gets the transposed matrix.
 /// <para>获取转置矩阵。</para>
 /// </summary>
 /// <param name="m"></param>
 /// <returns></returns>
 public static mat4 transpose(mat4 m)
 {
     vec4 col0 = m.col0;
     vec4 col1 = m.col1;
     vec4 col2 = m.col2;
     vec4 col3 = m.col3;
     return new mat4(
         new vec4(col0.x, col1.x, col2.x, col3.x),
         new vec4(col0.y, col1.y, col2.y, col3.y),
         new vec4(col0.z, col1.z, col2.z, col3.z),
         new vec4(col0.w, col1.w, col2.w, col3.w)
         );
 }
 /// <summary>
 /// Multiply matrix x by matrix y component-wise, i.e., result[i][j] is the scalar product of x[i][j] and y[i][j].
 /// Note: to get linear algebraic matrix multiplication, use the multiply operator (*).
 /// </summary>
 protected mat4 matrixCompMult(mat4 x, mat4 y)
 {
     throw _invalidAccess;
 }
 /// <summary>Returns the determinant of m. </summary>
 protected float determinant(mat4 m)
 {
     throw _invalidAccess;
 }
 /// <summary>
 /// Returns a matrix that is the transpose of m. 
 /// The input matrix m is not modified.
 /// </summary>
 protected mat4 transpose(mat4 m)
 {
     throw _invalidAccess;
 }
Пример #50
0
 void overlayControl_Resized(object sender, EventArgs e)
 {
   var gl = overlayControl.OpenGL;
   float top = 0f;
   float bottom = (float)overlayControl.Height;
   float left = 0f;
   float right = (float)overlayControl.Width;
   float far = 10f;
   float near = -10f;
   var col1 = new vec4(2 / (right - left), 0, 0, 0);
   var col2 = new vec4(0, 2 / (top - bottom), 0, 0);
   var col3 = new vec4(0, 0, -(2 / (far - near)), 0);
   var col4 = new vec4(-((right + left) / (right - left)), -((top + bottom) / (top - bottom)), (far + near) / (far - near), 1);
   projectionMatrix = new mat4(new vec4[] { col1, col2, col3, col4 });
 }
        public void BuildTurntableModelview(vec3 originPoint = new vec3())
        {
            var cosX = (float)Math.Cos(AngleX);
            var cosY = (float)Math.Cos(AngleY);
            var cosZ = (float)Math.Cos(AngleZ);
            var sinX = (float)Math.Sin(AngleX);
            var sinY = (float)Math.Sin(AngleY);
            var sinZ = (float)Math.Sin(AngleZ);

            mat4 rotX = new mat4(
                new vec4[]
                {
                    new vec4(1,0,0,0),
                    new vec4(0, cosX, -sinX, 0),
                    new vec4(0, sinX, cosX, 0),
                    new vec4(0,0,0,1)
                });
            mat4 rotY = new mat4(
                new vec4[]
                {
                    new vec4(cosY, 0, sinY, 0),
                    new vec4(0, 1, 0,0),
                    new vec4(-sinY, 0, cosY, 0),
                    new vec4(0,0,0,1)
                });

            var rotation = rotX * rotY;
            var translation = rotation * glm.translate(mat4.identity(), new vec3(TranslationX + originPoint.x, TranslationY + originPoint.y, TranslationZ + originPoint.z));
            var translation2 = glm.translate(translation, new vec3(-originPoint.x, -originPoint.y, -originPoint.z));

            ModelviewMatrix = translation2;
        }
Пример #52
0
        protected void BeforeRendering(OpenGL gl, RenderMode renderMode)
        {
            IScientificCamera camera = this.camera;
            if (camera != null)
            {
                if (camera.CameraType == CameraTypes.Perspecitive)
                {
                    IPerspectiveViewCamera perspective = camera;
                    this.projectionMatrix = perspective.GetProjectionMat4();
                    this.viewMatrix = perspective.GetViewMat4();
                }
                else if (camera.CameraType == CameraTypes.Ortho)
                {
                    IOrthoViewCamera ortho = camera;
                    this.projectionMatrix = ortho.GetProjectionMat4();
                    this.viewMatrix = ortho.GetViewMat4();
                }
                else
                { throw new NotImplementedException(); }
            }

            gl.Enable(OpenGL.GL_TEXTURE_2D);
            this.texture.Bind(gl);

            modelMatrix = glm.scale(mat4.identity(), new vec3(1, 1, this.ZAxisScale));
            ShaderProgram shaderProgram = this.shaderProgram;
            //  Bind the shader, set the matrices.
            shaderProgram.Bind(gl);
            shaderProgram.SetUniformMatrix4(gl, "projectionMatrix", projectionMatrix.to_array());
            shaderProgram.SetUniformMatrix4(gl, "viewMatrix", viewMatrix.to_array());
            shaderProgram.SetUniformMatrix4(gl, "modelMatrix", modelMatrix.to_array());

            shaderProgram.SetUniform1(gl, "tex", this.texture.TextureName);
            shaderProgram.SetUniform1(gl, "brightness", this.Brightness);
            shaderProgram.SetUniform1(gl, "opacity", this.Opacity);

            gl.Enable(OpenGL.GL_POLYGON_SMOOTH);
            gl.Hint(OpenGL.GL_POLYGON_SMOOTH_HINT, OpenGL.GL_NICEST);
        }
        void CreateAndDrawGrid(OpenGL GL)
        {
            // Debug.WriteLine("Painting Begins..");

            // Create vertices for 4 lines that will split the figure into 3 equal sections
            xgrid = new vec3[(C_NUM_Y_DIV + 1) * 2];
            for (int i = 0; i < (C_NUM_Y_DIV + 1) * 2; i = i + 2)
            {
                xgrid[i].x = -1f; xgrid[i + 1].x = 1f;
                xgrid[i].y = C_X_MARGIN_MIN + C_Y_STEP * i / 2; xgrid[i + 1].y = C_X_MARGIN_MIN + C_Y_STEP * i / 2;
                xgrid[i].z = 0f; xgrid[i + 1].z = 0f;
            }

            coldata = new vec3[] {
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White),
                GL.Color(DR.Color.White)
            };

            mviewdata = new mat4(1.0f);

            // --------------- Implementation WITH VERTEX ARRAY OBJECTS --------------------
            ////  Create the vertex array object.
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(GL);
            vertexBufferArray.Bind(GL);

            //  Create a vertex buffer for the vertex data.
            var vertexDataBuffer = new VertexBuffer();
            vertexDataBuffer.Create(GL);
            vertexDataBuffer.Bind(GL);
            vertexDataBuffer.SetData(GL, attribute_vpos, xgrid, false, 3);

            //  Now do the same for the colour data.
            var colourDataBuffer = new VertexBuffer();
            colourDataBuffer.Create(GL);
            colourDataBuffer.Bind(GL);
            colourDataBuffer.SetData(GL, attribute_vcol, coldata, false, 3);

            //  Unbind the vertex array, we've finished specifying data for it.
            vertexBufferArray.Unbind(GL);

            //  Bind the shader, set the matrices.
            shaderProgram.Bind(GL);
            //shaderProgram.SetUniformMatrix4(gl, "projectionMatrix", projectionMatrix.to_array());
            //shaderProgram.SetUniformMatrix4(gl, "viewMatrix", viewMatrix.to_array());
            shaderProgram.SetUniformMatrix4(GL, "modelview", mviewdata.to_array());

            //  Bind the out vertex array.
            vertexBufferArray.Bind(GL);

            GL.DrawArrays(OpenGL.GL_LINES, 0, 8);

            //  Unbind our vertex array and shader.
            vertexBufferArray.Unbind(GL);
            shaderProgram.Unbind(GL);

            // --------------- Implementation WITH VERTEX ARRAY OBJECTS END --------------------
        }
Пример #54
0
        public void BufferData(OpenGL gl,
            uint[] indices, float[] vertices, float[] normals, 
            mat4[] transformations, Material[] materials)
        {
            // Use the amount of transformations to decide how many particles of this object should be drawn.
            ParticleCount = transformations.Length;
            IndicesCount = indices.Length;

            var tColSize = 4 * transformations.Length;
            var color3Size = 3 * materials.Length;
            float[] tCol1 = new float[tColSize],
                tCol2 = new float[tColSize],
                tCol3 = new float[tColSize],
                tCol4 = new float[tColSize],
                ambs = new float[color3Size],
                diffs = new float[color3Size],
                specs = new float[color3Size],
                shinis = new float[materials.Length];

            // Convert transformations to float arrays.
            var newPos = 0;
            foreach (var trans in transformations)
            {
                for (int i = 0; i < 4; i++)
                {
                    tCol1[newPos] = trans[i][0];
                    tCol2[newPos] = trans[i][1];
                    tCol3[newPos] = trans[i][2];
                    tCol4[newPos] = trans[i][3];
                    newPos++;
                }
            }

            // Convert materials to float arrays.
            newPos = 0;
            for (int i = 0; i < materials.Length; i++)
            {
                var mat = materials[i];
                for (int j = 0; j < 3; j++)
                {
                    ambs[newPos] = mat.Ambient[j+1];
                    diffs[newPos] = mat.Diffuse[j+1];
                    specs[newPos] = mat.Specular[j+1];
                    newPos++;
                }
                shinis[i] = mat.Shininess;
            }

            // Set buffer data.
            BufferData(gl, indices, vertices, normals,
                tCol1, tCol2, tCol3, tCol4,
                ambs, diffs, specs, shinis);
        }
 /// <summary>
 /// </summary>
 /// <param name="uniformName"></param>
 /// <param name="m"></param>
 public int SetUniformMatrix4(string uniformName, mat4[] m)
 {
     int location = GetUniformLocation(uniformName);
     if (location >= 0)
     {
         if (glUniformMatrix4fv == null) { glUniformMatrix4fv = OpenGL.GetDelegateFor<OpenGL.glUniformMatrix4fv>(); }
         var values = new float[m.Length * 16];
         for (int index = 0, i = 0; i < m.Length; i++)
         {
             float[] array = m[i].ToArray();
             for (int j = 0; j < 16; j++)
             {
                 values[index++] = array[j];
             }
         }
         glUniformMatrix4fv(location, m.Length / 16, false, values);
     }
     return location;
 }
Пример #56
0
    private void overlayControl_Draw(object sender, RenderEventArgs args)
    {
      if (Form.ActiveForm != null)
      {
        if (Keyboard.IsKeyDown(Key.Escape))
        {
          Application.Exit();
        }
      }
   
      var gl = overlayControl.OpenGL;
      gl.ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
      gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT | OpenGL.GL_STENCIL_BUFFER_BIT);

      if (shaderProgram == null)
      {
        return;
      }
      var curTime = DateTime.UtcNow;
      float delta = (curTime  - lastTime).Ticks / 50000.0f;
      lastTime = curTime;

      var userOffsetModel = glm.translate(mat4.identity(), new vec3(offsetX, offsetY, 0));
      var scaledModel = glm.scale(userOffsetModel, new vec3(scale, scale, 1.0f));

      modelMatrix = scaledModel;
      shaderProgram.Bind(gl);
      shaderProgram.SetUniformMatrix4(gl, "projectionMatrix", projectionMatrix.to_array());
      shaderProgram.SetUniformMatrix4(gl, "modelMatrix", modelMatrix.to_array());

      Renderable readyRenderable = null;
      if( this.ready_renderables.TryTake(out readyRenderable)){
        Debug.WriteLine("setting up : " + readyRenderable.description);
        readyRenderable.Setup(gl);
        this.active_renderables.Add(readyRenderable);
      }
     
      Renderable unloadRenderable = null;
      if (this.unload_renderables.TryTake(out unloadRenderable))
      {
        Debug.WriteLine("tearing down : " + unloadRenderable.description);
        unloadRenderable.Teardown(gl);
      }
      var sortedRenderables = this.active_renderables.OrderByDescending(x => x is RadarScan);
      foreach (var renderable in sortedRenderables)
      {
        renderable.Draw(gl);
      }
      shaderProgram.Unbind(gl);

      var now = DateTime.UtcNow;
      frameCount++;
      if ((now - startTime).TotalSeconds > 1)
      {
        // 1 second has passed. print out frames.
        //Debug.WriteLine(frameCount + " frames per second");
        startTime = now;
        frameCount = 0;
      }
    }
        /// <summary>
        /// Slightly edited formula! 
        /// </summary>
        public void BuildPerspectiveProjection()
        {
            var a = Height / Width;
            var n = Near;
            var f = Far;
            var e = 1 / (float)Math.Tan(FovRadians / 2);

            var mat = new mat4(
                new vec4[]
                {
                    new vec4(e, 0, 0, 0),
                    new vec4(0, e/a, 0, 0),
                    new vec4(0, 0, -(2*f*n)/(f-n), -1),
                    new vec4(0, 0, -(f+n)/(f-n), 0),
                });

            ProjectionMatrix = mat;
        }
Пример #58
0
 public void loadProjectionMatrix(mat4 projection)
 {
     base.loadMatrix(Locations["projectionMatrix"], projection);
 }
Пример #59
0
 public void loadTransformationMatrix(mat4 matrix)
 {
     base.loadMatrix(Locations["transformationMatrix"], matrix);
 }
Пример #60
0
 /// <summary>initialized the matrix with the upperleft part of m</summary>
 public mat4x3(mat4 m)
 {
     throw _invalidAccess;
 }