public static OpenTK.Matrix4 GLSRT(OpenTK.Vector3 pos, OpenTK.Quaternion qua, OpenTK.Vector3 scale)
 {
     OpenTK.Matrix4 t = OpenTK.Matrix4.CreateTranslation(pos);
     OpenTK.Matrix4 r = OpenTK.Matrix4.CreateFromQuaternion(qua);
     OpenTK.Matrix4 s = OpenTK.Matrix4.CreateScale(scale);
     return(s * r * t);
 }
    public static Matrix4x4 ConvertOpenTkMatrixToUnityMatrix(OpenTK.Matrix4 ret)
    {
        Matrix4x4 mat = new Matrix4x4();

        mat.m00 = ret.M11;
        mat.m01 = ret.M12;
        mat.m02 = ret.M13;
        mat.m03 = ret.M14;

        mat.m10 = ret.M21;
        mat.m11 = ret.M22;
        mat.m12 = ret.M23;
        mat.m13 = ret.M24;

        mat.m20 = ret.M31;
        mat.m21 = ret.M32;
        mat.m22 = ret.M33;
        mat.m23 = ret.M34;

        mat.m30 = ret.M41;
        mat.m31 = ret.M42;
        mat.m32 = ret.M43;
        mat.m33 = ret.M44;

        return(mat);
    }
    public static OpenTK.Matrix4 Multiply(OpenTK.Matrix4 lhs, OpenTK.Matrix4 rhs)
    {
        Matrix4x4 t1 = ConvertOpenTkMatrixToUnityMatrix(lhs);
        Matrix4x4 t2 = ConvertOpenTkMatrixToUnityMatrix(rhs);

        return(ConvertUnityMatrixToOpenTkMatrix(t1 * t2));
    }
    //      float[] ConverToFloat3(Matrix4x4 mat)
    //      {
    //          float[] ret = new float[16];
    //          ret[0] = mat.m00;
    //          ret[1] = mat.m10;
    //          ret[2] = mat.m20;
    //          ret[3] = mat.m30;
    //
    //          ret[4] = mat.m01;
    //          ret[5] = mat.m11;
    //          ret[6] = mat.m21;
    //          ret[7] = mat.m31;
    //
    //          ret[8] = mat.m02;
    //          ret[9] = mat.m12;
    //          ret[10] = mat.m22;
    //          ret[11] = mat.m32;
    //
    //          ret[12] = mat.m03;
    //          ret[13] = mat.m13;
    //          ret[14] = mat.m23;
    //          ret[15] = mat.m33;
    //
    //          return ret;
    //      }

    public static OpenTK.Matrix4 ConvertUnityMatrixToOpenTkMatrix(Matrix4x4 mat)
    {
        OpenTK.Matrix4 ret = new OpenTK.Matrix4();
        ret.M11 = mat.m00;
        ret.M12 = mat.m01;
        ret.M13 = mat.m02;
        ret.M14 = mat.m03;

        ret.M21 = mat.m10;
        ret.M22 = mat.m11;
        ret.M23 = mat.m12;
        ret.M24 = mat.m13;

        ret.M31 = mat.m20;
        ret.M32 = mat.m21;
        ret.M33 = mat.m22;
        ret.M34 = mat.m23;

        ret.M41 = mat.m30;
        ret.M42 = mat.m31;
        ret.M43 = mat.m32;
        ret.M44 = mat.m33;

        return(ret);
    }
 /// <summary>
 /// Matrix Overload for Framework Match
 /// </summary>
 public static void CreateScale(float x, float y, float z, out Matrix result)
 {
     #if SharpDX
     Matrix.Scaling(x, y, z, out result);
     #else
     Matrix.CreateScale(x, y, z, out result);
     #endif
 }
 /// <summary>
 /// Matrix Overload for Framework Match
 /// </summary>
 public static void CreateScale(float scale, out Matrix result)
 {
     #if SharpDX
     Matrix.Scaling(scale, out result);
     #else
     Matrix.CreateScale(scale, out result);
     #endif
 }
Beispiel #7
0
 public C2DGraphics()
 {
     ImgDbase = new Dictionary<String, C2DImage>();
     FontDbase = new Dictionary<string,C2DFont>();
     mNewImages = new List<C2DImage>();
     m_2dView = OpenTK.Matrix4.LookAt(new OpenTK.Vector3(0, 0, 10), new OpenTK.Vector3(0, 0, 0), new OpenTK.Vector3(0, 1, 0));
     mUserTexture = -1;
 }
Beispiel #8
0
    void DrawCube()
    {
        float[] float_zeros = new float[] { 0.0f, 0.0f, 0.0f, 0.0f };
        float[] float_ones  = new float[] { 1.0f, 1.0f, 1.0f, 1.0f };

        GL.BindFramebuffer(All.Framebuffer, m_gbuffer);
        GL.Viewport(0, 0, m_width, m_height);
        All[] draw_buffers = new All[] { All.ColorAttachment0, All.ColorAttachment1 };
        GL.DrawBuffers(2, draw_buffers);
        GL.ClearBuffer(All.Color, 0, float_zeros);
        GL.ClearBuffer(All.Color, 1, float_zeros);
        GL.ClearBuffer(All.Depth, 0, float_ones);
        //float[] black = new float[] { 0, 0, 0, 1 };
        //GL.ClearBuffer(ClearBuffer.Color, 0, black);
        //float[] ones = new float[] { 1.0f };
        //GL.ClearBuffer(ClearBuffer.Depth, 0, ones);

        GL.UseProgram(m_prePassProgram);

        const int POS_INDEX    = 0;
        const int NORMAL_INDEX = 1;
        const int POS_SIZE     = 3;
        const int NORMAL_SIZE  = 3;

        GL.VertexAttribPointer(POS_INDEX, POS_SIZE, All.Float, false, (POS_SIZE + NORMAL_SIZE) * sizeof(float), m_ptrCube);
        GL.VertexAttribPointer(NORMAL_INDEX, NORMAL_SIZE, All.Float, false, (POS_SIZE + NORMAL_SIZE) * sizeof(float), m_ptrCube + sizeof(float) * POS_SIZE);

        GL.EnableVertexAttribArray(POS_INDEX);
        GL.EnableVertexAttribArray(NORMAL_INDEX);

        float[] vEyeLight = { -100.0f, 100.0f, 100.0f };

        OpenTK.Matrix4 model      = OpenGLHelper.GLSRT(OpenTK.Vector3.One, OpenTK.Quaternion.Identity, OpenTK.Vector3.One);
        OpenTK.Matrix4 view       = OpenGLHelper.GLLookAt(new OpenTK.Vector3(10, 10, 10), OpenTK.Vector3.Zero, new OpenTK.Vector3(0, 1, 0));
        OpenTK.Matrix4 projection = OpenGLHelper.GLPerspective(60, m_width / (float)m_height, 0.1f, 100f);

        OpenTK.Matrix4 mv  = OpenGLHelper.GLVMathMultiply(view, model);
        OpenTK.Matrix4 mvp = OpenGLHelper.GLVMathMultiply(projection, mv);

        GL.Uniform3(m_locLight, 1, vEyeLight);
        GL.UniformMatrix4(m_locMVP, 1, false, OpenGLHelper.ConverToFloat(mvp));
        GL.UniformMatrix4(m_locMV, false, ref mv);

        GL.Enable(EnableCap.DepthTest);
        GL.DepthFunc(All.Lequal);
        GL.Enable(EnableCap.CullFace);

        GL.DrawElements(PrimitiveType.Triangles, m_meshData.m_index.Length, DrawElementsType.UnsignedShort, m_meshData.m_index);

        GL.DisableVertexAttribArray(POS_INDEX);
        GL.DisableVertexAttribArray(NORMAL_INDEX);

        GL.BindFramebuffer(All.Framebuffer, 0);

        GL.Disable(EnableCap.DepthTest);
        GL.Disable(EnableCap.CullFace);
    }
 /// <summary>
 /// Matrix Overload for Framework Match
 /// </summary>
 public static void CreateRotation(Vector3 axis, float angle, out Matrix result)
 {
     #if SharpDX
     Matrix.RotationAxis(ref axis, angle, out result);
     #elif OpenTK
     Matrix.CreateFromAxisAngle(axis, angle, out result);
     #else
     Matrix.CreateFromAxisAngle(ref axis, angle, out result);
     #endif
 }
Beispiel #10
0
        public void QuickTransform()
        {
            OpenTK.Matrix4 A = new OpenTK.Matrix4();
            A[0, 0] = 16; A[0, 1] = 15; A[0, 2] = 14; A[0, 3] = 13;
            A[1, 0] = 12; A[1, 1] = 11; A[1, 2] = 10; A[1, 3] = 9;
            A[2, 0] = 8;  A[2, 1] = 7;  A[2, 2] = 6;  A[2, 3] = 5;

            OpenTK.Vector3 x        = new OpenTK.Vector3(1, 5, 9);
            OpenTK.Vector3 b        = A.QuickTransform(ref x);
            OpenTK.Vector3 expected = new OpenTK.Vector3(230, 166, 102);
            Assert.IsTrue(expected == b);
        }
Beispiel #11
0
        private OpenTK.Matrix4 ReadMatrix4( )
        {
            OpenTK.Matrix4 m = new OpenTK.Matrix4
            {
                Column0 = ReadVec4( ),
                Column1 = ReadVec4( ),
                Column2 = ReadVec4( ),
                Column3 = ReadVec4( )
            };

            return(m);
        }
Beispiel #12
0
        /// <summary>
        /// Called when the user resizes the window.
        /// </summary>
        /// <param name="e">Contains the new width/height of the window.</param>
        /// <remarks>
        /// You want the OpenGL viewport to match the window. This is the place to do it!
        /// </remarks>
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);

            GL.Viewport(0, 0, Width, Height);

            double aspect_ratio = Width / (double)Height;

            OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)aspect_ratio, 1, 64);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref perspective);
        }
Beispiel #13
0
        public void TestTranspose()
        {
            float x = TK.MathHelper.Pi;
            float y = TK.MathHelper.PiOver4;

            TK.Matrix4 tkM = TK.Matrix4.CreateRotationX(x) * TK.Matrix4.CreateRotationY(y);
            Matrix3x3  m   = Matrix3x3.FromRotationX(x) * Matrix3x3.FromRotationY(y);

            tkM.Transpose();
            m.Transpose();
            TestHelper.AssertEquals(tkM, m, "Testing transpose");
        }
Beispiel #14
0
        private void RenderHandler(object sender, FrameEventArgs e)
        {
            GL.Clear(ClearBufferMask.ColorBufferBit |
                     ClearBufferMask.StencilBufferBit
                     | ClearBufferMask.DepthBufferBit);
            var lookAtMatrix = Matrix4.LookAt(Eye, CameraAt, Up);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref lookAtMatrix);
            DrawObjectsByStage();
            Context.SwapBuffers();
        }
Beispiel #15
0
 public void SetShaderProgram(ShaderProgram program)
 {
     if (program != null)
     {
         program.__linkProgram();
         __curProgramObject = program.__programObject;
         __curProgram       = program;
         if (program.__programObject != 0)
         {
             __isUsedProgram[program.__programObject] = true;
             __programDic[program.__programObject]    = program;
             __vertexBuffer.Clear();                     //FIXME:?????? clear, because __programObject in UseProgram(program.__programObject) is changed
             //__textureDic.Clear(); //FIXME:?????? clear, because __programObject in UseProgram(program.__programObject) is changed
             //GL.Clear(ClearBufferMask.DepthBufferBit); //FIXME:???
             GL.UseProgram(program.__programObject);
             foreach (int location in program.__uniformMatrix4.Keys)
             {
                 OpenTK.Matrix4 v = program.__uniformMatrix4[location];
                 GL.UniformMatrix4(location, false, ref v);
                 //	                if (program.__filename.Equals("/Application/Sample/Graphics/ShaderCatalogSample/shaders/Simple.cgx"))
                 //	                {
                 //	                    Debug.WriteLine("======================location2:" + location + " : " + v.ToString());
                 //	                }
             }
             foreach (int location in program.__uniform4.Keys)
             {
                 OpenTK.Vector4 v = program.__uniform4[location];
                 GL.Uniform4(location, v.X, v.Y, v.Z, v.W);
             }
             foreach (int location in program.__uniform3.Keys)
             {
                 OpenTK.Vector3 v = program.__uniform3[location];
                 GL.Uniform3(location, v.X, v.Y, v.Z);
             }
             foreach (int location in program.__uniform1.Keys)
             {
                 float v = program.__uniform1[location];
                 GL.Uniform1(location, v);
             }
             program.__afterUseProgram();
         }
         else
         {
             //FIXME:
         }
     }
     else
     {
         __curProgramObject = 0;                 //FIXME:
         __curProgram       = null;
     }
 }
