Sign in to follow this  
XTAL256

OpenGL When to draw and swap buffers

Recommended Posts

XTAL256    106
I am currently making the graphical user interface (GUI) for my game using OpenGL (C++, VS2005). I have Window objects which have an array of Component objects. These can be Buttons, CheckBoxes, etc. Each component (Window is also a subclass of Component) has a draw() function which draws the images. For testing, i just call the draw function for my window in the WinMain loop:
while(!done) {
    if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
        if (msg.message==WM_QUIT) {
            done = TRUE;
        }
        else {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    else {
        clearScreen();
        // Test
        screen.draw();
        SwapBuffers(hdc);
    }
}

Don't worry about what that code does, it's not really important. What i want to know is where to put SwapBuffers(hdc);. If i draw everything in the loop, it will use 100% CPU. I want to only draw when an event occurs such as moving the mouse over a button or pressing a key. I have made an event system which using Windows' WNDPROC function to get events then passes those events to all Components that listen for events. Now, i only want to call draw() for each component when it gets an event. But how do i know when to swap buffers? If this cannot be done i could have two separate graphics contexts; one double buffered for drawing my game scenes, the other single buffered for drawing the GUI.

Share this post


Link to post
Share on other sites
purpledog    163
It can be a bit hard to update the buffer as you'll need a pretty good knowedge of damaged area so that when the UI is updated, you can erase the dirty area (by replacing it by "game" content), and then draw the updated area. In terms of code complexity, this approach needs careful attention as it can easily lead to dirty code (yes, I've been there :-)

An easier approach is to use offscreen buffer (fbo) and render the game content in one of them and the UI is the other. That way you are making the update event much coarser: "update game" or "update UI".
The entire scene is rendered by compositing the two layers.
That's more expensive than the first solution but so much easier to implement.

Another drawback of the second approach is the "double-buffer" issue. Basically you'll be tempted by duplicating ressources to hide more of the hideous latency. For instance, you might want to double buffer the "game content fbo".
That might turn out to be a good idea but I suggest to start with everything thing singled-buffered (expect the main buffer) and eventually optimize afterward.

Share this post


Link to post
Share on other sites
XTAL256    106
I don't really know how to use offscreen buffers but would it be just as good to create two separate rendering contexts (HDC and HGLRC). 'cos that's easy, i can just make my graphics class non-static and create two objects of the class.

Share this post


Link to post
Share on other sites
V-man    813
I would keep that code and just add sleep(howmuch) and continously measure the FPS and adjust howmuch until I get 60FPS.
That will reduce the CPU usage to 1-5%.
I don't recommend that while the game is running! Only do this for your game menu.

Share this post


Link to post
Share on other sites
XTAL256    106
I thought i would try using a single buffer for the UI just to see what it's like but i can't get it to work. I removed the PFD_DOUBLEBUFFER flag from the PIXELFORMATDESCRIPTOR and removed the call to SwapBuffers() but nothing gets drawn. How do i do it? btw, I am using Windows and OpenGL.

Share this post


Link to post
Share on other sites
Decrius    100
I suggest you redraw the GUI when something happened. Just redraw it completely. So whenever the mouse moves, or keys get hit. You can also filter events that have no effect to the GUI, but thats up to you. Only drawing when events are thrown reduces CPU dramatically (except if the user is moving the mouse insanely much)

This is what I do with SDL combined with OpenGL.

I'm working on the GUI aswell, and my code became LONG. Now I decided to make external text files which will decide the GUI's content, only need a parser and display functions, instead of endless code hardcoding button positions etc. The GUI is taking more time already than my game engine ^^ (using a 2D tile-based game).

PS: whats so bad in delaying 1 ms every frame in-game? I made it an option in this manner:

Normal - Low CPU - VSync

where users can choose one of them...I prefer the latter 2 though...

Share this post


Link to post
Share on other sites
XTAL256    106
Quote:
Original post by Decrius
I suggest you redraw the GUI when something happened. Just redraw it completely.

Yes, that's what i am trying to achieve. Except i was only going to draw the component that changes, not because it better but actually because it's easier. My event code calls a function in each component that listens for events. So when such an event occurs (say, clicking the mouse), each button gets that event and then calls it's draw() function. Now if i were to completely redraw everything, i would have to know what components are currently on the screen. It can be done but i would have to change my code a bit.

Quote:
Original post by Decrius
Now I decided to make external text files which will decide the GUI's content...

I'm just hardcoding my button positions and stuff but i am using an XML file to describe the GUI styles, fonts, etc. Some people told me that it's overkill and that i can just hardcode all that stuff in but i find it much easier. Not only can i easily change something without the need to re-compile but other users can create their own custom GUI theme/style, which is a feature that i personally like about a program.

Quote:
Original post by Decrius
PS: whats so bad in delaying 1 ms every frame in-game?

Well, i haven't even started coding the actual game (i haven't even though about how i will do it). But i would like to have a function that does all my game rendering and stuff, and that function gets called by a timer 30 times per second (for 30fps). I don't want to draw my GUI in that function because it won't even be running if game hasn't started and the user is just in the menu. I want my GUI and game to be separate.
But if that is too hard then i will just do it all in one place and delay 1ms or something.

Share this post


Link to post
Share on other sites
XTAL256    106
Hi again. I have decided that could swap the buffers after everything i draw, and if i don't clear the screen i only have to redraw the components that need redrawing. At first i didn't think this would work but double buffer or not i can still draw only when an event occurs, i just can't draw after i swap buffers cos that's when you get flickering. So all i have to do is put SwapBuffers(hdc) after i draw a component.
Also, is it ok to do drawing in two separate threads? Is there a good way of doing this? Because i am planning on using a timer to update the drawing of the game and GUI drawing will be done in the event thread.

