DoubleBuffers and SwapBuffers
It takes a significant amount of time to finish drawing a scene.
This makes a complex scene suffer from an effect called "screen tearing" - Which means that the animation will not be smooth,
as if some one is tearing the screen to display the next image.
Lets see what happens when the graphic content is displayed as soon as it is drawn...
Single buffer displays the unfinished drawing
But, if a back buffer is used to draw the scene in the background...
then it is possible to display only the finished image (and thus avoiding the display of the unfinished image).
So, its a good idea to do the drawing in the background and display the contents only after the drawing has been finished.
(Left) Back buffer is used to draw ... Front buffer is displayed (Right)
...
Double buffer displays only the finished drawing (Right)
How double buffering works?
In an overly simplified manner, double buffering works something like this...
- Graphics application will maintain two buffers... Buffer1 and Buffer2.
- One buffer is used for drawing, and the other buffer is used for displaying.
- Drawing means updating(writing) the pixel color values into the buffer.
- Displaying means transfering(reading) the pixel color values to the screen.
- Initially, Buffer1 is treated as back(write) buffer and Buffer2 is treated as the front(read) buffer.
- Once the drawing is finished, the buffers are swapped. Back buffer becomes front buffer and vice versa
- Drawing is done on the new back buffer. And this draw+swap loop is repeated untill the application exits.
This mechanism is illustrated in the following table...
Frame |
Buffer1 |
Buffer2 |
Display |
0 |
Back buffer |
Front buffer |
Buffer 2 |
1 |
Front buffer |
Back buffer |
Buffer 1 |
2 |
Back buffer |
Front buffer |
Buffer 2 |
3 |
Front buffer |
Back buffer |
Buffer 1 |
4 |
Back buffer |
Front buffer |
Buffer 2 |
... |
... |
... |
... |
And the loop continues...