Beispiel #16
0
        /// <summary>
        /// Reads the matrix33.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns>Matrix.</returns>
        public static Matrix ReadMatrix33(this BinaryReader reader)
        {
            Matrix identity = Matrix.Identity;

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    identity[j, i] = reader.ReadSingle();
                }
            }
            return(identity);
        }
Beispiel #17
0
        public void TestFromEulerAnglesXYZ()
        {
            float x = TK.MathHelper.Pi;
            float y = 0.0f;
            float z = TK.MathHelper.PiOver4;

            TK.Matrix4 tkM = TK.Matrix4.CreateRotationX(x) * TK.Matrix4.CreateRotationZ(z);
            Matrix3x3  m   = Matrix3x3.FromEulerAnglesXYZ(x, y, z);
            Matrix3x3  m2  = Matrix3x3.FromEulerAnglesXYZ(new Vector3D(x, y, z));

            TestHelper.AssertEquals(tkM, m, "Testing create from euler angles");
            Assert.IsTrue(m == m2, "Testing if create from euler angle as a vector is the same as floats.");
        }
Beispiel #18
0
        public void TestInverse()
        {
            float x = TK.MathHelper.PiOver6;
            float y = TK.MathHelper.Pi;

            TK.Matrix4 tkM = TK.Matrix4.CreateRotationX(x) * TK.Matrix4.CreateRotationY(y);
            Matrix3x3  m   = Matrix3x3.FromRotationX(x) * Matrix3x3.FromRotationY(y);

            tkM.Invert();
            m.Inverse();

            TestHelper.AssertEquals(tkM, m, "Testing inverse");
        }
    public static OpenTK.Matrix4 ToOpenTK(this UnityEngine.Matrix4x4 m)
    {
        var res = new OpenTK.Matrix4();

        for (int r = 0; r < 4; ++r)
        {
            for (int c = 0; c < 4; ++c)
            {
                res[r, c] = m[r, c];
            }
        }
        return(res);
    }
Beispiel #20
0
        public void TestDeterminant()
        {
            float x = TK.MathHelper.Pi;
            float y = TK.MathHelper.PiOver3;

            TK.Matrix4 tkM = TK.Matrix4.CreateRotationX(x) * TK.Matrix4.CreateRotationY(y);
            Matrix3x3  m   = Matrix3x3.FromRotationX(x) * Matrix3x3.FromRotationY(y);

            float tkDet = tkM.Determinant;
            float det   = m.Determinant();

            TestHelper.AssertEquals(tkDet, det, "Testing determinant");
        }
Beispiel #21
0
        /// <summary>
        /// Compute World Matrix Starting From Node and Reading all Parents Transformations
        /// </summary>
        /// <param name="leaf"></param>
        /// <returns></returns>
        public static Matrix GetWorldMatrixFromNode(this NiAVObject leaf)
        {
            var current     = leaf;
            var worldMatrix = Matrix.Identity;

            // For Each Parent Node
            while (current != null)
            {
                // Append Transformation To Matrix
                Matrix intermediate;

                                #if SharpDX
                Matrix.Multiply(ref worldMatrix, ref current.Rotation, out intermediate);
                worldMatrix = intermediate;

                var scale = Matrix.Scaling(current.Scale);
                Matrix.Multiply(ref worldMatrix, ref scale, out intermediate);
                worldMatrix = intermediate;

                var translate = Matrix.Translation(current.Translation.X, current.Translation.Y, current.Translation.Z);
                Matrix.Multiply(ref worldMatrix, ref translate, out intermediate);
                worldMatrix = intermediate;
                                #elif MonoGame
                Matrix.Multiply(ref worldMatrix, ref current.Rotation, out intermediate);
                worldMatrix = intermediate;

                var scale = Matrix.CreateScale(current.Scale);
                Matrix.Multiply(ref worldMatrix, ref scale, out intermediate);
                worldMatrix = intermediate;

                var translate = Matrix.CreateTranslation(current.Translation.X, current.Translation.Y, current.Translation.Z);
                Matrix.Multiply(ref worldMatrix, ref translate, out intermediate);
                worldMatrix = intermediate;
                                #else
                Matrix.Mult(ref worldMatrix, ref current.Rotation, out intermediate);
                worldMatrix = intermediate;

                var scale = Matrix.CreateScale(current.Scale);
                Matrix.Mult(ref worldMatrix, ref scale, out intermediate);
                worldMatrix = intermediate;

                var translate = Matrix.CreateTranslation(current.Translation.X, current.Translation.Y, current.Translation.Z);
                Matrix.Mult(ref worldMatrix, ref translate, out intermediate);
                worldMatrix = intermediate;
                                #endif

                current = current.Parent;
            }

            return(worldMatrix);
        }
Beispiel #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static BKE Open(string filePath)
        {
            var bke = new BKE();

            using (FileStream stream = new FileStream(filePath, FileMode.Open))
                using (StreamReader r = new StreamReader(stream))
                {
                    BKENode current = null;
                    while (!r.EndOfStream)
                    {
                        var arg = r.ReadLine().TrimStart().Split(' ');

                        if (arg[0].Contains("{"))
                        {
                            while (!r.EndOfStream)
                            {
                                arg = r.ReadLine().TrimStart().Split(' ');

                                if (arg[0].Equals("}"))
                                {
                                    break;
                                }

                                if (current != null)
                                {
                                    float frame = float.Parse(arg[0]) - 1;

                                    var matrix = new OpenTK.Matrix4(
                                        float.Parse(arg[1]), float.Parse(arg[2]), float.Parse(arg[3]), float.Parse(arg[4]),
                                        float.Parse(arg[5]), float.Parse(arg[6]), float.Parse(arg[7]), float.Parse(arg[8]),
                                        float.Parse(arg[9]), float.Parse(arg[10]), float.Parse(arg[11]), float.Parse(arg[12]),
                                        float.Parse(arg[13]), float.Parse(arg[14]), float.Parse(arg[15]), float.Parse(arg[16]));

                                    current.Keys.Add(matrix);
                                }
                            }
                        }
                        else
                        {
                            current = bke.GetCreateNode(arg[0]);
                            if (arg.Length > 1)
                            {
                                current.Parent = bke.GetCreateNode(arg[1]);
                            }
                        }
                    }
                }

            return(bke);
        }
