2
\$\begingroup\$

I've used this piece of code a lot in my games, but I still don't know exactly how it works.

 // Main loop
while (!done) {
     // Prepare for rendering the next frame
     // ...

     // Render single frame
    do {
        // The following loop ensures that the contents of the drawing buffer
        // are consistent in case the underlying surface was recreated
        do {
            // Get a new graphics context every time through the loop
            // to make sure the strategy is validated
            Graphics graphics = strategy.getDrawGraphics();

            // Render to graphics
            // ...

            // Dispose the graphics
            graphics.dispose();

            // Repeat the rendering if the drawing buffer contents
            // were restored
        } while (strategy.contentsRestored());

        // Display the buffer
        strategy.show();

        // Repeat the rendering if the drawing buffer was lost
    } while (strategy.contentsLost());
}

Why should I use those two do-while loops? What does it achieve? Well, I know why because of the comments, but I want to know exactly what happens

BufferStrategy: http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferStrategy.html

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

BufferStrategy will often use VolatileImage for the buffer. Part of the use case of volatile image is that its backing buffer may be lost without warning. This require you to rerender to the volatileImage.

What you can do as an optimization is test both contentsLost and contentsRestored inside the inner while loop and repeat the loop using continue if either are true (disposing the graphics object as needed):

Graphics graphics = strategy.getDrawGraphics();
try{
    background.render(graphics);

    if(strategy.contentsRestored() || strategy.contentsLost()){
        continue;
    }

    renderEntities(graphics);
} finally {
    graphics.dispose();
}
\$\endgroup\$
1
  • \$\begingroup\$ So, just to be clear, contentsLost checks if the buffer is lost, contentsRestored checks if it is restored, right? Why is it that you should check for both? Isn't checking for contentsLost enough? \$\endgroup\$
    – userx01
    Apr 11, 2015 at 12:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .