Skip to content

Architecture

Enrique Pérez edited this page Nov 18, 2026 · 3 revisions

Architecture

OpenLua is a single-threaded Lua 5.1 host for the PSP. It embeds the vendored Lua runtime, registers engine modules as global Lua tables, and runs one script.lua to completion.

The authoritative version is docs/ARCHITECTURE.md.

High-level layout

script.lua
    │
    ▼
engine/core/main.c ── register_api() ──────────────────────────────┐
    │                                                              │
    ├── gfx/     GE pipeline, surfaces, primitives  (screen, draw,   │
    │            splash)                                             │
    ├── img/     PNG/JPEG/BMP decode via stb_image   (image)        │
    ├── font/    PGF + SFont atlas renderer          (font, sfont)  │
    ├── snd/     WAV/VMA decode + PSP audio          (sound)        │
    ├── input/   sceCtrl polling                     (buttons)      │
    ├── util/    timers + OneLua math helpers         (timers, math) │
    ├── fs/      portable VFS, files, ini            (files, ini)   │
    ├── data/    JSON + PSMF + PBP/SFO parsing       (json, game)   │
    ├── sys/     saves + battery + power + os + hw + osk + game +   │
    │            cam + umd/usb/sio/ir                               │
    ├── maps/    tile grid renderer                  (map)          │
    ├── 3d/      OBJ/MTL parser, camera, 3D textures  (amg, cam3d,   │
    │            and model state                      texture3d,    │
    │                                                 model3d)      │
    └── video/   PMF playback via sceMpeg            (pmf)          │
                                                                    │
                                                             Lua globals

Boot sequence

engine/core/main.c:

  1. Register the PSP exit callback.
  2. chdir to the directory containing the executable (argv[0]), falling back to app0:/. app0: resolves to the EBOOT directory on both Memory Stick (ms0:) and PSP Go internal storage (ef0:).
  3. Initialise the GE (gfx_init).
  4. Create the Lua state and open the standard libraries.
  5. Register engine modules (register_api).
  6. Find and run script.lua (or SCRIPT.LUA / boot.lua, an argv path, or the explicit app0:/ equivalents).
  7. On error, write openlua.log and fall back to the debug screen.

Boot tracing appends short markers to flash0:/openlua_boot.txt, with an app0: fallback.

Lua binding pattern

Every module follows the same shape:

static const luaL_Reg module_funcs[] = { /* ... */ };

void module_api_register(lua_State *L)
{
    lua_newtable(L);
    ol_setfuncs(L, module_funcs);
    lua_setglobal(L, "module");
}

engine/core/olreg.c is a small helper that pushes each C function and sets it as a field. Handles are 1-based integers into fixed-size global arrays (FONT_MAX, SND_MAX, MAP_MAX). Userdata is used only for image and timers, mainly to attach __gc.

Rendering pipeline

engine/gfx/gfx.c:

  • OL_Surface is a 32-bit ABGR pixel buffer with power-of-two realW/realH pitch. Storage is 16-byte aligned and uploaded straight to the GE.
  • gfx_init allocates three 512x272x4 buffers as 8192-byte-aligned EDRAM offsets and configures the GE for 2D sprites. GU buffer APIs take VRAM offsets, not absolute 0x04000000 pointers.
  • The 2D depth range is 0..0xFFFF; the depth buffer clears to 0 and compares GU_GEQUAL, so the default z=0 plane renders and larger z-indexes draw in front. Face culling is disabled because flips and rotation can reverse quad winding.
  • gfx_blit is the per-sprite entry point. transform.c computes the four destination vertices and normalised UVs; gfx_blit converts UVs to texels, uploads the surface and draws a textured GU_TRIANGLE_FAN with nearest sampling. Scale, rotation, flips, pivot and tint all apply to that quad.
  • draw.c submits primitives with GU_DIRECT and flat shading.
  • screen.flip() calls sound_pump() and then gfx_flip_scene().

Fonts