Beispiel #23
0
    public static OpenTK.Vector4 LeftMultiply(OpenTK.Vector3 tmp, OpenTK.Matrix4 mat)
    {
        OpenTK.Vector4 vec = new OpenTK.Vector4(tmp);
        vec.W = 1;

        OpenTK.Vector4 ret = new OpenTK.Vector4();

        ret.X = vec.X * mat.M11 + vec.Y * mat.M21 + vec.Z * mat.M31 + vec.W * mat.M41;
        ret.Y = vec.X * mat.M12 + vec.Y * mat.M22 + vec.Z * mat.M32 + vec.W * mat.M42;
        ret.Z = vec.X * mat.M13 + vec.Y * mat.M23 + vec.Z * mat.M33 + vec.W * mat.M43;
        ret.W = vec.X * mat.M14 + vec.Y * mat.M24 + vec.Z * mat.M34 + vec.W * mat.M44;

        return(ret);
    }
Beispiel #24
0
    public static OpenTK.Vector4 RightMultiply(OpenTK.Matrix4 mat, OpenTK.Vector3 tmp)
    {
        OpenTK.Vector4 vec = new OpenTK.Vector4(tmp);
        vec.W = 1;

        OpenTK.Vector4 ret = new OpenTK.Vector4();

        ret.X = mat.M11 * vec.X + mat.M12 * vec.Y + mat.M13 * vec.Z + mat.M14 * vec.W;
        ret.Y = mat.M21 * vec.X + mat.M22 * vec.Y + mat.M23 * vec.Z + mat.M24 * vec.W;
        ret.Z = mat.M31 * vec.X + mat.M32 * vec.Y + mat.M33 * vec.Z + mat.M34 * vec.W;

        ret.W = mat.M41 * vec.X + mat.M42 * vec.Y + mat.M43 * vec.Z + mat.M44 * vec.W;
        return(ret);
    }
Beispiel #25
0
        private void SetupViewport()
        {
            float aspectRatio = (float)GLC_display.Width / (float)GLC_display.Height;

            GL.Viewport(0, 0, GLC_display.Width, GLC_display.Height);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();

            OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView((float)(System.Math.PI / 4f), aspectRatio, 0.01f, 2000f);
            GL.MultMatrix(ref perspective);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
        }
Beispiel #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NiAVObject" /> class.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="reader">The reader.</param>
 /// <exception cref="Exception">Cannot read BoundingBoxes yet</exception>
 public NiAVObject(NiFile file, BinaryReader reader) : base(file, reader)
 {
     if (this.File.Header.Version >= eNifVersion.VER_3_0)
     {
         this.Flags = reader.ReadUInt16();
     }
     if (this.File.Header.Version >= eNifVersion.VER_20_2_0_7 && this.File.Header.UserVersion == 11u && this.File.Header.UserVersion2 > 26u)
     {
         this.UnkownShort1 = reader.ReadUInt16();
     }
     this.Translation = reader.ReadVector3();
     this.Rotation    = reader.ReadMatrix33();
     this.Scale       = reader.ReadSingle();
     if (this.File.Header.Version <= eNifVersion.VER_4_2_2_0)
     {
         this.Velocity = reader.ReadVector3();
     }
     if (this.File.Header.Version <= eNifVersion.VER_20_2_0_7 || this.File.Header.UserVersion <= 11u)
     {
         uint num = reader.ReadUInt32();
         this.Properties = new NiRef <NiProperty> [num];
         int num2 = 0;
         while ((long)num2 < (long)((ulong)num))
         {
             this.Properties[num2] = new NiRef <NiProperty>(reader.ReadUInt32());
             num2++;
         }
     }
     if (this.File.Header.Version <= eNifVersion.VER_2_3)
     {
         this.UnkownInts1 = new uint[4];
         for (int i = 0; i < 4; i++)
         {
             this.UnkownInts1[i] = reader.ReadUInt32();
         }
         this.UnkownByte = reader.ReadByte();
     }
     if (this.File.Header.Version >= eNifVersion.VER_3_0 && this.File.Header.Version <= eNifVersion.VER_4_2_2_0)
     {
         this.HasBoundingBox = reader.ReadBoolean(Version);
         if (this.HasBoundingBox)
         {
             throw new Exception("Cannot read BoundingBoxes yet");
         }
     }
     if (this.File.Header.Version >= eNifVersion.VER_10_0_1_0)
     {
         this.CollisionObject = new NiRef <NiCollisionObject>(reader.ReadUInt32());
     }
 }
        protected override void OnLoad(EventArgs e)
        {
            var black     = new OpenTK.Vector4(0.0f, 0.0f, 0.0f, 1.0f);
            var yellow    = new OpenTK.Vector4(1.0f, 1.0f, 0.0f, 1.0f);
            var cyan      = new OpenTK.Vector4(0.0f, 1.0f, 1.0f, 1.0f);
            var white     = new OpenTK.Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            var direction = new OpenTK.Vector4(1.0f, 1.0f, 1.0f, 0.0f);

            GL.Material(MaterialFace.Front, MaterialParameter.AmbientAndDiffuse, cyan);
            GL.Material(MaterialFace.Front, MaterialParameter.Specular, white);
            GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 30f);

            GL.Light(LightName.Light0, LightParameter.Ambient, black);
            GL.Light(LightName.Light0, LightParameter.Diffuse, yellow);
            GL.Light(LightName.Light0, LightParameter.Specular, white);
            GL.Light(LightName.Light0, LightParameter.Position, direction);

            //GL.LightModel(LightModelParameter.LightModelAmbient, new float[] { 0.2f, 0.2f, 0.2f, 1.0f });
            //GL.LightModel(LightModelParameter.LightModelTwoSide, 1);
            //GL.LightModel(LightModelParameter.LightModelLocalViewer, 1);

            GL.Enable(EnableCap.Lighting);                // so the renderer considers light
            GL.Enable(EnableCap.Light0);                  // turn LIGHT0 on
            GL.Enable(EnableCap.DepthTest);               // so the renderer considers depth

            // Set the current clear color to sky blue and the current drawing color to white.
            GL.ClearColor(0.1f, 0.39f, 0.88f, 1.0f);
            GL.Color3(1.0, 1.0, 1.0);

            float aspect_ratio  = Width / (float)Height; // Aspect ratio of the screen
            float fov           = MathHelper.PiOver2;    // camera field of view
            float near_distance = 0.1f;                  // The nearest the camera can see. >= 0.1f else clips
            float far_distance  = 100.0f;                // Fartherest the camera can see

            OpenTK.Matrix4 perspective_matrix =
                OpenTK.Matrix4.CreatePerspectiveFieldOfView(fov, aspect_ratio, near_distance, far_distance);

            ////Then we tell GL to use are matrix as the new Projection matrix.
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref perspective_matrix);

            GL.Enable(EnableCap.DepthTest);            // 'Enable correct Z Drawings
            GL.DepthFunc(DepthFunction.Less);          // 'Enable correct Z Drawings
            //GL.Viewport(0, 0, Width, Height);

            GL.Enable(EnableCap.CullFace);
            GL.CullFace(CullFaceMode.Back);

            //GL.ShadeModel(ShadingModel.Smooth);  // TODO - requires vertex normals to be calulated across polys
        }
        /// <summary>
        /// Get World Matrix For NifGeometry
        /// </summary>
        /// <param name="nifGeom"></param>
        /// <param name="UnitFactor"></param>
        /// <returns></returns>
        protected static Matrix ComputeWorldMatrix(NifGeometry nifGeom, float UnitFactor)
        {
            if (nifGeom == null)
            {
                throw new ArgumentNullException("nifGeom");
            }

            // Get Translation (XY Inverted), Scale, Rotation
            Matrix translation;

            ZoneDrawingExtensions.CreateTranslation(nifGeom.X * UnitFactor, nifGeom.Y * UnitFactor, nifGeom.Z * UnitFactor, out translation);
            Matrix scale;

            ZoneDrawingExtensions.CreateScale(nifGeom.Scale * UnitFactor, out scale);
            Matrix rotation;

            ZoneDrawingExtensions.CreateRotation(new Vector3(nifGeom.RotationX, nifGeom.RotationY, nifGeom.RotationZ * -1f), nifGeom.Angle, out rotation);

            Matrix result = Matrix.Identity;

            // Flip if needed
            if (nifGeom.Flip)
            {
                Matrix flip;
                ZoneDrawingExtensions.CreateScale(-1f, 1f, 1f, out flip);
                result = flip;
            }

            Matrix intermediateResult;

            // Combine Scale, Rotation, Translation, Invertion Rotation
            ZoneDrawingExtensions.Mult(ref result, ref scale, out intermediateResult);
            result = intermediateResult;
            ZoneDrawingExtensions.Mult(ref result, ref rotation, out intermediateResult);
            result = intermediateResult;
            ZoneDrawingExtensions.Mult(ref result, ref translation, out intermediateResult);
            result = intermediateResult;
            ZoneDrawingExtensions.Mult(ref result, ref RotationMatrix, out intermediateResult);
            result = intermediateResult;

            // Combine Matrix with Parent Matrix
            if (nifGeom.RelativeTo != null)
            {
                Matrix relativeMatrix = ComputeWorldMatrix(nifGeom.RelativeTo, UnitFactor);
                ZoneDrawingExtensions.Mult(ref result, ref relativeMatrix, out intermediateResult);
                result = intermediateResult;
            }

            return(result);
        }
Beispiel #29
0
        /// <summary>
        /// Sets the viewport and projection matrix for orthographic projection.
        /// </summary>
        /// <param name="e">resize event args</param>
        protected override void OnResize(EventArgs e)
        {
            GL.Viewport(ClientRectangle);

            // Set projection matrix
            GL.MatrixMode(MatrixMode.Projection);
            OpenTK.Matrix4 ortho = OpenTK.Matrix4.CreateOrthographicOffCenter(-1, 1, -1, 1, 1, -1);
            GL.LoadMatrix(ref ortho);

            // Set selector state back to matrix mode
            GL.MatrixMode(MatrixMode.Modelview);

            base.OnResize(e);
        }
Beispiel #30
0
        public static JToken Serialize(this OpenTK.Matrix4 mat)
        {
            var res = new JArray();

            for (int r = 0; r < 4; ++r)
            {
                for (int c = 0; c < 4; ++c)
                {
                    var val = mat[r, c];
                    res.Add(val);
                }
            }

            return(res);
        }
Beispiel #31
0
        public bool UpdateUniform(String name, OpenTK.Matrix4 mat)
        {
            bool result = true;

            GL.UniformMatrix4(uniforms[name], false, ref mat);

            ErrorCode error = GL.GetError();

            if (error != ErrorCode.NoError)
            {
                result = false;
            }

            return(result);
        }
Beispiel #32
0
        public void GetProjection(out OpenTK.Matrix4 projection)
        {
            if (type == CameraType.Perspective)
            {
                float aspectRatio = (float)renderWidth / (float)renderHeight;

                Matrix4.CreatePerspectiveFieldOfView(fieldOfView,
                                                     aspectRatio, nearPlane, farPlane, out projection);
            }
            else
            {
                Matrix4.CreateOrthographic((float)renderWidth, (float)renderHeight,
                                           nearPlane, farPlane, out projection);
            }
        }
 public void SetupViewport(int w, int h)
 {
     mWidth  = w;
     mHeight = h;
     m_ortho = OpenTK.Matrix4.CreateOrthographicOffCenter(0, w, h, 0, 1, 2000);
     GL.MatrixMode(MatrixMode.Projection);
     //GL.LoadIdentity();
     GL.LoadMatrix(ref m_ortho);
     GL.MatrixMode(MatrixMode.Modelview);
     //GL.LoadIdentity();
     GL.LoadMatrix(ref m_2dView);
     GL.Disable(EnableCap.Lighting);
     GL.Disable(EnableCap.DepthTest);
     GL.CullFace(CullFaceMode.Front); // the 2d view is reverse looking
 }
 public void SetupViewport(int w, int h)
 {
     mWidth = w;
     mHeight = h;
     m_ortho = OpenTK.Matrix4.CreateOrthographicOffCenter(0, w, h, 0, 1, 2000);
     GL.MatrixMode(MatrixMode.Projection);
     //GL.LoadIdentity();
     GL.LoadMatrix(ref m_ortho);
     GL.MatrixMode(MatrixMode.Modelview);
     //GL.LoadIdentity();
     GL.LoadMatrix(ref m_2dView);
     GL.Disable(EnableCap.Lighting);
     GL.Disable(EnableCap.DepthTest);
     GL.CullFace(CullFaceMode.Front); // the 2d view is reverse looking             
 }
