Skip to Content
The Alchemy Project

The system library

The system library is the foundation underneath Golden Sun: The Broken Seal.

Whenever the Game Boy Advance is switched on, Isaac walks through Vale, a battle is fought in Goma Cave, or the quest is saved, the same small set of system routines keeps the console running. The library owns power-on setup, top-level engine switching, the blocking tick loop, the 20-slot event table, temporary heaps, compressed scene overlays, atomic flash saving, and link-cable I/O.

Camelot built this runtime around four ideas. With those four understood, almost every file in the codebase becomes readable, because even long cutscenes and multi-layered menus follow the same rhythm.

1. The engine loop and cold starts

Isaac walks through Goma Cave until a random battle starts, wins the battle, and returns to the same spot in the cave
Isaac walks through Goma Cave until a random battle starts, wins the battle, and returns to the same spot in…

Power-on and soft reset (A + B + Select + Start) both begin at syInit in system_start_up.c. It clears RAM, copies fast ARM routines into on-chip IWRAM (32 KB), enables hardware interrupts, and calls 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 from start to finish, reads its result, and launches the next one:

  • Field engine: Runs one scene until the party takes an exit or starts another engine. Towns, dungeon floors, the World Map, the Title Screen, the File Screen, and the Battle Arena all run as field scenes.
  • Battle engine (ENGINE_BATTLE): Runs one complete fight and writes back whether the party won, fled, or lost.
  • Lucky Dice (ENGINE_LUCKY_DICE) and Lucky Wheels (ENGINE_LUCKY_WHEELS): Run Tolbi's two minigames as standalone engines.
  • Menus and shops are not engines. They are ordinary blocking C functions called from inside the field engine, and they return directly to their caller.

Between every two engines, gmMainRoutineRun resets the runtime. It clears the event table, resets both bump allocators (IwramHeap in 32 KB fast RAM and EwramHeap in 256 KB main RAM, each handing out memory like a stack of plates), stops looping sounds, and turns off scanline (HBlank) effects. When the party leaves Goma Cave for a random battle and wins, the cave is torn down before the fight and rebuilt from scratch on return.

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

  • MainRoutineStateWork: Party roster and UNIT stats, coins, play time, settings, the next engine or destination, and the last engine's outcome.
  • GameFlags: 4,096 boolean bits remembering chests, Djinn, and story progress, including two 256-bit temporary ranges that clear themselves (RPG Data & Rules).
  • ActorSnapshotWork: Saved positions and facings of every actor in the current scene, captured before entering a battle or writing a save so the scene restores identically.

That cold-start boundary keeps every engine simple and decoupled. During the Vault inn thieves cutscene, field code writes the win and loss destinations into MainRoutineStateWork, requests ENGINE_BATTLE, and lets the field engine end. The battle engine knows nothing about Vault. When the fight ends, gmReturnFromEngine checks the outcome and launches a fresh field engine at the right destination.

2. Waiting (sySynch) and events

A villager by Vale's river waits for the A Button. Watch the river behind him: it keeps flowing the whole time he waits.
A villager by Vale's river waits for the A Button

Rather than placing a while (running) loop at the top of main(), The Broken Seal places its tick loop inside one blocking function, sySynch(Sint32 ticks) in system_frame.c:

