Skip to content

3. Dissecting the code (and hardware)

N•I•L edited this page Nov 24, 2021 · 6 revisions

Let's take a look at the simplest program that can be compiled with devkitARM + ndslib:

#include <nds.h>

int main()
{
    while(1)
    {
        swiWaitForVBlank();
    }
    return 0;
}

Let's take every (interesting) line of code apart:

#include <nds.h>

The header nds.h is a part of libnds and includes implementations of basic hardware manipulation routines all the low-level stuff like addresses/registers definitions, constants, flags declarations etc.

while(1)

Nothing special to those familiarized with game development. For the curious ones, all the game logic must be run in an infinite loop, where on each step you check the user input, update your game data (e.g characters position) and render your graphics to display them on screen. This is what that while(1) or while(true) is responsible for. Usually, a single step in the loop takes ~ 1/60th of a second, so we are allowed to render at most 60 frames on every second (this is where the notion of fps comes from, isn't it?).

swiWaitForVBlank();

This is something specific to the old-days displays, whose Video memory (VRAM) cannot be accessed while the screen is drawing/refresing. The screen is updating line by line and pixel by pixel starting from the top-left corner (coordintates 0,0) and all the way until the bottom right of the screen (in DS's case, of the bottom (touch-)screen). For this reason, there exists a small blank period between two consecutive screen updates, called Vertical Blank, or VBlank, when the VRAM can be accessed by the CPU in order to draw something new (a map, a sprite etc). This is where swiWaitForVBlank comes in handy to make the CPU wait for te display to finish refresing in order to update the VRAM without unexpectedly corrupting things.

return 0;

Normally a consistent program shouldn't get here, because that means stopping execution and freezing the console. We're talking not about a PC, but a poor 2004 DS for whom end of execution means physically turning off the console. Therefore no need for main return 0. Some emulators like DeSmuME report the situations where the execution stops via return instruction.