#region License
/*
MIT License
Copyright ©2003-2005 Tao Framework Team
http://www.taoframework.com
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion License

#region Original Credits / License
/*
 *  This Code Was Created By Jeff Molofee 2000
 *  A HUGE Thanks To Fredric Echols For Cleaning Up
 *  And Optimizing The Base Code, Making It More Flexible!
 *  If You've Found This Code Useful, Please Let Me Know.
 *  Visit My Site At nehe.gamedev.net
*/
/*
==========================================================================
                     OpenGL Lesson 05:  Solid Objects
==========================================================================

  Authors Name: Jeff Molofee ( NeHe )

  Disclaimer:

  This program may crash your system or run poorly depending on your
  hardware.  The program and code contained in this archive was scanned
  for virii and has passed all test before it was put online.  If you
  use this code in project of your own, send a shout out to the author!

==========================================================================
                        NeHe Productions 1997-2004
==========================================================================
*/
#endregion Original Credits / License

using System;
using System.Threading;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Tao.OpenGl;
using Tao.Platform.Windows;
using Log740;
using WiimoteLib;

namespace Log740 {
    public class Viewer : Form {
        // --- Fields ---
        #region Private Fields
        private IntPtr hDC;                                              // Private GDI Device Context
        private IntPtr hRC;                                              // Permanent Rendering Context
        private bool[] keys = new bool[256];                             // Array Used For The Keyboard Routine
        private bool active = true;                                      // Window Active Flag, Set To True By Default
        private bool fullscreen = true;                                  // Fullscreen Flag, Set To Fullscreen Mode By Default
        private bool done = false;                                       // Bool Variable To Exit Main Loop

        private int fontbase;                                            // Base Display List For The Font Set

        private double lens = 45;

        private int[] buffer = new int[512];
        private int[] viewport = new int[4];


        private Quaternion camera_rotation = Quaternion.Identity();
        private Vecteur3F camera_position = new Vecteur3F(0, 0, 0);

        private int animation_period = 20;

        private bool animate = false;
        private System.Threading.Timer t;

        #endregion Private Fields

        // --- Constructors & Destructors ---
        #region Viewer
        /// <summary>
        ///     Creates a new instance.
        /// </summary>
        public Viewer() {
            this.CreateParams.ClassStyle = this.CreateParams.ClassStyle |       // Redraw On Size, And Own DC For Window.
                User.CS_HREDRAW | User.CS_VREDRAW | User.CS_OWNDC;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);            // No Need To Erase Form Background
            this.SetStyle(ControlStyles.DoubleBuffer, true);                    // Buffer Control
            this.SetStyle(ControlStyles.Opaque, true);                          // No Need To Draw Form Background
            this.SetStyle(ControlStyles.ResizeRedraw, true);                    // Redraw On Resize
            this.SetStyle(ControlStyles.UserPaint, true);                       // We'll Handle Painting Ourselves

            this.Activated += new EventHandler(this.Form_Activated);            // On Activate Event Call Form_Activated
            this.Closing += new CancelEventHandler(this.Form_Closing);          // On Closing Event Call Form_Closing
            this.Deactivate += new EventHandler(this.Form_Deactivate);          // On Deactivate Event Call Form_Deactivate
            this.KeyDown += new KeyEventHandler(this.Form_KeyDown);             // On KeyDown Event Call Form_KeyDown
            this.KeyUp += new KeyEventHandler(this.Form_KeyUp);                 // On KeyUp Event Call Form_KeyUp
            this.Resize += new EventHandler(this.Form_Resize);                  // On Resize Event Call Form_Resize

            t = new System.Threading.Timer(AnimateCallback);
            t.Change(0, animation_period);
        }
        #endregion Viewer

        // --- Entry Point ---
        #region Run()
        /// <summary>
        ///     The application's entry point.
        /// </summary>
        /// <param name="commandLineArguments">
        ///     Any supplied command line arguments.
        /// </param>
        [MTAThread]
        public void Run(string title, int width, int height, bool fullscreenflag)
        {
            // Create Our OpenGL Window
            if (!CreateGLWindow(title, width, height, 32, fullscreenflag))
            {
                return;                                                         // Quit If Window Was Not Created
            }

            while (!done)
            {                                                      // Loop That Runs While done = false
                Application.DoEvents();                                         // Process Events

                RefreshScene();

                if (this.animate)
                {
                    AnimateScene();
                    this.animate = false;
                }

                // Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
                if ((active && !Draw()))
                {   //  Active?  Was There A Quit Received?
                    done = true;                                            // Draw Signalled A Quit
                }
                else {                                                      // Not Time To Quit, Update Screen
                    Gdi.SwapBuffers(hDC);                                   // Swap Buffers (Double Buffering)
                }
            }

            // Shutdown
            KillGLWindow();                                                     // Kill The Window
            KillFont();
            Cleanup();
            return;                                                             // Exit The Program
        }
        #endregion Run()

