[2-14-18] BlitzBASIC: Buffer Manipulation

There is at least one decently useful feature of BlitzBASIC that doesn't seem to show up in any of the modern languages I've seen, that feature being buffer manipulation.

BlitzBASIC forces/allows you to use the graphics buffers freely, which is both a blessing and a curse at times. However, at this point you may or may not be wondering exactly what buffer manipulation is. That is why I will now explain the three buffers: front, back, and image.


The Front Buffer

Essentially, buffers are like big canvases onto which your program draws. The front buffer is the buffer that your user will see when using your program. Now, we could draw directly to the front buffer, but then the user would see it being drawn. This means that the user will see the program placing images and pixels, which leads to visible scan lines and flickering sprites. I will demonstrate using a tampered version of Quest Guy:

As you can see, drawing to the front buffer, or single-buffering, is not a good idea if you plan on having graphics. This is why we use the back buffer.

The Back Buffer

Thanks to the back buffer, we are able to avoid these graphical errors by only showing buffers after they've been drawn, or double-buffering. Essentially, the back buffer goes unseen in the background. We tell our program to draw on this buffer, then "flip" it into the front buffer when it's ready. This way the player doesn't see the graphics being drawn. Here's another demonstration:

The code would look like this:


Graphics 800, 600, 16, 3 ;800x600 scaleable window
SetBuffer BackBuffer() ;tell our program to draw to the back buffer

Repeat ;main loop
	
	;draw images
	
	Flip ;copy the back buffer to the front buffer
Until KeyHit(1) ;until the user hits escape

It should be noted that the Flip function does not clear the back buffer, it only copies it. If you want to clear the back buffer, you have to use the Cls function.

The Image Buffer

The image buffer is probably the only reason the buffer manipulation system is beneficial, considering the fact that you need to remember to double-buffer in every game with any images. Unlike the other two buffers, the image buffer allows you to draw to any image loaded into memory. This even allows you to create and draw sprites within your program, which could potentially prevent image tampering when using simple graphics.


square = CreateImage(20,20)
SetBuffer ImageBuffer(square)
Rect(0,0,20,20,1) ;this will make "square" an image of a 20x20 square