Beispiel #35
0
        private void SetupViewport()
        {
            int w = glControl1.Width;
            int h = glControl1.Height;

            //GL.MatrixMode(MatrixMode.Projection);
            //GL.LoadIdentity();
            //GL.Ortho(0, w, 0, h, -1, 1);
            GL.Viewport(0, 0, w, h);
            double aspect_ratio = w / (double)h;

            OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)aspect_ratio, 1, 64);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref perspective);
        }
 public void ResetDrawingRegion()
 {
     GL.Flush();
     m_ortho = OpenTK.Matrix4.CreateOrthographicOffCenter(0, mWidth, mHeight, 0, 1, 2000);
     GL.MatrixMode(MatrixMode.Projection);
     GL.LoadMatrix(ref m_ortho);
     GL.Disable(EnableCap.ScissorTest);
 }
Beispiel #37
0
 public void SetRotation(float a_fRot)
 {
     m_m4ModelMatrix = Matrix4.CreateRotationZ(a_fRot);
 }
Beispiel #38
0
 // Only computes if FOV, aspect ratio, or near/far planes have changed
 public void computeProjection()
 {
     if (m_projectionChanged)
     {
         //CreatePerspectiveFieldOfView
         m_projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView (m_verticalFov,
                          m_aspectRatio, m_nearPlane, m_farPlane);
         m_projectionChanged = false;
     }
 }
Beispiel #39
0
        private void initCommon()
        {
            // By default view is aligned with world axes
            m_view = OpenTK.Matrix4.Identity;

            m_verticalFov = MathHelper.PiOver4;
            m_aspectRatio = (float)ClientBounds.Width / ClientBounds.Height;
            m_nearPlane = 1.0f;
            m_farPlane = 1.0e5f;
            m_projectionChanged = true;
            computeProjection ();
        }
Beispiel #40
0
 public void UpdatePos(int x, int y)
 {
     m_m4ModelMatrix = Matrix4.CreateTranslation(x, y, 0);
 }
 /// <summary>
 /// Matrix Overload for Framework Match
 /// </summary>
 public static void Mult(ref Matrix left, ref Matrix right, out Matrix result)
 {
     #if OpenTK
     Matrix.Mult(ref left, ref right, out result);
     #else
     Matrix.Multiply(ref left, ref right, out result);
     #endif
 }
Beispiel #42
0
		//----------------------------------------------------------------------------
		public LandmarkTransform()
		{
			Matrix = new Matrix4();

		}
