32
\$\begingroup\$

When writing a game in C# that uses plain-old Windows Forms and some graphics API wrapper like SlimDX or OpenTK, how should the main game loop be structured?

A canonical Windows Forms application has an entry point that looks like

public static void Main () {
  Application.Run(new MainForm());
}

and while one can accomplish some of what is neccessary by hooking the various events of the Form class, those events don't provide an obvious place to put the bits of code to perform constant periodic updates to game logic objects or to begin and end a render frame.

What technique should such a game use to achieve something akin to the canonical

while(!done) {
  update();
  render();
}

game loop, and to do with minimal performance and GC impact?

\$\endgroup\$
45
\$\begingroup\$

The Application.Run call drives your Windows message pump, which is ultimately what powers all the events you can hook on the Form class (and others). To create a game loop in this ecosystem, you want to listen for when the application's message pump is empty, and while it remains empty, do the typical "process input state, update game logic, render the scene" steps of the prototypical game loop.

The Application.Idle event fires once every time the application's message queue is emptied and the application is transitioning to an idle state. You can hook the event in the constructor of your main form:

class MainForm : Form {
  public MainForm () {
    Application.Idle += HandleApplicationIdle;
  }

  void HandleApplicationIdle (object sender, EventArgs e) {
    //TODO: Implement me.
  }
}

Next, you need to be able to determine if the application is still idle. The Idle event only fires once, when the application becomes idle. It does not get fired again until a message gets into the queue and then the queue empties out again. Windows Forms doesn't expose a method to query the state of the message queue, but you can use platform invocation services to delegate the query to a native Win32 function that can answer that question. The import declaration for PeekMessage and its supporting types looks like:

[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
    public IntPtr Handle;
    public uint Message;
    public IntPtr WParameter;
    public IntPtr LParameter;
    public uint Time;
    public Point Location;
}

[DllImport("user32.dll")]
public static extern int PeekMessage(out NativeMessage message, IntPtr window, uint filterMin, uint filterMax, uint remove);

PeekMessage basically allows you to look at the next message in the queue; it returns true if one exists, false otherwise. For the purposes of this problem, none of the parameters are particularly relevant: it's only the return value that matters. This allows you to write a function that tells you if the application is still idle (that is, there are still no messages in the queue):

bool IsApplicationIdle () {
    NativeMessage result;
    return PeekMessage(out result, IntPtr.Zero, (uint)0, (uint)0, (uint)0) == 0;
}

Now you have everything you need to write your complete game loop:

class MainForm : Form {
  public MainForm () {
    Application.Idle += HandleApplicationIdle;
  }

  void HandleApplicationIdle (object sender, EventArgs e) {
    while(IsApplicationIdle()) {
      Update();
      Render();
    }
  }

  void Update () {
    // ...
  }

  void Render () {
    // ...
  }

  [StructLayout(LayoutKind.Sequential)]
  public struct NativeMessage
  {
      public IntPtr Handle;
      public uint Message;
      public IntPtr WParameter;
      public IntPtr LParameter;
      public uint Time;
      public Point Location;
  }

  [DllImport("user32.dll")]
  public static extern int PeekMessage(out NativeMessage message, IntPtr window, uint filterMin, uint filterMax, uint remove);
}

Furthermore, this approach matches up as close as possible (with minimal reliance on P/Invoke) to the canonical native Windows game loop, which looks like:

while (!done) {
    if (PeekMessage(&message, window, 0, 0, PM_REMOVE)){
        TranslateMessage(&message);
        DispatchMessage(&message);
    }
    else {
        Update();
        Render();
    }
}
\$\endgroup\$
  • \$\begingroup\$ What's the need for dealing with such windows apis features? Making a while block ruled by a precise stop watch (for fps control), wouldn't be sufficient? \$\endgroup\$ – Emir Lima Dec 20 '13 at 14:33
  • 3
    \$\begingroup\$ You need to return from the Application.Idle handler at some point, otherwise your application will freeze (since it never allows further Win32 messages to happen). You could instead try to make a loop based on WM_TIMER messages, but WM_TIMER isn't nearly as precise as you'd really want, and even if it was it would force everything to that lowest-common-denominator update rate. Many games need or want to have independent render and logic update rates, some of which (like physics) remain fixed while others aren't. \$\endgroup\$ – Josh Dec 20 '13 at 16:18
  • \$\begingroup\$ Native Windows game loops use the same technique (I've amended my answer to include a simple one for comparison. Timers to force a fixed update rate are less flexible, and you can always implement your fixed update rate within the broader context of the PeekMessage-style loop (using timers with better precision and GC impact than WM_TIMER-based ones). \$\endgroup\$ – Josh Dec 20 '13 at 16:22
  • \$\begingroup\$ @JoshPetrie To be clear, the above checking for idle uses a function for SlimDX. Would it be ideal to include this in the answer? Or is it just by chance you edited the code to read 'IsApplicationIdle' which is the SlimDX counterpart? \$\endgroup\$ – Vaughan Hilts Apr 4 '14 at 6:01
  • \$\begingroup\$ ** Please ignore me, I just realized you define it further down... :) \$\endgroup\$ – Vaughan Hilts Apr 4 '14 at 6:02
2
\$\begingroup\$

Agreed with the answer from Josh, just want to add my 5 cents. WinForms default message loop (Application.Run) could be replaced with the following (without p/invoke):

[STAThread]
static void Main()
{
    using (Form1 f = new Form1())
    {
        f.Show();
        while (true) // here should be some nice exit condition
        {
            Application.DoEvents(); // default message pump
        }
    }
}

Also if you want to inject some code into message pump, then use this:

public partial class Form1 : Form
{
    protected override void WndProc(ref Message m)
    {
        // this code is invoked inside default message pump
        base.WndProc(ref m);
    }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ You need to be aware of the DoEvents() garbage-generation overhead if you choose this approach, however. \$\endgroup\$ – Josh Dec 20 '13 at 19:13
0
\$\begingroup\$

I understand that this is an old thread, but I’d like to provide two alternatives to the techniques suggested above. Before I go into them, here are some of the pitfalls with the proposals made so far:

  1. PeekMessage carries considerable overhead, as do the library methods that call it (SlimDX IsApplicationIdle).

  2. If you want to employ buffered RawInput, you’ll need to poll the message pump with PeekMessage on another thread other than the UI thread, so you don’t want to be calling it twice.

  3. Application.DoEvents is not designed to be called in a tight loop, GC problems will quickly emerge.

  4. When using Application.Idle or PeekMessage, because you’re only doing work when Idle, your game or application will not run when moving or resizing your window, without code smells.

To work around these (except 2 if you’re going down the RawInput road) you can either:

  1. Create a Threading.Thread and run your game loop there.

  2. Create a Threading.Tasks.Task with the IsLongRunning flag, and run it there. Microsoft recommends that Tasks be used in place of Threads these days and it’s not hard to see why.

Both of these techniques isolate your graphics API from the UI thread and message pump, as is the recommended approach. The handling of resource/state destruction and recreation during Window resizing is also simplified and is aesthetically much more professional when done from done (exericising due caution to avoid deadlocks wifh the message pump) from outside the UI thread.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.