Skip to Content
The Alchemy Project

The system library

The system library is the runtime foundation of Golden Sun: The Lost Age.

Whenever the Game Boy Advance is powered on, Felix walks across Daila, the Lemurian Ship sails, a fight takes place in the Kandorean Temple, or the quest is saved, the same small set of system routines keeps the console running. The library owns startup, five cold-start gameplay engines, the caller-stack sySynch() tick loop, 24 event slots, compressed scene overlays, atomic 12 KB flash saving, and link-cable I/O.

Camelot kept the same four core runtime ideas from The Broken Seal and refined each one to fit a cartridge twice the size. The rest of the codebase is far easier to follow once these four ideas are understood.

1. The engine loop and cold starts

Felix walks through a cave in the Kandorean Temple until a random battle with an Angle Worm starts, wins, and returns to the same spot
Felix walks through a cave in the Kandorean Temple until a random battle with an Angle Worm starts, wins, and…

Power-on and soft reset (A + B + Select + Start) both start at syInit in system_start_up.c. It clears RAM, copies hot ARM routines into fast on-chip IWRAM (32 KB), turns on interrupts, and enters gmMainRoutineRun in game/main_routine.c, which never returns.

gmMainRoutineRun is a coarse engine loop, not a frame-by-frame loop. Each pass runs one complete gameplay engine to completion and then launches the next one:

  • Field engine: Runs one scene until the party leaves or requests another engine. Towns, dungeon floors, the World Map, the Title Screen, the File Screen, and the Battle Arena lobby all run as field scenes.
  • Battle engine (ENGINE_BATTLE): Runs one fight and writes back whether the party won, fled, or lost.
  • Minigames: Runs Lucky Dice (ENGINE_LUCKY_DICE), Lucky Wheels (ENGINE_LUCKY_WHEELS), and The Lost Age's new Super Lucky Dice (ENGINE_SUPER_LUCKY_DICE) inside Contigo's tent.
  • Menus, shops, and the forge are not engines. They are blocking C functions called from inside the field engine, and they return directly to their caller.

Between every two engines, gmMainRoutineRun resets the runtime state. It clears the event callback table, resets both bump allocators (IwramHeap in 32 KB fast RAM and EwramHeap in 256 KB main RAM, each handing out memory in the manner of a stack), stops looping sounds, and turns off scanline (HBlank) effects. Returning from a Kandorean Temple random battle rebuilds the cave from scratch rather than resuming it from RAM.

Only four persistent global blocks outside the heaps survive an engine change:

  • MainRoutineStateWork: Party order, coins, play time, settings, Sunshine's Forge state, the next engine or destination, and the last engine's outcome.
  • GameFlags: 4,096 boolean bits managed by system_flags.c, including two 256-bit temporary ranges that clear themselves (RPG Data & Rules).
  • CharacterUnits: Persistent 332-byte UNIT stats, inventory, Djinn, and Psynergy records for all eight playable characters.
  • SnapshotObjects: Saved positions and facings of every actor in the current scene, captured before entering battle or writing a save.

The fight with Obaba in the caverns above Champa is an example. The cutscene script writes win and loss destinations into MainRoutineStateWork, requests ENGINE_BATTLE, and lets the field engine finish. The battle engine holds no knowledge of Champa. When the fight ends, gmReturnFromEngine checks the result and launches a fresh field engine at the matching destination.

2. Waiting (sySynch) and events

Felix talks to the man by the pond in Daila: a dialogue box opens at the top of the screen, types two pages with a bobbing advance arrow, and closes
Felix talks to the man by the pond in Daila: a dialogue box opens at the top of the screen, types two pages…

Rather than an inverted top-level frame loop, The Lost Age places its tick loop inside one blocking function, sySynch(Sint32 ticks) in system_frame.c:

void sySynch(Sint32 ticks)
{
    for (Uint32 i = 0; i < (Uint32)ticks; i++)
    {
        syExecuteEvent(EVENT_PASS_TICK);      /* run tick-pass callbacks, highest priority first */
        syRenderBuildOAMList(...);            /* flatten depth-sorted sprites into shadow OAM */
        TickRenderPending = 1;                /* mark this tick ready for VBlank */
        syWaitForVBlankInterrupt();           /* run music ramps & mix audio ahead of VBlank, then wait */
        /* clear OAM buckets, increment TickCount, update key repeat & idle sleep */
    }
}

Calling sySynch(10) runs ten full game ticks inline and returns to the next line of C. Unlike The Broken Seal, TLA's sySynch() runs events on the caller's stack without relocating it. Its syWaitForVBlankInterrupt() helper also runs music ramps (sySoundUpdateBGMRampsStub) and mixes audio (IwramSoundRenderVBlank) proactively before waiting for VBlank instead of calling BIOS Halt.

In the terms of coroutines, foreground C is the one coroutine, and sySynch() is its yield and scheduler in one. A night at Daila's inn is written as a plain sequence: fade to black, play the jingle and wait for it to finish, restore HP and PP, and fade back in. No state machine records how far through the night the party is. The position in the code is the memory.

Events versus actor scripts

An event (EVENT in EventBuf, expanded to 24 slots in TLA) is a registered per-tick C callback. It is not a cutscene (cutscenes are blocking C sc* scripts). TLA swaps the two pass priority bands relative to TBS so that EVENT_PASS_VBLANK = 0xC80 sits ahead of EVENT_PASS_TICK = 0x480 in descending-priority EventBuf. Because of that swap, the VBlank interrupt handler scans from slot 0 and exits immediately on the first tick-pass event instead of walking the rest of the table.