engine/font/font.c keeps up to eight font handles and dispatches three loaders:

  • font.load(path) opens a PGF through sceLibFont (pgf.c) in host and opt-in PSP builds. The standard PSP build defines OPENLUA_NO_PGF because sceLibFont comes from a per-game user module, and a static import makes the firmware reject the EBOOT with 8002013C.
  • font.new(path, cellW, cellH) loads a fixed-cell PNG grid.
  • sfont.load accepts a classic SFont strip with magenta top-row separators and variable advances, or a fixed 95-cell sheet.

All three share the same handle table, print/textwidth path and gfx_blit renderer. PNG and SFont sheets are repacked into an atlas no wider than 512 px (the GE texture limit) on first draw.

Audio pipeline

sound decodes WAV (PCM16) or VMA/VOX, reserves one of eight channels and is pumped by screen.flip(). pmf uses sceMpeg for PSMF video and sceAudioOutputBlocking for ATRAC3+ audio.

Storage

engine/fs provides a portable VFS layer used by files, ini, data and the tester. Paths are relative to the working directory. The loader falls back across ms0: and ef0: for saves.

Memory and limits

  • PSP_HEAP_SIZE_KB(20000) — roughly 20 MB.
  • Images capped at 1024x1024, padded to power-of-two dimensions.
  • Fonts: 8 slots, cells up to 256x256; atlases no wider than 512 px.
  • Sounds: 8 slots, 8 MB source file cap.
  • Maps: 8 slots; tileset anchored via the Lua registry until map.free.
  • INI: 512-byte parse lines, 256 KB file cap.
  • JSON: 256 KB load cap; HTTP body 16 MB, headers 16 KB.

Module map

Directory Responsibility Public API
engine/core Boot, Lua registration color, screen.clear/flip
engine/gfx Surfaces, GE, primitives, splash draw.*, splash.*
engine/img Image decode, blits, transforms image.*
engine/font PGF (host/opt-in), PNG/SFont, atlas font.*, sfont.*, screen.print
engine/snd Audio decode and output sound.*
engine/input Controller polling buttons.*
engine/util Timers, math helpers timers.*, math.*
engine/ecs Entity/component/system worlds with generational slots ecs.*
engine/fs Files, INI, portable VFS, archive reader files.*, ini.*
engine/data JSON, PSMF header, PBP/SFO json.*, PBP metadata
engine/net Shared network-stack refcount used by networking modules
engine/sys Saves, battery, power, OS, hardware, OSK, PBP, networking data.*, batt.*, power.*, os.*, hw.*, osk.*, game.*, wlan.*, socket.*, http.*, ftp.*, adhoc.*, bluetooth.*
engine/maps Tilemaps map.*
engine/3d OBJ/MTL, camera/model/texture state amg.*, cam3d.*, texture3d.*, model3d.*
engine/gfx/gfx3d.c GE 3D state and triangle submission shared by 3D modules
engine/video PMF playback pmf.*
third_party Lua 5.1.5, stb headers, miniz, libbzip2 —

ECS handle safety

engine/ecs/ecs.c keeps a per-world slot array with a generation counter, an alive flag and a free list. An entity handle stores (world id, slot, generation) and never holds a C pointer to the world. destroy bumps the generation before the slot can be reused, so stale and foreign handles resolve to their documented dead values; a handle whose world was collected has nothing to dereference.

Component and system tables live in the world userdata's Lua environment, keyed by the canonical handle for each live slot. Lua therefore reclaims values when an entity dies or the world is cleared, and the world's __gc only frees the C arrays. Queries and systems walk slots in order, keeping entity ordering stable across growth and reuse.

Host testing

The PSP headers keep most graphics/input code out of host builds. The storage layer, timers, math helpers, formatting/clamping, transform math, OBJ/MTL parsing, map geometry, sound parsing, PBP/SFO parsing, URL/HTTP parsing, loopback TCP/HTTP/FTP paths and the Lua sources all compile and run on a PC.

bash test/host/run.sh
bash tools/check_repo_hygiene.sh

CI runs the suite and builds EBOOT.PBP on every push and pull request.

Related

Clone this wiki locally