My last post on render loops (hopefully)..


The most common topic on my blog returns again.  This time it will be brief as all I’m going to to do now is show you the render loop the June’05 SDK will be using.  A coworker in another group came up with this markedly simple, yet deceptively effective loop for that groups projects.  I liked it so much, i’m sharing it with everyone else. =)


The basic loop (slightly modified from his original version and the version in the new SDK for ease of reading):


public void MainLoop()
{
        // Hook the application’s idle event
        System.Windows.Forms.Application.Idle += new EventHandler(OnApplicationIdle);
        System.Windows.Forms.Application.Run(myForm);
}


private void OnApplicationIdle(object sender, EventArgs e)
{
    while (AppStillIdle)
    {
         // Render a frame during idle time (no messages are waiting)
         UpdateEnvironment();
         Render3DEnvironment();
    }
}

private bool AppStillIdle
{
     get
    {
        NativeMethods.Message msg;
        return !NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
     }
}


And the declarations for those two native methods members:


[StructLayout(LayoutKind.Sequential)]
public struct Message
{
    public IntPtr hWnd;
    public WindowMessage msg;
    public IntPtr wParam;
    public IntPtr lParam;
    public uint time;
    public System.Drawing.Point p;
}

[System.Security.SuppressUnmanagedCodeSecurity] // We won’t use this maliciously
[DllImport(“User32.dll”, CharSet=CharSet.Auto)]
public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);


——


Simple, elegant, effective.  No extra allocations, no extra collections, it just works..  The Idle event fires when there’s no messages in the queue, and then the handler keeps looping continuously until a message does appear, in which case it stops..  Once all the messages are handled, the idle event is fired again, and the process starts over.

Comments (29)

  1. dwellerville says:

    Tom Miller finally states the last word on the subject of game loops in Managed DirectX code.  Now…

  2. Richard says:

    So Tom how does this way of looping compare (fps and memory wise) to the way Rick Hoskinson recently started discussing on his blog. http://blogs.msdn.com/rickhos/archive/2005/04/04/405327.aspx

    -Richard

    Richard.Parsons (at) gmail.com

  3. wtf says:

    Why on earth is this page using SSL?

  4. Tom, in your Message struct, what is WindowMessage? Would that be System.Windows.Forms.Message?

  5. Seb Nemeth says:

    How does this stand up to supporting rendering to Controls and not just a Form, I wonder..?

  6. Zman says:

    Added link to ‘the saga of the MDX render loop’ http://www.thezbuffer.com/articles/185.aspx

  7. Turon says:

    Hi Tom,

    Can’t help but notice that your new approach, if i’m not mistaken, is quite similar how GLUT handles the rendering. In GLUT, you need to hook up a callback to the idle event for rendering. Your latest approach is the cleanest so far. KUDOS Tom!

    BTW, I have your book "Beginning 3D Game Programming" and it ROCKS!

    PS: Sorry about the OpenGL / GLUT post. Since I moved to using C#, I’m now a Managed DirectX fan 😛

  8. Bob the slob says:

    This is bloody brilliant, why didn’t I think of this? I have perhaps the most complicated render loop in the history of the universe right now (mind you, it handles switching between windowed/fullscreen, task switching, res changes flawlessly).

  9. Petey says:

    public WindowMessage msg;

    Where does "WindowMessage" come from? I can’t seem to find it in any of the namespaces!

  10. Sivan Segev says:

    I’ve been tracking the posts regarding render loops, but early on I moved the scene preperation and rendering into a seperate thread. The thread renders to a window or a full screen, at synchronized frame rate or at maximum, with varying "sleep" times. This has worked much better than all proposed "main thread" render loop proposals so far.

  11. sapropel says:

    i was going to try it out, but where did you get that WindowMessage enum/struct/class/whatever from? the one inside the Message struct declaration.

    thanks []

  12. sapropel says:

    also, why the use of SuppressUnmanagedCodeSecurity? theres no need for that (i think).

    and where is that CharSet.Auto from? the only one i know is CharacterSet, and it has no .Auto

    also, could you post a complete working example please? something really simple like device.Clear(…); device.Present();

    i managed to compile it by removing the CharSet=CharSet.Auto and chaging the public WindowMessage msg; Message struct member to public int msg; (since i dont know where that WindowMessage is), but i dont know if it is as good as yours.

    again thanks 🙂

  13. Deezer says:

    Is there anywhere a newbie can go to view VB.NET solutions to the issues that started this issue applies to VB.NET Managed DirectX coding too?

    Everything about Managed DirectX samples and blog chats is infuriatingly C# centric. Am I simply choosing the wrong language if I wish to learn to use Managed DirectX? The utter lack of VB.NET samples even in the DirectX SDK itself, not to mention no talk of how this render loop issue here is implemented in VB.NET, suggests VB.NET is indeed a poor language choice.

    Any pointers to a good VB site covering this issue would be very welcome.

  14. Mort says:

    I hate to sound stupid but what #using’ do you need with that.

    I copied the code in to a blank project and I get compile errors.

    Thanks

    Mort.

  15. T-T says:

    Wassup with all that C# Code?

    Forgot about vb have we?

  16. akshay says:

    The PeekMessage loop has been in use for ages by game programmers who code in unmanaged DirectX and even OpenGL. What surprises me is that it took such a long before someone was able to figure it out for managed dx!

  17. Anonymous says:

    I put the using directive System.Runtime.InteropServices and that solved all of the errors except for one that says:

    The type or namespace name ‘WindowMessage’ could not be found (are you missing a using directive or an assembly reference?)

    I’ve looked in the MSDN and all over the web, and I cannot find the namespace it is in. Thank you for your help.

  18. mimfeld says:

    I can only guess this works – since I cannot get it to run. Reason for this being that I – as an average programmer – simply have no idea what namespaces / references to include.

    What type is WindowMessage? IntPtr? (I tried looking for WindowMessage in MSDN to no avail).

    System.Drawing.NativeMethods seems to be an internal class. Consequently I get compilation errors when trying to compile the code. What am I missing?

    Might be I am the only one that plays around with MDX without a complete understanding and knowledge of the .net framework, at least to my very limited mind a complete code sample would be extremely helpful.

    Don’t get me wrong, I am not critizing here. It’s just that I have very limited ressources (both time and brain 😉 )

  19. Akshay says:

    I have made a sample framework app using the loop you have suggested here. It does work better than the original SDK loop. It is located <a href="http://photongl.blogspot.com">here</a&gt;.

  20. John says:

    I’m wondering how much of a performance difference will be if I take out the AppStillIdle while loop and just call the update and render methods within OnApplicationIdle.

    Tom, do you have any figures on this?

  21. ChrSmith says:

    That looks great. I am new to DirectX, but I remember back when doing OpenGL that the main render loop was the most difficult part- especially trying to balance always redrawing without overworking the CPU.

    Could you provide the source for the C# version of the WindowMessage struct as well? I am having difficulty getting this to compile since I assume that structure is defined else where in your code. (Is it defined somewhere in the managed source for the April MDX SDK update?)

    Thanks,

    -Chris

  22. HopeDagger says:

    Simply put: Yuck. That’s not simple nor elegant. :/

  23. Exabyte256 says:

    Hrm. The Message struct is already defined by the .NET libraries as:

    System.Windows.Forms.Message

  24. I have checked in a new initial version of the Client UI which is based on the OnApplicationIdle style…