Four rules keep this deterministic:

SC_ANIMATION(2),          /* walk */
SC_WANDER_HOME(4, 8, 16), /* pick a spot near home and head for it */
SC_SYNC,                  /* stay on this line until arrival */
SC_ANIMATION(1),          /* stand */
SC_WAIT(20),              /* count down 20 ticks inside this actor */
sySynch(20) in CSC_WAIT(20) in an actor script
What it isBlocking function running 20 game ticksBytecode order storing a countdown of 20 in the actor
Who uses itForeground code (engines, scripts, menus, shops, battle effects)Each of the 64 field actors independently
Blocks other work?Pauses the caller while tick events keep runningNo, the actor event decrements the counter and moves on
How many at onceOne active call stack (can nest arbitrarily deep)Up to 64 actors pausing in parallel

Concurrent actions and every way of taking time

To move two characters together from foreground C (such as the two guards closing ranks on Madra Drawbridge), a script starts them with non-blocking calls and waits once:

fdActorWalkTo(ACTOR_WEST_GUARD, 148, 252);        /* starts walk, returns at once */
fdActorWalkToAndWait(ACTOR_EAST_GUARD, 170, 252); /* starts walk, loops sySynch(1) until arrived */
fdActorWaitForMoveById(ACTOR_WEST_GUARD);         /* waits until west guard also arrives */

fdActorWalkToAndWait gives up after 600 ticks (10 seconds), so that a blocked actor can never soft-lock a cutscene.

Written asWhereWhat it does
sySynch(n)Foreground CRuns n ticks inline and returns
fdScriptWait(n)Scene scriptCalls sySynch(n) (skipped if DebugMode fast-forward is active)
fdScriptShowMessage / *AndWaitScene scriptStarts an action and loops sySynch(1) until done (600-tick cap on walks)
SC_WAIT(n)Actor scriptSets a per-actor countdown decremented once per tick
SC_SYNCActor scriptHolds the actor script until movement arrives
Counter in subsystem stateEvent callbackChecked once per tick (mid-line text pauses, battle hit flashes)

A talk, tick by tick

Felix walks up to the man by Daila's pond and A is pressed:

  1. fdEngineRun sits in its walking loop calling sySynch(1) repeatedly. It is the only foreground code waiting.
  2. Inside one sySynch(1), fdActorUpdateAllOnField reaches Felix (SC_PLAYER), sees A, and records a request in RamHeapSlots->fieldState. It then ticks the villager's SC_WAIT countdown down by 1.
  3. sySynch(1) returns. fdEngineRun sees the request, switches Felix to the idle script, finds the villager in reach with a matching CUE_TALK row, and starts the talk. Zero ticks have passed.
  4. The talk handler pauses the villager, turns both characters to face each other, and requests a dialogue window (mnWindowCreate), which returns at once.
  5. Foreground code loops sySynch(1) until the window closes. Each tick, mnWindowSystemUpdate grows the box, types glyphs, and watches for A, while the paused villager's SC_WAIT stays frozen.
  6. Pressing A shrinks and closes the box, ending the loop. The villager unpauses, Felix returns to SC_PLAYER, fdEngineRun resumes walking, and the villager's countdown resumes from where it stopped.

When nothing waits: VBlank and slowdown

During a tick, game code fills RAM buffers and queues hardware register changes through syIOWriteQueueStore*. At every ~60 Hz hardware VBlank, syVBlankHandler refreshes DMA sound buffers (SoundDriverVSyncRefresh), commits finished ticks atomically when TickRenderPending is set, runs VBlank-pass events (stopping at the first tick-pass entry), polls buttons, and increments FrameCount. It also runs IwramSoundRenderVBlank as a fallback whenever a heavy tick overruns a frame without reaching syWaitForVBlankInterrupt().

If a heavy tick runs longer than one frame, VBlank shows the previous frame again. The result is tear-free slowdown while music holds exact tempo. Code that stopped calling sySynch() would leave a still picture on screen while the music continued to play.

3. Compressed scene overlays

All 325 scenes' dialogue, cue tables, and cutscenes are stored compressed inside the 2,048-row resource directory as 114 -Os overlays. Related places often share one overlay, such as the three scenes of Suhalla Gate.

On scene entry, syOverlayLoad unpacks the overlay into a fixed 32 KB EWRAM buffer (0x02008000) and patches its long branches, overwriting the previous one. Overlays never call each other directly. Shared helpers in scene/shared/ compile into each overlay that includes them. The resident main image queries the active overlay through a fixed 7-stub entry table (scene/entry.s, which adds scPrepareMap over TBS's 6), and the overlay calls back through a build-generated import table at its end.

4. Atomic 12 KB copy-on-write flash saving

Felix opens the Pause menu in Daila, picks Save your quest, chooses slot 1, and confirms the 12 KB atomic flash write
Felix opens the Pause menu in Daila, picks Save your quest, chooses slot 1, and confirms the 12 KB atomic…

A save file stores the four blocks that survive an engine transition: GameFlags, MainRoutineStateWork, CharacterUnits, and SnapshotObjects (captured fresh as saving begins).

On the cartridge's 64 KB flash chip (sixteen 4 KB sectors), each of the three save files occupies one 12 KB copy spanning 3 contiguous sectors. The chip fits 5 such 12 KB slots, leaving 2 spare slots free at all times. syBupWritePart writes the new copy with a higher sequence counter and checksum into a spare slot, verifies it by reading it back, and only then retires the prior slot. If power fails mid-save, the previous save remains intact.

Code reference