Sign in to follow this  

OpenGL When to draw and swap buffers

This topic is 3533 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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
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
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
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
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
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
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
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
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
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
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
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

This topic is 3533 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
       
      #define NUM_LIGHTS 2
      struct Light
      {
          vec3 position;
          vec3 diffuse;
          float attenuation;
      };
      uniform Light Lights[NUM_LIGHTS];
       
       
    • By pr033r
      Hello,
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article (http://natureofcode.com/book/chapter-6-autonomous-agents/) inspirate from another code (here: https://github.com/jyanar/Boids/tree/master/src) but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch): https://github.com/pr033r/BachelorProject/tree/Optimalizing
      Exe file (if you want to look) and models folder (for those who will download the sources):
      http://leteckaposta.cz/367190436
      Thanks for any help...

    • By Andrija
      I am currently trying to implement shadow mapping into my project , but although i can render my depth map to the screen and it looks okay , when i sample it with shadowCoords there is no shadow.
      Here is my light space matrix calculation
      mat4x4 lightViewMatrix; vec3 sun_pos = {SUN_OFFSET * the_sun->direction[0], SUN_OFFSET * the_sun->direction[1], SUN_OFFSET * the_sun->direction[2]}; mat4x4_look_at(lightViewMatrix,sun_pos,player->pos,up); mat4x4_mul(lightSpaceMatrix,lightProjMatrix,lightViewMatrix); I will tweak the values for the size and frustum of the shadow map, but for now i just want to draw shadows around the player position
      the_sun->direction is a normalized vector so i multiply it by a constant to get the position.
      player->pos is the camera position in world space
      the light projection matrix is calculated like this:
      mat4x4_ortho(lightProjMatrix,-SHADOW_FAR,SHADOW_FAR,-SHADOW_FAR,SHADOW_FAR,NEAR,SHADOW_FAR); Shadow vertex shader:
      uniform mat4 light_space_matrix; void main() { gl_Position = light_space_matrix * transfMatrix * vec4(position, 1.0f); } Shadow fragment shader:
      out float fragDepth; void main() { fragDepth = gl_FragCoord.z; } I am using deferred rendering so i have all my world positions in the g_positions buffer
      My shadow calculation in the deferred fragment shader:
      float get_shadow_fac(vec4 light_space_pos) { vec3 shadow_coords = light_space_pos.xyz / light_space_pos.w; shadow_coords = shadow_coords * 0.5 + 0.5; float closest_depth = texture(shadow_map, shadow_coords.xy).r; float current_depth = shadow_coords.z; float shadow_fac = 1.0; if(closest_depth < current_depth) shadow_fac = 0.5; return shadow_fac; } I call the function like this:
      get_shadow_fac(light_space_matrix * vec4(position,1.0)); Where position is the value i got from sampling the g_position buffer
      Here is my depth texture (i know it will produce low quality shadows but i just want to get it working for now):
      sorry because of the compression , the black smudges are trees ... https://i.stack.imgur.com/T43aK.jpg
      EDIT: Depth texture attachment:
      glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24,fbo->width,fbo->height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fbo->depthTexture, 0);
  • Popular Now