Thursday, February 9, 2017

architecture - What is the standard C# / Windows Forms game loop?


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?



Answer



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();
}
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...