In a previous post , I detailed a double-buffering
implementation written in C. The idea behind double buffering is to draw graphics off-screen, then quickly swap
(or “flip”) this off-screen buffer with the visible screen. This technique reduces flickering and provides smoother
rendering. While the C implementation was relatively straightforward using GDI functions, I decided to challenge myself
by recreating it in assembly language using MASM32.
There are some slight differences that I’ll go through.
First up, this module defines some macros that are just helpful blocks of reusable code.
szText defines a string inline
m2m performs value assignment from a memory location, to another
return is a simple analog for the return keyword in c
rgb encodes 8 bit RGB components into the eax register
Setup
The setup is very much like its C counterpart with a registration of a class first, and then the creation of the window.
The szClassName gives us a reference to the name of the class to use.
Message pump
We continue to render out to the window in a loop:
Using InvalidateRect tells the window that there is an update to draw. This is then propagated through the WM_PAINT
message.
Window proc
Each of the window messages is handled in a switch/case like arrangement with a series of cmp and je instructions.
In higher level MASM this can be handled using the .IF syntax.
We use the WM_CREATE, WM_SIZE, and WM_DESTROY messages to control when we create and destroy our back buffer.
WM_PAINT only needs to worry about drawing the backbuffer to the window.
Handling the buffer
The routine that handles the back buffer construction is called RecreateBackBuffer. It’s a routine that will clean
up before it trys to create the back buffer saving the program from memory leaks:
DestroyBackBuffer being the first thing called here; it’s just a basic clean up:
Flipping
When we want to draw that back buffer to the window, we just use BitBlt from the GDI:
Conclusion
This is just a different take on the same application written in C. Some of the control structures in assembly language
can seem a little hard to follow, but there is something elegant about their simplicity.