Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

Tutorials

pet_cz

Creating OpenGL context

  • Include references to System.Windows.Forms and System.Drawing.
  • Include a reference to OpenGL4Net.dll (IMPORTANT! 32 or 64 bit version according to your project properties) or add OpenGL4Net.cs to your project.
  • Optionally use the "using" statement to shorten the syntax

    using System;
    using System.Windows.Forms;
    using OpenGL4Net;
    
  • It is easier to inherit your class from System.Windows.Forms.Form.

  • Add the RenderingContext as a class variable.
  • Create the Main function that creates an instance of your form, calls the Init function and starts the application with Application.Run method.

    class Program : Form
    {
        RenderingContext rc;
    
        static void Main(string[] args)
        {
            Program program = new Program();
            program.Init();
            Application.Run(program);
        }
    
  • Now create the Init function that creates the rendering context, using the form (this). To avoid flickering in some cases (e.g., changing the size), it is necessary to ignore the WM_ERASEBKGND message. This could be achieved by setting control style AllPaintingInWmPaint to true (or by ignoring WM_ERASEBKGND in WndProc method).

        void Init()
        {
            rc = RenderingContext.CreateContext(this);
            SetStyle (ControlStyles.AllPaintingInWmPaint, true);
        }
    
  • The Render method should clear the screen and swap front and back buffers

        void Render()
        {
            gl.Clear(GL.COLOR_BUFFER_BIT);
    
            // here is the right place to draw all your scene
    
            rc.SwapBuffers();
        }
    
  • If you plan to allow the user to change the window size, you have to update the viewport size and probably make some changes in your projection matrix.

        protected override void OnSizeChanged(EventArgs e)
        {
            gl.Viewport(0,0,ClientSize.Width, ClientSize.Height);
            // change projection matrix etc.
        }
    
  • Finally, override the WndProc method and call Render method on WM_PAINT message

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case Windows.WM_PAINT: Render(); break;
                default: base.WndProc(ref m); break;
            }
        }
    
    }
    

Related

Wiki: Home

  • jwr
    jwr
    2013-01-20

    You may have to call Render() for WM_ERASEBKGND (0x0014) too. If your window has FormBorderStyle of Sizable then you'll need to watch for WM_SIZE (0x0005) messages and update your gl.Viewport accordingly.

     
    • pet_cz
      pet_cz
      2013-01-21

      Yes, you are right, I just wanted to make the example as simple as possible, but this should be probably mentioned. Thank you.