Beispiel #43
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NiAVObject" /> class.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="reader">The reader.</param>
        /// <exception cref="Exception">Cannot read BoundingBoxes yet</exception>
        public NiAVObject(NiFile file, BinaryReader reader) : base(file, reader)
		{
			if (this.File.Header.Version >= eNifVersion.VER_3_0)
			{
				this.Flags = reader.ReadUInt16();
			}
			if (this.File.Header.Version >= eNifVersion.VER_20_2_0_7 && this.File.Header.UserVersion == 11u && this.File.Header.UserVersion2 > 26u)
			{
				this.UnkownShort1 = reader.ReadUInt16();
			}
			this.Translation = reader.ReadVector3();
			this.Rotation = reader.ReadMatrix33();
			this.Scale = reader.ReadSingle();
			if (this.File.Header.Version <= eNifVersion.VER_4_2_2_0)
			{
				this.Velocity = reader.ReadVector3();
			}
			if (this.File.Header.Version <= eNifVersion.VER_20_2_0_7 || this.File.Header.UserVersion <= 11u)
			{
				uint num = reader.ReadUInt32();
				this.Properties = new NiRef<NiProperty>[num];
				int num2 = 0;
				while ((long)num2 < (long)((ulong)num))
				{
					this.Properties[num2] = new NiRef<NiProperty>(reader.ReadUInt32());
					num2++;
				}
			}
			if (this.File.Header.Version <= eNifVersion.VER_2_3)
			{
				this.UnkownInts1 = new uint[4];
				for (int i = 0; i < 4; i++)
				{
					this.UnkownInts1[i] = reader.ReadUInt32();
				}
				this.UnkownByte = reader.ReadByte();
			}
			if (this.File.Header.Version >= eNifVersion.VER_3_0 && this.File.Header.Version <= eNifVersion.VER_4_2_2_0)
			{
				this.HasBoundingBox = reader.ReadBoolean(Version);
				if (this.HasBoundingBox)
				{
					throw new Exception("Cannot read BoundingBoxes yet");
				}
			}
			if (this.File.Header.Version >= eNifVersion.VER_10_0_1_0)
			{
				this.CollisionObject = new NiRef<NiCollisionObject>(reader.ReadUInt32());
			}
		}
        private void SetupViewport()
        {
            if (!loaded)
                return;
            float aspect = 1.0f;
            try
            {
                int w = glControl1.Width;
                int h = glControl1.Height;

                GL.Viewport(0, 0, w, h); // Use all of the glControl painting area
                aspect = ((float)glControl1.Width) / ((float)glControl1.Height);

                SetAlpha(false); // start off with alpha off

                GL.Enable(EnableCap.CullFace); // enable culling of faces
                GL.CullFace(CullFaceMode.Back); // specify culling backfaces               

                m_projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView(0.55f, aspect, 1, 2000);
                m_axisProjection = OpenTK.Matrix4.CreatePerspectiveOffCenter(-2 * aspect + 0.3f, 0.3f, -0.3f, 1.7f, 1, 2000);
                m_modelView = OpenTK.Matrix4.LookAt(new OpenTK.Vector3(5, 0, -5), new OpenTK.Vector3(0, 0, 0), new OpenTK.Vector3(0, 0, 1));
                
                GL.ShadeModel(ShadingModel.Smooth); // tell it to shade smoothly

                // properties of materials
                GL.Enable(EnableCap.ColorMaterial); // allow polys to have color
                float[] mat_specular = { 1.0f, 1.0f, 1.0f, 1.0f };
                float[] mat_shininess = { 50.0f };
                GL.Material(MaterialFace.Front, MaterialParameter.Specular, mat_specular);
                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, mat_shininess);

                //set a color to clear the background
                GL.ClearColor(Color.LightBlue);

                // antialising lines
                GL.Enable(EnableCap.LineSmooth);
                //GL.Enable(EnableCap.PolygonSmooth);
                GL.Enable(EnableCap.Blend);
                GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
                GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest);
                //GL.Hint(HintTarget.PolygonSmoothHint, HintMode.Nicest);
                float[] res = new float[2];
                GL.GetFloat(GetPName.SmoothLineWidthRange, res);
               // DebugLogger.Instance().LogInfo("Stencil depth: " + glControl1.GraphicsMode.Stencil.ToString());

                // prepare texture buffer to save 3d rendring
                if (mColorBuffer == 0)
                    GL.GenTextures(1, out mColorBuffer);
                GL.BindTexture(TextureTarget.Texture2D, mColorBuffer);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Width, Height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);


                // lighting
                if (firstTime)
                {
                    GL.Enable(EnableCap.Lighting);
                    GL.Enable(EnableCap.Light0);
                    float[] light_position = { 1.0f, 1.0f, 1.0f, 0.0f };
                    GL.Light(LightName.Light0, LightParameter.Position, light_position);
                    GL.Light(LightName.Light0, LightParameter.Diffuse, Color.LightGray);
                }

                // load gui elements
                if (firstTime)
                {
                    gr2d.LoadTexture(global::UV_DLP_3D_Printer.Properties.Resources.cwtexture1_index);
                    gr2d.LoadFont("Arial18", global::UV_DLP_3D_Printer.Properties.Resources.Arial18_metrics);
                    LoadPluginGui();
                    //Visible = true;
                }

                Set3DView();               

                firstTime = false;
            }
            catch (Exception ex)
            {
                String s = ex.Message;
                // the create perspective function blows up on certain ratios
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NiTextureEffect"/> class.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="reader">The reader.</param>
        /// <exception cref="Exception">NOT SUPPORTED!</exception>
        public NiTextureEffect(NiFile file, BinaryReader reader) : base(file, reader)
		{
			this.ModelProjectionMatrix = reader.ReadMatrix33();
			this.ModelProjectionTransform = reader.ReadVector3();
			this.TextureFiltering = (eTexFilterMode)reader.ReadUInt32();
			this.TextureClamping = (eTexClampMode)reader.ReadUInt32();
			this.EffectType = (eEffectType)reader.ReadUInt32();
			this.CoordGenType = (eCoordGenType)reader.ReadUInt32();
			if (base.Version <= eNifVersion.VER_3_1)
			{
				throw new Exception("NOT SUPPORTED!");
			}
			if (base.Version >= eNifVersion.VER_4_0_0_0)
			{
				this.SourceTexture = new NiRef<NiSourceTexture>(reader);
			}
			this.ClippingPlane = reader.ReadBoolean(Version);
			this.unknownVector = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
			this.Unknown2 = reader.ReadSingle();
			if (this.File.Header.Version <= eNifVersion.VER_10_2_0_0)
			{
				this.PS2L = reader.ReadInt16();
				this.PS2K = reader.ReadInt16();
			}
			if (this.File.Header.Version <= eNifVersion.VER_4_1_0_12)
			{
				this.Unknown3 = reader.ReadUInt16();
			}
		}
Beispiel #46
0
		public bool Update()
		{
			/*
		 The solution is based on
		 Berthold K. P. Horn (1987),
		 "Closed-form solution of absolute orientation using unit quaternions,"
		 Journal of the Optical Society of America A, 4:629-642
	 */

			// Original python implementation by David G. Gobbi

			if (this.SourceLandmarks == null || this.TargetLandmarks == null)
			{
				//Identity Matrix
				this.Matrix = new Matrix4(Vector4.UnitX, Vector4.UnitY, Vector4.UnitZ, Vector4.UnitW);
				return false;
			}

			// --- compute the necessary transform to match the two sets of landmarks ---



			int N_PTS = this.SourceLandmarks.Length;
			if (N_PTS != this.TargetLandmarks.Length)
			{
				System.Diagnostics.Debug.WriteLine("Error:  Source and Target Landmarks contain a different number of points");
				return false;
			}

			// -- if no points, stop here

			if (N_PTS == 0)
			{
				//Identity Matrix
				this.Matrix = new Matrix4(Vector4.UnitX, Vector4.UnitY, Vector4.UnitZ, Vector4.UnitW);
				return false;
			}
			float[] source_centroid = { 0, 0, 0 };
			float[] target_centroid = { 0, 0, 0 };

			FindCentroids(N_PTS, source_centroid, target_centroid);

			///-------------------------------
			// -- if only one point, stop right here

			if (N_PTS == 1)
			{
				this.Matrix = new Matrix4(Vector4.UnitX, Vector4.UnitY, Vector4.UnitZ, Vector4.UnitW);
				Matrix[0, 3] = target_centroid[0] - source_centroid[0];
				this.Matrix[1, 3] = target_centroid[1] - source_centroid[1];
				this.Matrix[2, 3] = target_centroid[2] - source_centroid[2];
				return true;
			}

			// -- build the 3x3 matrix M --

			float[,] M = new float[3, 3];
			float[,] AAT = new float[3, 3];

			for (int i = 0; i < 3; i++)
			{
				AAT[i, 0] = M[i, 0] = 0.0F; // fill M with zeros
				AAT[i, 1] = M[i, 1] = 0.0F;
				AAT[i, 2] = M[i, 2] = 0.0F;
			}
			int pt;


			for (pt = 0; pt < N_PTS; pt++)
			{

				float scale = 0F;
				float[,] N = CreateMatrixForDiag(pt, source_centroid, target_centroid, M, ref scale);

				float[,] eigenvectorData = new float[4, 4];
				//float *eigenvectors[4],eigenvalues[4];
				float[,] eigenvectors = new float[4, 4];
				float[] eigenvalues = new float[4];



				//for (int i = 0; i < 4; i++)
				//{
				//    for (int j = 0; j < 4; j++)
				//    {
				//        eigenvectors[i, j] = eigenvectorData[i, j];
				//    }
				//}


				vtkJacobiN(N, 4, eigenvalues, eigenvectors);

				//returns this.Matrix
				CreateMatrixOutOfDiagonalizationResult(eigenvectors, eigenvalues, N_PTS, source_centroid, target_centroid, scale);


				//this.Matrix.Modified();


			}
			return true;
		}
 public void SetDrawingRegion(int x, int y, int w, int h)
 {
     GL.Flush();
     m_ortho = OpenTK.Matrix4.CreateOrthographicOffCenter(-x, mWidth - x, mHeight - y, -y, 1, 2000);
     GL.MatrixMode(MatrixMode.Projection);
     GL.LoadMatrix(ref m_ortho);
     GL.Scissor(x, mHeight - y - h, w, h);
     GL.Enable(EnableCap.ScissorTest);
 }
 /// <summary>
 /// Matrix Overload for Framework Match
 /// </summary>
 public static void CreateTranslation(float x, float y, float z, out Matrix result)
 {
     #if SharpDX
     Matrix.Translation(x, y, z, out result);
     #else
     Matrix.CreateTranslation(x, y, z, out result);
     #endif
 }
        public void SetProjection(CalibrationResult calib, Matrix4? modelView = null, Matrix4? offset = null)
        {
            this.calib = calib;
            parent.MakeCurrent();

            var Width = parent.Width;
            var Height = parent.Height;
            GL.Viewport(0, 0, Width, Height);
            var rt = calib.Extrinsic.ExtrinsicMatrix.Data;
            var extrin = new OpenTK.Matrix4(
                    (float)rt[0, 0], (float)rt[1, 0], (float)rt[2, 0], 0,
                    (float)rt[0, 1], (float)rt[1, 1], (float)rt[2, 1], 0,
                    (float)rt[0, 2], (float)rt[1, 2], (float)rt[2, 2], 0,
                    (float)rt[0, 3], (float)rt[1, 3], (float)rt[2, 3], 1) * (offset.HasValue ? offset.Value : Matrix4.Identity);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref extrin);

            GL.MatrixMode(MatrixMode.Modelview);
            if (modelView == null)
                GL.LoadIdentity();
            else
            {
                var mat = modelView.Value;
                GL.LoadMatrix(ref mat);
            }

            var intrin = calib.Intrinsic.IntrinsicMatrix.Data;
            var dist = calib.Intrinsic.DistortionCoeffs.Data;
            F = new Vector2((float)intrin[0, 0], (float)intrin[1, 1]);
            C = new Vector2((float)intrin[0, 2], (float)intrin[1, 2]);
            K = new Matrix4(
                    (float)dist[0, 0], (float)dist[1, 0], (float)dist[2, 0], (float)dist[3, 0],
                    (float)dist[4, 0], (float)dist[5, 0], (float)dist[6, 0], (float)dist[7, 0],
                    0, 0, 0, 0,
                    0, 0, 0, 0);
        }