EDIT: doesn't work. All i get is a black screen (from initially clearing the screen). Event functions are called, which draw stuff and call SwapBuffers, but nothing. If it's possible to do it this way (which i want to do), i can upload the full source so you can check it out.

[Edited by - XTAL256 on May 9, 2008 8:27:03 PM]

Share this post


Link to post
Share on other sites
wlw_wl    146
Quote:
Original post by XTAL256
I thought i would try using a single buffer for the UI just to see what it's like but i can't get it to work. I removed the PFD_DOUBLEBUFFER flag from the PIXELFORMATDESCRIPTOR and removed the call to SwapBuffers() but nothing gets drawn. How do i do it? btw, I am using Windows and OpenGL.


haven't you forgot to glFlush(); when you deleted buffer swapping?

Share this post


Link to post
Share on other sites
XTAL256    106
Hmm, when do you need to use glFlush? And why don't you need to do that when double buffering?
Anyway, i have decided to just do what V-man and Decrius suggested and just render every 30ms or so. I am currently having problems with that but i should be able to get it sorted out.

EDIT: btw, glFlush worked for single buffering, thanks. And, strangely, there was no flickering or anything, is that because of OpenGL doing something? Anyway, depending on how things go, i may use single buffering for the GUI and double buffering for the game.

Share this post


Link to post
Share on other sites
wlw_wl    146
The idea is that any drawing you make in your drawing function is no happening directly on the screen, you are in fact altering the buffer. So, when you're done with drawing, you need to output that buffer onto the screen, which is what is called flushing. When you are using double buffering you don't need to flush the buffer, beacuse the SwapBuffers function does it for you.
That is why when you use single buffering, you need to do that manually or nothing will be drawn, everything will stay in the buffer.

Share this post


Link to post
Share on other sites
XTAL256    106
Quote:
Original post by XTAL256
Anyway, i have decided to just do what V-man and Decrius suggested and just render every 30ms or so. I am currently having problems with that but i should be able to get it sorted out.

Ok, i need help [grin]. I am using a timer (SDL) to render each frame but for some reason nothing is being drawn (just garbage on the screen).

UINT render(UINT interval, void* param) {
clearScreen();
Component::drawScreen(); // Draw the GUI on screen
SwapBuffers(hdc);
return interval;
}

thread::Timer timer(render, 30);

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdLine, int wndState) {
MSG msg; // Windows message structure
BOOL done = FALSE; // Bool variable to exit loop

// Create our OpenGL window, initiate SDL components and graphics
try {
initWindow(false);
initSDL();
initGraphics(hdc);
}
catch (Error e) {
displayError(e);
done = TRUE;
}
guiLoadData();
PlayerScreen screen;
timer.start(); // <-- i start the timer here
while(!done) {
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
if (msg.message==WM_QUIT) {
done = TRUE;
}
else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
// shutdown stuff
}

/// Timer.h ///////////////////////////////////////
class Timer {
public:
SDL_TimerID id;
unsigned int interval;
bool isRunning;

Timer(UINT (*funcPtr)(UINT, void*), int interval, bool run = false);
~Timer();

UINT (*funcPtr)(UINT, void*);
void start();
};

/// Timer.cpp /////////////////////////////////////
Timer::Timer(UINT (*funcPtr)(UINT, void*), int interval, bool run) {
this->funcPtr = funcPtr;
this->interval = interval;
this->isRunning = run;
if (run)
start();
else
this->id = NULL;
}

Timer::~Timer() {
SDL_RemoveTimer(id);
}

void Timer::start() {
this->id = SDL_AddTimer(interval, funcPtr, NULL);

if (this->id == NULL)
throw TimerError("Could not initiate timer");
}


I have tested the timer and it works, it calls render after i start it. And the drawing code works fine if i have it in the while loop (as an 'else' to 'if(PeekMessage...)').
Is it ok to call OpenGL operations from a separate thread/timer?

Share this post


Link to post
Share on other sites
XTAL256    106
I just tested the render function running in an SDL_Thread and still nothing, just a blank screen.
Ok, i just realised what's happening. When i was doing some debugging before i noticed that code in the main while loop was being executed before code in the thread. I guessed that the loop was receiving a lot of messages like WM_CREATE (?) and that had priority over the thread (or had equal priority but was scheduled first). Anyway, i realised that i started the thread before the loop was entered. So although i started it after OGL and window was initialised, well i don't actually know what is happening. But what i did was put timer.start() after the loop, and when i quit i saw a little flicker of my GUI being drawn. So when do i actually need to start rendering the screen?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By pseudomarvin
      I assumed that if a shader is computationally expensive then the execution is just slower. But running the following GLSL FS instead just crashes
      void main() { float x = 0; float y = 0; int sum = 0; for (float x = 0; x < 10; x += 0.00005) { for (float y = 0; y < 10; y += 0.00005) { sum++; } } fragColor = vec4(1, 1, 1 , 1.0); } with unhandled exception in nvoglv32.dll. Are there any hard limits on the number of steps/time that a shader can take before it is shut down? I was thinking about implementing some time intensive computation in shaders where it would take on the order of seconds to compute a frame, is that possible? Thanks.
    • By Arulbabu Donbosco
      There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window. 
      I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.
      anyone, please help me .. how to go further... to create an application like VR CAVE. 
       
      Thanks
    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
       
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      http://www.informit.com/articles/article.aspx?p=2120983
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
      Thanks!
  • Popular Now