        // --- Private Static Methods ---
        #region BuildFont()
        /// <summary>
        ///     Builds our bitmap font.
        /// </summary>
        private void BuildFont()
        {
            IntPtr font;                                                        // Windows Font ID
            IntPtr oldfont;                                                     // Used For Good House Keeping
            fontbase = Gl.glGenLists(96);                                       // Storage For 96 Characters

            font = Gdi.CreateFont(                                              // Create The Font
                -24,                                                            // Height Of Font
                0,                                                              // Width Of Font
                0,                                                              // Angle Of Escapement
                0,                                                              // Orientation Angle
                Gdi.FW_BOLD,                                                    // Font Weight
                false,                                                          // Italic
                false,                                                          // Underline
                false,                                                          // Strikeout
                Gdi.ANSI_CHARSET,                                               // Character Set Identifier
                Gdi.OUT_TT_PRECIS,                                              // Output Precision
                Gdi.CLIP_DEFAULT_PRECIS,                                        // Clipping Precision
                Gdi.ANTIALIASED_QUALITY,                                        // Output Quality
                Gdi.FF_DONTCARE | Gdi.DEFAULT_PITCH,                            // Family And Pitch
                "Courier New");                                                 // Font Name

            oldfont = Gdi.SelectObject(hDC, font);                              // Selects The Font We Want
            Wgl.wglUseFontBitmapsA(hDC, 32, 96, fontbase);                       // Builds 96 Characters Starting At Character 32
            Gdi.SelectObject(hDC, oldfont);                                     // Selects The Font We Want
            Gdi.DeleteObject(font);                                             // Delete The Font
        }
        #endregion BuildFont()

        #region KillFont()
        /// <summary>
        ///     Delete the font list.
        /// </summary>
        private void KillFont() {
            Gl.glDeleteLists(fontbase, 96);                                     // Delete All 96 Characters
        }
        #endregion KillFont()

        #region glPrint(string text)
        /// <summary>
        ///     Custom GL "print" routine.
        /// </summary>
        /// <param name="text">
        ///     The text to print.
        /// </param>
        public void glPrint(string text) {
            if(text == null || text.Length == 0) {                              // If There's No Text
                return;                                                         // Do Nothing
            }
            Gl.glPushAttrib(Gl.GL_LIST_BIT);                                    // Pushes The Display List Bits
                Gl.glListBase(fontbase - 32);                                   // Sets The Base Character to 32
                byte [] textbytes = new byte[text.Length];
                for (int i = 0; i < text.Length; i++) textbytes[i] = (byte) text[i];
                Gl.glCallLists(text.Length, Gl.GL_UNSIGNED_BYTE, textbytes);        // Draws The Display List Text
            Gl.glPopAttrib();                                                   // Pops The Display List Bits
        }
        #endregion glPrint(string text)
        
        protected void CloseGLWindow()
        {
            this.done = true;
        }

        protected int AnimationPeriod
        {
            get
            {
                return animation_period;
            }

            set
            {
                animation_period = value;
                t.Change(0, animation_period);
            }
        }

        protected double Lens
        {
            get
            {
                return this.lens;
            }
            set
            {
                if (value != this.lens)
                {
                    this.lens = value;

                    if (this.lens < 1)
                    {
                        this.lens = 1;
                    }
                    else if (this.lens > 179)
                    {
                        this.lens = 179;
                    }

                    ReSizeGLWindow(this.DisplayRectangle.Width, this.DisplayRectangle.Height);
                }
            }
        }

        protected Vecteur3F CameraPosition
        {
            get
            {
                return camera_position;
            }

            set
            {
                camera_position = value;
            }
        }

        protected Quaternion CameraRotation
        {
            get
            {
                return camera_rotation;
            }

            set
            {
                camera_rotation = value;
            }
        }

        virtual protected void Cleanup()
        {
        }

        virtual protected void AnimateScene()
        {
        }

        virtual protected void RefreshScene()
        {
            if (keys[(int)Keys.Escape])
            {
                CloseGLWindow();
            }
        }

        public Vecteur3F NormalUnderPixel(double X, double Y)
        {
            Vecteur3F v = new Vecteur3F(0, 0, -1);
            
            double original = Math.Tan(this.lens / 2 / 180 * Math.PI);
            
            double py = (Y - DisplayRectangle.Height / 2) / (DisplayRectangle.Height / 2) * original;
            double px = (X - DisplayRectangle.Width / 2)  / (DisplayRectangle.Height / 2) * original;

            Quaternion quat_pointer = Quaternion.BetweenAxis(v, new Vecteur3F(px, py, -1));

            return -camera_rotation * quat_pointer * v;
        }

        protected void Draw2D(ObjectGL obj, double X, double Y)
        {
            Gl.glMatrixMode(Gl.GL_PROJECTION);
            Gl.glPushMatrix();
            Gl.glLoadIdentity();
            Gl.glOrtho(0, this.DisplayRectangle.Width, 0, this.DisplayRectangle.Height, -1, 1);
            Gl.glMatrixMode(Gl.GL_MODELVIEW);
            Gl.glPushMatrix();
            Gl.glLoadIdentity();

            Gl.glTranslated(X, Y, 0);

            obj.Draw();

            Gl.glPopMatrix();
            Gl.glMatrixMode(Gl.GL_PROJECTION);
            Gl.glPopMatrix();
            Gl.glMatrixMode(Gl.GL_MODELVIEW);
        }

        virtual protected bool DrawGLScene()
        {
            return true;
        }

        virtual protected bool DrawGLSceneWithNames()
        {
            return true;
        }

        protected bool IsKeyPressed(Keys k)
        {
            return keys[(int)k];
        }

        // --- Private Static Methods ---
        
        #region bool CreateGLWindow(string title, int width, int height, int bits, bool fullscreenflag)
        /// <summary>
        ///     Creates our OpenGL Window.
        /// </summary>
        /// <param name="title">
        ///     The title to appear at the top of the window.
        /// </param>
        /// <param name="width">
        ///     The width of the GL window or fullscreen mode.
        /// </param>
        /// <param name="height">
        ///     The height of the GL window or fullscreen mode.
        /// </param>
        /// <param name="bits">
        ///     The number of bits to use for color (8/16/24/32).
        /// </param>
        /// <param name="fullscreenflag">
        ///     Use fullscreen mode (<c>true</c>) or windowed mode (<c>false</c>).
        /// </param>
        /// <returns>
        ///     <c>true</c> on successful window creation, otherwise <c>false</c>.
        /// </returns>
        private bool CreateGLWindow(string title, int width, int height, int bits, bool fullscreenflag) {
            int pixelFormat;                                                    // Holds The Results After Searching For A Match
            fullscreen = fullscreenflag;                                        // Set The Global Fullscreen Flag

            GC.Collect();                                                       // Request A Collection
            // This Forces A Swap
            Kernel.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);