void sySynch(Sint32 ticks)
{
    for (Sint32 i = 0; i < ticks; i++)
    {
        syExecuteEvent(EVENT_PASS_TICK); /* run tick-pass callbacks, highest priority first */
        syOAMBuildBuffer(...);           /* flatten depth-sorted sprites into shadow OAM */
        TickRenderPending = 1;           /* mark this tick ready for VBlank */
        /* halt CPU until VBlank commits the frame to hardware */
        /* 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.

In coroutine terms, foreground C is the one coroutine, and sySynch() is both its yield and its scheduler. A night at an inn reads as a plain sequence: wait, fade to black, play the jingle and wait for it to finish, restore HP and PP, and fade back in. No state machine tracks 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, capacity 20) is a registered per-tick C callback. It is not a cutscene (cutscenes are blocking C sc* scripts). Each tick, sySynch() calls active tick-pass events (EVENT_PASS_TICK = 0xC80) in descending priority order. VBlank-pass events (EVENT_PASS_VBLANK = 0x480) run inside syVBlankHandler to copy finished buffers into VRAM.

Four rules govern events:

  • Events run only inside sySynch(). While dialogue waits for A, it loops on sySynch(1), which keeps Vale's river and townsfolk moving behind the box.
  • Events must never call sySynch(). They also never add or re-sort events mid-pass.
  • One event drives an entire subsystem. For example, fdActorUpdateAllOnField steps all 64 field actors on every tick. Because an NPC cannot call sySynch() between strolls, its bytecode actor script counts down a per-actor timer (SC_WAIT) instead:
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

Because there is only one foreground call stack, two C routines never block side by side. To move two characters together, a cutscene starts both with non-blocking calls and waits once:

fdActorWalkTo(ACTOR_PARTY_LEADER, 120, 96); /* returns at once */
fdActorWalkTo(ACTOR_GARET, 136, 96);        /* returns at once */
sySynch(40);                                /* both walk while this runs */

Commands ending in AndWait start an action and loop sySynch(1) until it finishes. fdActorWalkToAndWait gives up after 600 ticks (10 seconds) so a blocked actor can never soft-lock a cutscene. Because an event cannot block or start a conversation directly, events write a field request into FieldStateWork, and fdEngineRun services it immediately after sySynch(1) returns.

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

Isaac walks up to a villager in Vault and the player presses A. The six steps below show which code runs at each point:

  1. fdEngineRun sits in its walking loop calling sySynch(1) over and over. It is the only foreground code waiting.
  2. Inside one sySynch(1), fdActorUpdateAllOnField steps Isaac (SC_PLAYER), sees the A Button, and records a request in FieldStateWork. It then moves on to the villager, who is mid-SC_WAIT, and ticks his countdown down by 1.
  3. sySynch(1) returns. fdEngineRun notices the request, leaves its walking loop, switches Isaac 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 marks the villager paused, turns both characters to face each other, and requests a dialogue window (mnWindowCreate), which returns at once.
  5. Foreground code now loops sySynch(1) until the window closes. Each tick, mnWindowSystemUpdate grows the box, types a few glyphs, and watches for A. Because the villager is paused, fdActorUpdateAllOnField skips him so his SC_WAIT countdown stays frozen.
  6. The player presses A. mnWindowSystemUpdate shrinks and closes the box, ending the loop. The villager unpauses, Isaac returns to SC_PLAYER, fdEngineRun resumes its walking loop, and the villager's countdown resumes where it stopped.

When nothing waits: VBlank and slowdown

During a tick, game code never writes directly to visible sprite hardware (OAM). Instead, it fills RAM buffers and queues hardware register changes through syIOWriteQueueStore*. At every ~60 Hz hardware VBlank, syVBlankHandler commits finished ticks atomically whenever TickRenderPending is set. It also increments FrameCount, runs VBlank-pass events, polls buttons, and steps the audio mixer (MixerEnter) on every refresh.

If a heavy tick runs longer than one frame (~1/60 second), VBlank shows the previous frame again and commits the new tick on the next VBlank. The result is tear-free slowdown while the music holds exact tempo. If game code ever stopped calling sySynch(), the screen would freeze on a still picture while the music continued playing.

3. Compressed scene overlays

All 201 scenes' dialogue, cue tables, and cutscenes are far too large to stay in GBA RAM together, and only one scene ever runs at a time. Camelot therefore stores scene code compressed inside the 1,000-row resource directory as 96 overlays. Related rooms often share one overlay, such as Crossbone Isle and all nine floors of its cave.

When a scene is entered, syOverlayLoad unpacks its overlay into a fixed 32 KB EWRAM buffer (0x02008000) and patches its long branches, overwriting the previous overlay. Overlays never call each other directly. Shared helpers in scene/shared/ compile into each overlay that includes them. The resident main image talks to the active overlay through a fixed 6-stub entry table (scene/entry.s), and the overlay calls back into the main image through a build-generated import table at its end. Battles and Tolbi's minigames load no overlay at all.

4. Atomic copy-on-write flash saving

Isaac opens the Pause menu in Vale and saves to slot 1: Saving... holds briefly while the new copy is written and verified before the old sector is retired
Isaac opens the Pause menu in Vale and saves to slot 1: Saving... holds briefly while the new copy is written…

A save file holds exactly the three persistent blocks that survive an engine transition: GameFlags, MainRoutineStateWork, and ActorSnapshotWork (captured fresh as saving begins).

The cartridge's 64 KB flash chip holds sixteen 4 KB sectors. Each of the three save slots takes two 4 KB parts (one sector each), leaving 10 spare sectors free. syBupWritePart writes the updated part with a higher sequence counter and checksum into a spare sector, verifies it by reading it back, and only then retires the old sector. Even if the GBA loses power halfway through saving, the previous save stays intact.

Code reference