Beispiel #50
0
 public virtual void RecalculateModelMatrix()
 {
     m_m4ModelMatrix = Matrix4.CreateScale(m_v2Size.X) * Matrix4.CreateTranslation(m_v3Position);
 }
        void ResizeHandler(object sender, EventArgs e)
        {
            GL.Viewport(ClientRectangle);

            float aspect_ratio = Width / (float)Height;
            projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver2, aspect_ratio, 1, 512);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref projection);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SkinTransform"/> class.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="reader">The reader.</param>
        public SkinTransform(NiFile file, BinaryReader reader)
		{
			this.Rotation = reader.ReadMatrix33();
			this.Translation = reader.ReadVector3();
			this.Scale = reader.ReadSingle();
		}
        private void SetupViewport()
        {
            if (!loaded)
                return;
            float aspect = 1.0f;
            try
            {
                int w = glControl1.Width;
                int h = glControl1.Height;

                GL.Viewport(0, 0, w, h); // Use all of the glControl painting area
                aspect = ((float)glControl1.Width) / ((float)glControl1.Height);

                SetAlpha(false); // start off with alpha off

                GL.Enable(EnableCap.CullFace); // enable culling of faces
                GL.CullFace(CullFaceMode.Back); // specify culling backfaces

                m_projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView(0.55f, aspect, 1, 2000);
                m_modelView = OpenTK.Matrix4.LookAt(new OpenTK.Vector3(5, 0, -5), new OpenTK.Vector3(0, 0, 0), new OpenTK.Vector3(0, 0, 1));

                m_ortho = OpenTK.Matrix4.CreateOrthographicOffCenter(0, w, h, 0, 1, 2000);
                m_2dView = OpenTK.Matrix4.LookAt(new OpenTK.Vector3(0, 0, 10), new OpenTK.Vector3(0, 0, 0), new OpenTK.Vector3(0, 1, 0));

                GL.ShadeModel(ShadingModel.Smooth); // tell it to shade smoothly

                // properties of materials
                GL.Enable(EnableCap.ColorMaterial); // allow polys to have color
                float[] mat_specular = { 1.0f, 1.0f, 1.0f, 1.0f };
                float[] mat_shininess = { 50.0f };
                GL.Material(MaterialFace.Front, MaterialParameter.Specular, mat_specular);
                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, mat_shininess);

                //set a color to clear the background
                GL.ClearColor(Color.LightBlue);

                // antialising lines
                GL.Enable(EnableCap.LineSmooth);
                //GL.Enable(EnableCap.PolygonSmooth);
                GL.Enable(EnableCap.Blend);
                GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
                GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest);
                //GL.Hint(HintTarget.PolygonSmoothHint, HintMode.Nicest);
                float[] res = new float[2];
                GL.GetFloat(GetPName.SmoothLineWidthRange, res);
                DebugLogger.Instance().LogInfo("Stencil depth: " + glControl1.GraphicsMode.Stencil.ToString());

                // lighting
                if (firstTime)
                {
                    GL.Enable(EnableCap.Lighting);
                    GL.Enable(EnableCap.Light0);
                    float[] light_position = { 1.0f, 1.0f, 1.0f, 0.0f };
                    GL.Light(LightName.Light0, LightParameter.Position, light_position);
                    GL.Light(LightName.Light0, LightParameter.Diffuse, Color.LightGray);
                }
                Set3DView();

                gr2d.LoadTexture(global::UV_DLP_3D_Printer.Properties.Resources.cwtexture1,
                    global::UV_DLP_3D_Printer.Properties.Resources.cwtexture1_index);

                firstTime = false;
            }
            catch (Exception ex)
            {
                String s = ex.Message;
                // the create perspective function blows up on certain ratios
            }
        }