            if(fullscreen) {                                                    // Attempt Fullscreen Mode?
                Gdi.DEVMODE dmScreenSettings = new Gdi.DEVMODE();               // Device Mode
                // Size Of The Devmode Structure
                dmScreenSettings.dmSize = (short) Marshal.SizeOf(dmScreenSettings);
                dmScreenSettings.dmPelsWidth = width;                           // Selected Screen Width
                dmScreenSettings.dmPelsHeight = height;                         // Selected Screen Height
                dmScreenSettings.dmBitsPerPel = bits;                           // Selected Bits Per Pixel
                dmScreenSettings.dmFields = Gdi.DM_BITSPERPEL | Gdi.DM_PELSWIDTH | Gdi.DM_PELSHEIGHT;

                // Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
                if(User.ChangeDisplaySettings(ref dmScreenSettings, User.CDS_FULLSCREEN) != User.DISP_CHANGE_SUCCESSFUL) {
                    // If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
                    if(MessageBox.Show("The Requested Fullscreen Mode Is Not Supported By\nYour Video Card.  Use Windowed Mode Instead?", "OpenGL",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) {
                        fullscreen = false;                                     // Windowed Mode Selected.  Fullscreen = false
                    }
                    else {
                        // Pop up A Message Box Lessing User Know The Program Is Closing.
                        MessageBox.Show("Program Will Now Close.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        return false;                                           // Return false
                    }
                }
            }

            if(fullscreen) {                                                    // Are We Still In Fullscreen Mode?
                this.FormBorderStyle = FormBorderStyle.None;                    // No Border
                Cursor.Hide();                                                  // Hide Mouse Pointer
            }
            else {                                                              // If Windowed
                this.FormBorderStyle = FormBorderStyle.Sizable;                 // Sizable
                Cursor.Show();                                                  // Show Mouse Pointer
            }

            this.Width = width;                                                 // Set Window Width
            this.Height = height;                                               // Set Window Height
            this.Text = title;                                                  // Set Window Title

            Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR();    // pfd Tells Windows How We Want Things To Be
            pfd.nSize = (short) Marshal.SizeOf(pfd);                            // Size Of This Pixel Format Descriptor
            pfd.nVersion = 1;                                                   // Version Number
            pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW |                              // Format Must Support Window
                Gdi.PFD_SUPPORT_OPENGL |                                        // Format Must Support OpenGL
                Gdi.PFD_DOUBLEBUFFER;                                           // Format Must Support Double Buffering
            pfd.iPixelType = (byte) Gdi.PFD_TYPE_RGBA;                          // Request An RGBA Format
            pfd.cColorBits = (byte) bits;                                       // Select Our Color Depth
            pfd.cRedBits = 0;                                                   // Color Bits Ignored
            pfd.cRedShift = 0;
            pfd.cGreenBits = 0;
            pfd.cGreenShift = 0;
            pfd.cBlueBits = 0;
            pfd.cBlueShift = 0;
            pfd.cAlphaBits = 0;                                                 // No Alpha Buffer
            pfd.cAlphaShift = 0;                                                // Shift Bit Ignored
            pfd.cAccumBits = 0;                                                 // No Accumulation Buffer
            pfd.cAccumRedBits = 0;                                              // Accumulation Bits Ignored
            pfd.cAccumGreenBits = 0;
            pfd.cAccumBlueBits = 0;
            pfd.cAccumAlphaBits = 0;
            pfd.cDepthBits = 16;                                                // 16Bit Z-Buffer (Depth Buffer)
            pfd.cStencilBits = 0;                                               // No Stencil Buffer
            pfd.cAuxBuffers = 0;                                                // No Auxiliary Buffer
            pfd.iLayerType = (byte) Gdi.PFD_MAIN_PLANE;                         // Main Drawing Layer
            pfd.bReserved = 0;                                                  // Reserved
            pfd.dwLayerMask = 0;                                                // Layer Masks Ignored
            pfd.dwVisibleMask = 0;
            pfd.dwDamageMask = 0;

            hDC = User.GetDC(this.Handle);                                      // Attempt To Get A Device Context
            if(hDC == IntPtr.Zero) {                                            // Did We Get A Device Context?
                KillGLWindow();                                                 // Reset The Display
                MessageBox.Show("Can't Create A GL Device Context.", "ERROR",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            pixelFormat = Gdi.ChoosePixelFormat(hDC, ref pfd);                  // Attempt To Find An Appropriate Pixel Format
            if(pixelFormat == 0) {                                              // Did Windows Find A Matching Pixel Format?
                KillGLWindow();                                                 // Reset The Display
                MessageBox.Show("Can't Find A Suitable PixelFormat.", "ERROR",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if(!Gdi.SetPixelFormat(hDC, pixelFormat, ref pfd)) {                // Are We Able To Set The Pixel Format?
                KillGLWindow();                                                 // Reset The Display
                MessageBox.Show("Can't Set The PixelFormat.", "ERROR",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            hRC = Wgl.wglCreateContext(hDC);                                    // Attempt To Get The Rendering Context
            if(hRC == IntPtr.Zero) {                                            // Are We Able To Get A Rendering Context?
                KillGLWindow();                                                 // Reset The Display
                MessageBox.Show("Can't Create A GL Rendering Context.", "ERROR",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if(!Wgl.wglMakeCurrent(hDC, hRC)) {                                 // Try To Activate The Rendering Context
                KillGLWindow();                                                 // Reset The Display
                MessageBox.Show("Can't Activate The GL Rendering Context.", "ERROR",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            this.Show();                                                        // Show The Window
            this.TopMost = true;                                                // Topmost Window
            this.Focus();                                                       // Focus The Window

            if(fullscreen) {                                                    // This Shouldn't Be Necessary, But Is
                Cursor.Hide();
            }
            ReSizeGLWindow(this.DisplayRectangle.Width, this.DisplayRectangle.Height);                                       // Set Up Our Perspective GL Screen

            if(!InitGL()) {                                                     // Initialize Our Newly Created GL Window
                KillGLWindow();                                                 // Reset The Display
                MessageBox.Show("Initialization Failed.", "ERROR",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;                                                        // Success
        }
        #endregion bool CreateGLWindow(string title, int width, int height, int bits, bool fullscreenflag)

        public int Select(double x, double y, double width, double height)
        {
            int selected = -1;
            int min_z;
            int hits;

            Gl.glGetIntegerv(Gl.GL_VIEWPORT, viewport);
            Gl.glSelectBuffer(512, buffer);
            Gl.glRenderMode(Gl.GL_SELECT);

            Gl.glMatrixMode(Gl.GL_PROJECTION);
            Gl.glPushMatrix();
            Gl.glLoadIdentity();
            Glu.gluPickMatrix(x, y, width, height, viewport);
            Glu.gluPerspective(lens, this.DisplayRectangle.Width / (double)this.DisplayRectangle.Height, 0.1, 200);          // Calculate The Aspect Ratio Of The Window

            Gl.glMatrixMode(Gl.GL_MODELVIEW);

            if (!DrawWithNames())
            {
                return -1;
            }

            Gl.glMatrixMode(Gl.GL_PROJECTION);
            Gl.glPopMatrix();
            Gl.glFlush();

            Gl.glMatrixMode(Gl.GL_MODELVIEW);

            hits = Gl.glRenderMode(Gl.GL_RENDER);


            if (hits > 0)
            {
                int i;

                selected = buffer[3];
                min_z = buffer[1];

                for (i = 1; i < hits; i++)
                {
                    if (buffer[4 * i + 1] < min_z)
                    {
                        selected = buffer[4 * i + 3];
                        min_z = buffer[4 * i + 1];
                    }
                }
            }

            return selected;
        }

        private void ApplyCamera()
        {
            Gl.glLoadIdentity();                                                // Reset The Current Modelview Matrix
            Gl.glRotated(180 * camera_rotation.Angle / Math.PI, camera_rotation.X, camera_rotation.Y, camera_rotation.Z);
            Gl.glTranslated(-camera_position.X, -camera_position.Y, -camera_position.Z);
        }

        private bool DrawWithNames()
        {
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);        // Clear Screen And Depth Buffer
            ApplyCamera();

            return DrawGLSceneWithNames();
        }

        private bool Draw()
        {
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);        // Clear Screen And Depth Buffer
            ApplyCamera();

            Gl.glRenderMode(Gl.GL_RENDER);

            return DrawGLScene();
        }

        #region bool InitGL()
        /// <summary>
        ///     All setup for OpenGL goes here.
        /// </summary>
        /// <returns>
        ///     <c>true</c> on successful initialization, otherwise <c>false</c>.
        /// </returns>
        virtual protected bool InitGL() {
            Gl.glShadeModel(Gl.GL_SMOOTH);                                      // Enable Smooth Shading
            Gl.glClearColor(0, 0, 0, 0.5f);                                     // Black Background
            Gl.glClearDepth(1);                                                 // Depth Buffer Setup
            Gl.glEnable(Gl.GL_DEPTH_TEST);                                      // Enables Depth Testing
            Gl.glDepthFunc(Gl.GL_LEQUAL);                                       // The Type Of Depth Testing To Do
            Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST);         // Really Nice Perspective Calculations
            BuildFont();                                                        // Build The Font
            return true;
        }
        #endregion bool InitGL()

        #region KillGLWindow()
        /// <summary>
        ///     Properly kill the window.
        /// </summary>
        private void KillGLWindow() {
            if(fullscreen) {                                                    // Are We In Fullscreen Mode?
                User.ChangeDisplaySettings(IntPtr.Zero, 0);                     // If So, Switch Back To The Desktop
                Cursor.Show();                                                  // Show Mouse Pointer
            }

            if(hRC != IntPtr.Zero) {                                            // Do We Have A Rendering Context?
                if(!Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero)) {             // Are We Able To Release The DC and RC Contexts?
                    MessageBox.Show("Release Of DC And RC Failed.", "SHUTDOWN ERROR",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if(!Wgl.wglDeleteContext(hRC)) {                                // Are We Able To Delete The RC?
                    MessageBox.Show("Release Rendering Context Failed.", "SHUTDOWN ERROR",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                hRC = IntPtr.Zero;                                              // Set RC To Null
            }

            if(hDC != IntPtr.Zero) {                                            // Do We Have A Device Context?
                if(!this.IsDisposed) {                                          // Do We Have A Window?
                    if(this.Handle != IntPtr.Zero) {                            // Do We Have A Window Handle?
                        if(!User.ReleaseDC(this.Handle, hDC)) {                 // Are We Able To Release The DC?
                            MessageBox.Show("Release Device Context Failed.", "SHUTDOWN ERROR",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }

                hDC = IntPtr.Zero;                                              // Set DC To Null
            }

            this.Hide();                                                    // Hide The Window
            this.Close();                                                   // Close The Form
        }
        #endregion KillGLWindow()

        #region ReSizeGLWindow(int width, int height)
        /// <summary>
        ///     Resizes and initializes the GL window.
        /// </summary>
        /// <param name="width">
        ///     The new window width.
        /// </param>
        /// <param name="height">
        ///     The new window height.
        /// </param>
        private void ReSizeGLWindow(int width, int height)
        {
            if(height == 0) {                                                   // Prevent A Divide By Zero...
                height = 1;                                                     // By Making Height Equal To One
            }

            Gl.glViewport(0, 0, width, height);                                 // Reset The Current Viewport
            Gl.glMatrixMode(Gl.GL_PROJECTION);                                  // Select The Projection Matrix
            Gl.glLoadIdentity();                                                // Reset The Projection Matrix
            Glu.gluPerspective(lens, width / (double) height, 0.1, 400);        // Calculate The Aspect Ratio Of The Window
            Gl.glMatrixMode(Gl.GL_MODELVIEW);                                   // Select The Modelview Matrix
        }
        #endregion ReSizeGLScene(int width, int height)

        private void AnimateCallback(object state)
        {
            this.animate = true;
        }


        // --- Private Instance Event Handlers ---
        #region Form_Activated
        /// <summary>
        ///     Handles the form's activated event.
        /// </summary>
        /// <param name="sender">
        ///     The event sender.
        /// </param>
        /// <param name="e">
        ///     The event arguments.
        /// </param>
        private void Form_Activated(object sender, EventArgs e) {
            active = true;                                                      // Program Is Active
        }
        #endregion Form_Activated

        #region Form_Closing(object sender, CancelEventArgs e)
        /// <summary>
        ///     Handles the form's closing event.
        /// </summary>
        /// <param name="sender">
        ///     The event sender.
        /// </param>
        /// <param name="e">
        ///     The event arguments.
        /// </param>
        private void Form_Closing(object sender, CancelEventArgs e) {
            done = true;                                                        // Send A Quit Message
        }
        #endregion Form_Closing(object sender, CancelEventArgs e)

        #region Form_Deactivate(object sender, EventArgs e)
        /// <summary>
        ///     Handles the form's deactivate event.
        /// </summary>
        /// <param name="sender">
        ///     The event sender.
        /// </param>
        /// <param name="e">
        ///     The event arguments.
        /// </param>
        private void Form_Deactivate(object sender, EventArgs e) {
            active = false;                                                     // Program Is No Longer Active
        }
        #endregion Form_Deactivate(object sender, EventArgs e)

        #region Form_KeyDown(object sender, KeyEventArgs e)
        /// <summary>
        ///     Handles the form's key down event.
        /// </summary>
        /// <param name="sender">
        ///     The event sender.
        /// </param>
        /// <param name="e">
        ///     The event arguments.
        /// </param>
        private void Form_KeyDown(object sender, KeyEventArgs e) {
            keys[e.KeyValue] = true;                                            // Key Has Been Pressed, Mark It As true
        }
        #endregion Form_KeyDown(object sender, KeyEventArgs e)

        #region Form_KeyUp(object sender, KeyEventArgs e)
        /// <summary>
        ///     Handles the form's key down event.
        /// </summary>
        /// <param name="sender">
        ///     The event sender.
        /// </param>
        /// <param name="e">
        ///     The event arguments.
        /// </param>
        private void Form_KeyUp(object sender, KeyEventArgs e) {
            keys[e.KeyValue] = false;                                           // Key Has Been Released, Mark It As false
        }
        #endregion Form_KeyUp(object sender, KeyEventArgs e)

        #region Form_Resize(object sender, EventArgs e)
        /// <summary>
        ///     Handles the form's resize event.
        /// </summary>
        /// <param name="sender">
        ///     The event sender.
        /// </param>
        /// <param name="e">
        ///     The event arguments.
        /// </param>
        private void Form_Resize(object sender, EventArgs e) {
            ReSizeGLWindow(this.DisplayRectangle.Width, this.DisplayRectangle.Height);                             // Resize The OpenGL Window
        }
        #endregion Form_Resize(object sender, EventArgs e)
    }
}
