15 Commits

Author SHA1 Message Date
YourWishes 16c27e0124 Nothing 2026-06-21 17:16:17 -05:00
YourWishes f41ebd69b4 aturn 2026-06-21 11:40:46 -05:00
YourWishes 7f8bcf07e8 Saturn builds 2026-06-21 10:00:30 -05:00
YourWishes 0438011ca3 Dolphin 2026-06-20 11:25:47 -05:00
YourWishes 8d6d33c159 Fix PSP spinning box 2026-06-20 09:58:08 -05:00
YourWishes 943297b685 More render tests 2026-06-20 09:39:53 -05:00
YourWishes 91924e1259 float -> float_t 2026-06-19 21:56:43 -05:00
YourWishes 9ad481d8f3 Renders on PSP 2026-06-19 21:47:50 -05:00
YourWishes 1f67e817ae Some progress 2026-06-19 14:24:09 -05:00
YourWishes 4e491d8332 Tilemap stuff 2026-06-19 13:17:20 -05:00
YourWishes 57b2cdb9d1 prog 2026-06-18 20:25:54 -05:00
YourWishes 730a5b2b10 Docs 2026-06-18 14:59:21 -05:00
YourWishes 6135d60ddc Interact 2026-06-18 13:34:36 -05:00
YourWishes 4c2a883038 Bit more cleanup of floats 2026-06-18 13:03:57 -05:00
YourWishes c88b672f42 Fixed_t updates 2026-06-18 12:44:23 -05:00
269 changed files with 9334 additions and 3456 deletions
+74
View File
@@ -0,0 +1,74 @@
# Animation System
Source: `src/dusk/animation/`
Lightweight keyframe-based value interpolation using fixed-point math throughout.
---
## Easing (`animation/easing.h`)
`easingApply(type, t)` applies an easing function to a normalized time value `t ∈ [0, FIXED_ONE]` and returns the eased value in the same range.
All functions are also callable directly:
```c
fixed_t t = FIXED(0.5f);
fixed_t out = easingApply(EASING_IN_OUT_CUBIC, t);
```
Available easing types (all in `easingtype_t`):
| Enum value | Curve |
|---|---|
| `EASING_LINEAR` | straight line |
| `EASING_IN_SINE` / `OUT` / `IN_OUT` | sinusoidal |
| `EASING_IN_QUAD` / `OUT` / `IN_OUT` | quadratic |
| `EASING_IN_CUBIC` / `OUT` / `IN_OUT` | cubic |
| `EASING_IN_QUART` / `OUT` / `IN_OUT` | quartic |
| `EASING_IN_BACK` / `OUT` / `IN_OUT` | overshoots slightly |
`EASING_FUNCTIONS[EASING_COUNT]` is a table of `easingfn_t` function pointers for when you need to pick an easing at runtime without a switch.
---
## Keyframes (`animation/keyframe.h`)
```c
typedef struct {
fixed_t time; // time point this keyframe is at
fixed_t value; // output value at this time
easingtype_t easing; // easing to apply when interpolating toward the NEXT keyframe
} keyframe_t;
```
Keyframe arrays should be sorted ascending by `time`.
---
## Animation (`animation/animation.h`)
`animation_t` wraps a keyframe array and provides value lookup:
```c
keyframe_t frames[] = {
{ FIXED(0.0f), FIXED(0.0f), EASING_LINEAR },
{ FIXED(1.0f), FIXED(1.0f), EASING_IN_OUT_CUBIC },
{ FIXED(2.0f), FIXED(0.0f), EASING_LINEAR },
};
animation_t anim;
animationInit(&anim, frames, 3);
fixed_t value = animationGetValue(&anim, FIXED(0.75f)); // interpolated
```
`animationGetValue` finds the surrounding keyframes for the given `time`, computes the local `t` within that segment, applies the keyframe's easing, and linearly interpolates between the two keyframe values.
The animation does not own the keyframe array — it holds a pointer. Pass a static or long-lived array.
---
## Usage in the engine
Entity animations (`entityanim_t`) do NOT use this system — they use a simple countdown timer (`animTime`) and a state enum. The `animation_t` system is intended for property animation: UI transitions, camera easing, visual effects, anything that needs a time → value curve.
+81
View File
@@ -0,0 +1,81 @@
# Architecture
## Platform abstraction
Every subsystem that differs across platforms (display, input, asset loading, save, time, network, log) follows the same pattern:
1. `src/dusk/<subsystem>/<subsystem>platform.h` — included by the public header. Contains `#include "path/to/platform-specific-header.h"` resolved by the build system include path.
2. `src/dusk{platform}/<subsystem>/<subsystem>platform.h` — the actual platform-specific header included above (e.g. `src/duskgl/display/framebuffer/framebufferplatform.h`).
3. The shared header (`src/dusk/<subsystem>/<subsystem>.h`) `#error`s at compile time if the platform doesn't define the expected macros/types.
The active platform backends are selected by `DUSK_TARGET_SYSTEM` in CMake, which includes `cmake/targets/<system>.cmake`. That file sets compile definitions (`DUSK_LINUX`, `DUSK_SDL2`, `DUSK_OPENGL`, …) and links platform libraries.
Platform source directories:
- `src/duskgl/` — OpenGL rendering (used on Linux and as the GL layer for SDL2)
- `src/dusksdl2/` — SDL2 window/input/time (Linux desktop)
- `src/dusklinux/` — Linux filesystem/save/network
- `src/duskdolphin/` — GameCube & Wii (GX renderer, libogc)
- `src/duskpsp/` — PSP (GU renderer, PSPSDK)
- `src/duskvita/` — PS Vita
## Subsystem lifecycle
All subsystems follow `init → update (per frame) → dispose`. Engine initialization order matters and is centralized in `engine.c`:
```
systemInit → timeInit → consoleInit → inputInit → assetInit →
localeManagerInit → displayInit → uiInit → uiTextboxInit →
cutsceneInit → rpgInit → networkInit → sceneInit
```
Dispose runs in reverse. Each call uses `errorChain()` to propagate failures.
## Error handling
Functions that can fail return `errorret_t` (a code + pointer to thread-local error state). Three core macros:
```c
errorThrow("message %s", arg); // sets error, returns from current function
errorChain(someCall()); // if someCall() fails, propagates and returns
errorOk(); // returns success
```
Check with `errorIsOk(ret)` / `errorIsNotOk(ret)`. The error state carries file/function/line info for a stack-like trace.
## Fixed-point math
`fixed_t` is `int32_t` with Q24.8 format (8 fractional bits, ~0.004 resolution). Use it for all world/game values:
```c
fixed_t x = FIXED(1.5); // compile-time literal
fixed_t y = fixedFromI32(3); // runtime conversion
fixed_t z = fixedMul(x, y); // arithmetic
float_t f = fixedToFloat(z); // only where float is needed (e.g. GL uniforms)
```
## Code generation from CSV
Several subsystems define their data in CSV files and have corresponding Python tools that generate C headers at build time (via CMake `add_custom_command`):
| CSV | Tool | Output |
|-----|------|--------|
| `src/dusk/input/input.csv` | `tools/input/csv/` | input action enum + names |
| `src/dusk/display/color.csv` | `tools/color/csv/` | color constants |
| `src/dusk/rpg/item/item.csv` | `tools/item/csv/` | item enum + metadata |
| `src/dusk/rpg/story/storyflag.csv` | `tools/story/csv/` | story flag enum + initial values |
Generated headers are written to `build-<target>/generated/` and included via `target_include_directories`.
## Asset system
Assets are packed into `dusk.dsk` (a zip archive) at build time from the `assets/` directory. At runtime `asset.c` opens the archive and serves files from it.
Loading is asynchronous: `assetLock()` registers a load request; the background thread calls the appropriate loader; call `assetRequireLoaded()` to block until ready. `assetUnlock()` / `assetUnlockEntry()` releases the entry so it can be reclaimed.
Loaders are registered per type (`assetloadertype_t`) and live under `src/dusk/asset/loader/`. Platform-specific asset init (finding the .dsk file) is in `src/dusk{platform}/asset/`.
## Display subsystem
The display system is currently organized around immediate GPU-style rendering: `mesh_t` (vertex buffers), `shader_t` (GLSL on GL / TEV state on Dolphin), `texture_t`, and `framebuffer_t`. See [display-refactor.md](display-refactor.md) for the planned move to a render-queue model (needed for a future Saturn port).
The `spritebatch_t` (`display/spritebatch/`) accumulates 2D quads and flushes in batches — the primary 2D drawing primitive used by the RPG layer.
+115
View File
@@ -0,0 +1,115 @@
# Asset System
Source: `src/dusk/asset/`
All game assets are packed into `dusk.dsk` (a zip archive) at build time and served from it at runtime. The asset system manages async loading, reference counting, and platform-specific archive location.
See [architecture.md](architecture.md#asset-system) for the high-level overview.
---
## Asset archive
The archive is opened at `assetInit()`. `assetFileExists(filename)` checks for a file without loading it. The file path format inside the archive matches the layout of the `assets/` source directory.
On each platform, `assetInitPlatform()` locates the `.dsk` file (e.g. adjacent to the binary on Linux, on the SD card on PSP).
---
## Entry lifecycle
An `assetentry_t` represents one file being managed by the system. States:
```
NOT_STARTED → PENDING_ASYNC → LOADING_ASYNC → PENDING_SYNC → LOADING_SYNC → LOADED
└→ ERROR
```
- **PENDING_ASYNC / LOADING_ASYNC**: the background thread is handling I/O (file reads, decompression).
- **PENDING_SYNC / LOADING_SYNC**: the main thread needs to finish loading (e.g. uploading to GPU), triggered during `assetUpdate()`.
The async/sync split exists because GPU operations must happen on the main thread.
---
## Using assets
```c
// Acquire a loaded entry (blocks until loaded):
assetentry_t *entry = assetLock(filename, ASSET_LOADER_TYPE_TEXTURE, &input);
errorChain(assetRequireLoaded(entry));
// Use the loaded data:
texture_t *tex = &entry->data.texture.texture;
// Release when done:
assetUnlockEntry(entry);
```
`assetLock` finds-or-creates an entry and increments its reference count. `assetUnlock` / `assetUnlockEntry` decrements it; when it reaches zero the entry is reclaimed at the next `assetUpdate()`.
To subscribe to async completion instead of blocking:
```c
eventSubscribe(&entry->onLoaded, myCallback, myUser);
```
---
## Loader types
| Type constant | File | Output struct accessed via |
|---|---|---|
| `ASSET_LOADER_TYPE_TEXTURE` | `.png` etc. | `entry->data.texture.texture` |
| `ASSET_LOADER_TYPE_TILESET` | tileset descriptor | `entry->data.tileset.tileset` |
| `ASSET_LOADER_TYPE_MESH` | mesh data | `entry->data.mesh.mesh` |
| `ASSET_LOADER_TYPE_LOCALE` | `.po` file | internal to locale manager |
| `ASSET_LOADER_TYPE_JSON` | `.json` | `entry->data.json.*` |
Each loader type registers `loadAsync`, `loadSync`, and `dispose` callbacks in `ASSET_LOADER_CALLBACKS[]`.
The async callback runs on the loader thread; the sync callback runs on the main thread during `assetUpdate()`. Most loaders do file I/O async and GPU upload sync.
### Error handling inside loaders
Use these macros instead of `errorThrow` / `errorChain` inside loader callbacks — they also set the entry state to ERROR:
```c
assetLoaderErrorChain(loading, someCall());
assetLoaderErrorThrow(loading, "Descriptive message");
```
---
## Low-level file I/O (`asset/assetfile.h`)
`assetfile_t` wraps a `zip_file_t` handle and provides streaming reads:
```c
assetFileInit(&file, "textures/player.png", NULL, NULL);
assetFileOpen(&file);
assetFileRead(&file, buffer, size);
assetFileClose(&file);
assetFileDispose(&file);
// Read entire file into a malloc'd buffer:
uint8_t *buf; size_t size;
assetFileReadEntire(&file, &buf, &size); // caller frees buf
```
For line-by-line text parsing (`assetfilelinereader_t`):
```c
assetFileLineReaderInit(&reader, &file, readBuf, readBufSize, outBuf, outBufSize);
while(!reader.eof) {
errorChain(assetFileLineReaderNext(&reader));
// reader.outBuffer contains the line, reader.lineLength its length
}
```
---
## Background loader thread
`assetUpdateAsync(thread)` is the thread entry point. It calls `assetUpdate()` in a loop, sleeping briefly between iterations, until `threadShouldStop()` returns true. The main thread also calls `assetUpdate()` once per frame to process the sync phase.
Up to `ASSET_LOADING_COUNT_MAX` (4) entries can be loading concurrently.
Up to `ASSET_ENTRY_COUNT_MAX` (128) entries can exist at once.
+92
View File
@@ -0,0 +1,92 @@
# Display Refactor Progress
## Immediate Goal
Render a 32x32 white square through the new render opcode stack on Linux.
## Architecture (summary)
See `.claude/display-refactor.md` for the full design.
- `src/dusk/render/` -- opcode format + buffer + submission API (the *contract*).
- Platform backends (e.g. `src/duskgl/`) consume the buffer and translate to native API calls.
- `src/dusk/display/` -- orchestration shell only: `displayInit`, `displayUpdate`, `displayDispose`.
- Scenes call `renderSprite(...)`, `renderClear(...)`. The backend executes the intent.
## Opcode format (32 bytes)
Every command starts with a 4-byte `ropheader_t` (opcode, flags, depth). Two commands defined:
- `ROP_CLEAR` (32 bytes) -- clear with a color.
- `ROP_DRAW_SPRITE` (32 bytes) -- screen-space int16 x/y/w/h + tint color.
## Milestone 1 -- Archive + strip existing display deps ✓
- [x] Old `src/dusk/display/` archived (now deleted from working tree via git).
- [x] Old `src/duskgl/display/` removed (new GL renderer replaces it).
- [x] `engine.c` stripped to minimal subsystems, set to `SCENE_TYPE_TEST`.
- [x] `scene.c` stripped of old display/shader/screen references.
- [x] `console.c` stripped of display deps.
- [x] `ui/CMakeLists.txt` gutted (re-implementation deferred).
- [x] `asset/loader/CMakeLists.txt` -- display loaders disabled.
- [x] `asset/loader/assetloader.h` -- display loader types removed.
- [x] `rpg/overworld/chunk.h` -- mesh_t / meshvertex_t removed.
- [x] `rpg/overworld/map.c` -- mesh/spritebatch calls removed.
- [x] `scene/overworld/sceneoverworld.c` -- stubbed to empty callbacks.
- [x] Test suite display tests disabled.
## Milestone 2 -- Render opcode system ✓
- [x] `src/dusk/render/rop.h` -- `ropheader_t`, `ropclear_t`, `ropsprite_t`.
- [x] `src/dusk/render/ropbuffer.h/.c` -- `ROPBUFFER` global, reset, alloc.
- [x] `src/dusk/render/render.h/.c` -- `renderClear()`, `renderSprite()`.
- [x] `src/dusk/render/CMakeLists.txt`.
## Milestone 3 -- New minimal display shell ✓
- [x] `src/dusk/display/display.h/.c` -- init/update/dispose, calls platform hooks.
- [x] `src/dusk/display/displaystate.h` -- cull/depth/blend flags.
- [x] `src/dusk/display/color.csv` + `CMakeLists.txt` -- color generation kept.
## Milestone 4 -- GL backend ✓
- [x] `src/duskgl/render/rendergl.h/.c`:
- GL 3.3 core shader (ortho projection, solid color, no texture yet).
- `renderGLInit` -- creates VAO/VBO/shader.
- `renderGLFlush(buf, w, h)` -- walks ROPBUFFER, GL calls per opcode.
- `ROP_CLEAR``glClearColor` + `glClear`.
- `ROP_DRAW_SPRITE` → 6-vertex quad, `glDrawArrays`.
- [x] `src/duskgl/error/errorgl.h/.c` -- `errorGLCheck`.
- [x] `src/duskgl/CMakeLists.txt`.
- [x] `src/dusksdl2/display/displaysdl2.h/.c` updated:
- `displaySDL2Init` -- SDL2 window + GL 3.3 context + `renderGLInit`.
- `displaySDL2Flush(ropbuffer_t *)` -- MakeCurrent + `renderGLFlush`.
- `displaySDL2Swap` -- SDL_GL_SwapWindow.
- [x] `src/dusklinux/display/displayplatform.h` updated with new macros.
## Milestone 5 -- Test scene ✓
- [x] `SCENE_TYPE_TEST` added to `scenetype.h/.c`.
- [x] `src/dusk/scene/test/scenetest.h/.c`:
- `renderClear(color(32, 32, 48, 255))` -- dark blue-grey background.
- `renderSprite(100, 100, 32, 32, COLOR_WHITE)` -- 32x32 white square.
- [x] `engine.c` starts with `SCENE_TYPE_TEST`.
## Milestone 6 -- Verified ✓
- [x] Build succeeds with no errors (2026-06-18).
- [x] Engine initializes: SDL window + GL context + shader + test scene.
- [x] No crashes running for 5+ seconds.
- [ ] 32x32 white square visually confirmed on screen.
---
## Status: BUILD PASSING -- awaiting visual confirmation
---
## Decisions log
**2026-06-18** -- `color_t = color4b_t` (from generated `display/color.h`). The color generation pipeline (color.csv + Python tool) is kept in the new minimal `src/dusk/display/CMakeLists.txt`.
**2026-06-18** -- `ROP_SIZE = 32`. All opcodes fixed 32 bytes. 3D quads will be 64 bytes when added later.
**2026-06-18** -- Depth sort deferred. Buffer stores unsorted commands; painter platforms sort on flush. GL uses Z-buffer.
**2026-06-18** -- Texture system not yet wired into the opcode pipeline. `ROP_DRAW_SPRITE` with `texture=0` uses solid tint color only (no sampler). Texture handle system comes next.
**2026-06-18** -- GL backend uses GL 3.3 Core profile. Shader takes screen-space pixel coordinates and converts to clip space using window size queried from SDL each frame.
**2026-06-18** -- `ROPBUFFER` is a global (4096 slots × 32 bytes = 128 KB). Reset at start of each frame in `displayUpdate`.
**2026-06-18** -- `ui/`, `rpg/overworld` display code, asset display loaders all temporarily stubbed/disabled. Will be rewritten against the new render API.
+352
View File
@@ -0,0 +1,352 @@
# Display System
Source: `src/dusk/display/`
The display system is the rendering pipeline. It is abstracted across platforms via `displayplatform.h` — see [architecture.md](architecture.md) for the abstraction pattern. The current concrete backends are OpenGL (`src/duskgl/`) and GX/Dolphin (`src/duskdolphin/`).
For the planned render-queue refactor (required for Saturn), see [display-refactor.md](display-refactor.md).
---
## Render / ROP system (`display/render/`)
The ROP (Render OPcode) system is the low-level, backend-agnostic drawing API. All game drawing goes through this layer; backends (`rendergl.c`, `renderpsp.c`, `renderdolphin.c`) execute the commands at display flush time.
### API (`display/render/render.h`)
```c
/* Clear the framebuffer */
void renderClear(color_t color);
/* 2D textured quad at pixel coordinates */
void renderSprite(
int16_t x, int16_t y, int16_t w, int16_t h,
int16_t depth, /* 0=front … 32767=back */
rtexture_t texture, color_t tint
);
/* Set perspective projection for subsequent 3D draws */
void renderSetProjection(
fixed_t fovY, fixed_t aspect, fixed_t nearZ, fixed_t farZ
);
/* Set camera position/target for subsequent 3D draws */
void renderSetView(
int16_t eyeX, int16_t eyeY, int16_t eyeZ,
int16_t tgtX, int16_t tgtY, int16_t tgtZ
);
/* World-space quad: center point + right half-extent + up half-extent */
void renderQuad3D(
int16_t cx, int16_t cy, int16_t cz,
int16_t rx, int16_t ry, int16_t rz,
int16_t ux, int16_t uy, int16_t uz,
int16_t depth,
rtexture_t texture, color_t tint
);
/* Create / dispose an 8-bit indexed palette texture */
rtexture_t renderTextureCreate(
uint16_t w, uint16_t h,
const uint8_t *indices, /* w×h pixel indices (0-255) */
const color_t *palette /* 256 RGBA colour entries */
);
void renderTextureDispose(rtexture_t tex);
/* Mutable pointers to the texture's CPU-side data.
* Write directly to these; the next draw call picks up the changes.
* GL: dirty flag set on getter call; glTexSubImage2D at next bind.
* PSP: re-pads indices and converts palette → ABGR at bind time.
* Dolphin: re-tiles CI8 and converts palette → RGB5A3 at bind time. */
color_t *renderTextureGetPalette(rtexture_t tex); /* color_t[256] */
uint8_t *renderTextureGetIndices(rtexture_t tex); /* uint8_t[w*h] */
```
### Coordinate conventions
| Domain | Type | Scale | Notes |
|---|---|---|---|
| 3D world positions | `int16_t` | 1 unit = 1 cm | Matches PS1 GTE / N64 RSP native format |
| Camera/projection params | `fixed_t` | Q24.8 | `FIXED(x)` for literals |
| 2D screen positions | `int16_t` | pixels | Origin top-left |
| UV coords | `uint8_t` | 0255 → 0.01.0 | Stored in ROP structs |
### Palettized textures
All textures are 8-bit indexed. `renderTextureCreate` takes:
- `indices`: one `uint8_t` per pixel (0255), row-major
- `palette`: exactly **256** `color_t` RGBA entries
**Per-platform storage:**
| Platform | CPU source of truth | GPU/native format | When derived |
|---|---|---|---|
| GL (Linux/Vita) | `color_t palette[256]` + `uint8_t *cpuIndices` in slot | `GL_R8` index tex + `GL_RGBA` 256×1 palette tex | Lazy: dirty flag set by getter, `glTexSubImage2D` at next bind |
| PSP | `color_t palette[256]` + unpadded `uint8_t *cpuIndices` | Stride-padded indices (POT ≥ 8) + ABGR8888 CLUT in shared `pspAbgrBuf` | Every `bindTexture` call; dcache-flushed before GU reads |
| Dolphin/GC/Wii | `color_t palette[256]` + unpadded `uint8_t *cpuIndices` | CI8 tiled (8×4 tiles, 32 B/tile) + RGB5A3 TLUT in `tlutData` | Every `bindTexture` call; `DCFlushRange` before GX load |
**GL palette shader detail**: The fragment shader samples the R8 index texture, converts the normalised float back to an exact texel centre with `raw*(255/256) + 0.5/256`, then looks up the 256×1 palette texture. This gives pixel-exact results for all 256 index values and allows independent real-time updates to indices or palette.
**Dolphin RGB5A3 encoding**:
- Opaque (`a == 255`): bit 15 = 1, RGB555
- Transparent: bit 15 = 0, A3RGB4 (alpha quantised to 3 bits — dithered transparency is planned for a future pass)
### ROP buffer (`display/render/ropbuffer.h` / `rop.h`)
Commands are written into `ROPBUFFER` (a static byte array) then replayed by the backend at flush time. All ops are fixed-size aligned structs:
| Op | Struct | Size |
|---|---|---|
| `ROP_CLEAR` | `ropclear_t` | 32 bytes |
| `ROP_DRAW_SPRITE` | `ropsprite_t` | 32 bytes |
| `ROP_SET_PROJECTION` | `ropprojection_t` | 32 bytes |
| `ROP_SET_VIEW` | `ropview_t` | 32 bytes |
| `ROP_DRAW_QUAD_3D` | `ropquad3d_t` | 64 bytes |
| `ROP_DRAW_TILEMAP_CHUNK` | `roptilemapc_t` | 32 bytes |
`ropOpSize(op)` returns the byte size for any op. Backends iterate with `offset += ropOpSize(op)`.
### Texture handles (`display/render/rtexture.h`)
`rtexture_t` is a `uint16_t` index into the platform's texture table. `RTEXTURE_NONE` (0 or a sentinel) means "white fallback". Tables are platform-static; handles are valid until `renderTextureDispose` is called.
### Tilemap chunk handles (`display/render/rtilemapchunk.h`)
`rtilemapchunk_t` is a `uint16_t` index into the platform's chunk table. `RTILEMAPCHUNK_INVALID` (0) means no-op. Chunks are pre-built at map load time; each backend constructs its native draw structure once (VAO+VBO on GL, display list on PSP/GX/N64) and the ROP entry costs only a handle lookup + single native draw call per frame.
```c
/* Build once at map load */
rtilemapchunk_t chunk = renderTilemapChunkCreate(
chunkW, chunkH, /* size in tiles */
tileW, tileH, /* pixels per tile */
tileset, /* rtexture_t of the packed tileset */
tileIndices /* uint8_t[chunkW*chunkH], row-major tile indices */
);
/* Each frame for visible chunks */
renderTilemapChunk(screenX, screenY, depth, chunk);
/* At map unload */
renderTilemapChunkDispose(chunk);
```
Animated tiles should be drawn on top as separate `renderSprite()` calls; the chunk itself is treated as static geometry and never rebuilt at runtime.
**Per-platform build:**
| Platform | What's built at create time | Draw cost per frame |
|---|---|---|
| GL (Linux/Vita) | VAO + VBO (`GL_STATIC_DRAW`), `uOffset` uniform translates to screen pos | 1 `glDrawArrays` |
| PSP | GU display list in uncached EDRAM | 1 `sceGuCallList` |
| GC/Wii | Compiled GX display list | 1 `GX_CallDispList` |
| PS1 | Pre-linked POLY_FT4/SPRT chain | Linked into OT at one slot |
| N64 | RDP display list with pre-scheduled `LOAD_TILE` batches (TMEM-aware) | 1 `gSPDisplayList` |
| Saturn | VDP2 plane config + VRAM tilemap data | Scroll register write only |
---
## Initialization order
Within the display system, init must follow this order (enforced in `engine.c`):
```
displayInit → uiInit → uiTextboxInit
```
Within `displayInit`, the platform typically initialises: framebuffer → screen → shader list → textures → spritebatch → text system.
---
## `display_t` / `displaystate_t`
`display_t DISPLAY` is the global display instance (type alias for `displayplatform_t`).
`displaystate_t` carries per-draw-call render state flags:
```c
DISPLAY_STATE_FLAG_CULL // face culling
DISPLAY_STATE_FLAG_DEPTH_TEST // depth testing
DISPLAY_STATE_FLAG_BLEND // alpha blending
```
Set state before drawing with `displaySetState(state)`.
---
## Screen (`display/screen/`)
`screen_t SCREEN` manages the logical viewport that game content renders into. On dynamic-size platforms (Linux/SDL2) the screen can differ from the native window/framebuffer resolution.
Screen modes:
```
SCREEN_MODE_BACKBUFFER — maps 1:1 to backbuffer
SCREEN_MODE_FIXED_SIZE — fixed pixel dimensions
SCREEN_MODE_ASPECT_RATIO — fixed aspect, scale to fit
SCREEN_MODE_FIXED_HEIGHT — fixed height, width scales
SCREEN_MODE_FIXED_WIDTH — fixed width, height scales
SCREEN_MODE_FIXED_VIEWPORT_HEIGHT — fixed viewport height
```
The linux target defines `DUSK_DISPLAY_SCREEN_HEIGHT=240`, producing a 240p fixed-height viewport.
Render loop usage:
```c
screenBind(); // set up viewport, projection
// ... draw game content ...
screenUnbind();
screenRender(); // blit to backbuffer / current framebuffer
```
`SCREEN.width` / `SCREEN.height` are the logical dimensions used for world-to-screen math — always prefer these over the framebuffer dimensions.
---
## Framebuffer (`display/framebuffer/`)
`framebuffer_t FRAMEBUFFER_BACKBUFFER` is the platform backbuffer. `FRAMEBUFFER_BOUND` points to the currently-bound framebuffer (or `NULL` for backbuffer).
```c
frameBufferInitBackBuffer(); // called once at startup
frameBufferBind(fb); // NULL → backbuffer
frameBufferClear(FRAMEBUFFER_CLEAR_COLOR | FRAMEBUFFER_CLEAR_DEPTH, COLOR_BLACK);
frameBufferGetWidth(fb) / frameBufferGetHeight(fb) / frameBufferGetAspect(fb);
```
On platforms with `DUSK_DISPLAY_SIZE_DYNAMIC`, off-screen framebuffers can be created with `frameBufferInit(fb, w, h)` and disposed with `frameBufferDispose(fb)`. Fixed-resolution platforms (PSP, GameCube) only ever use the backbuffer.
---
## Mesh (`display/mesh/`)
`mesh_t` is a vertex buffer. The type is `meshplatform_t` (e.g. a VAO+VBO on GL, a GX display list on Dolphin).
```c
meshInit(&mesh, MESH_PRIMITIVE_TYPE_TRIANGLES, vertexCount, verticesPtr);
meshFlush(&mesh, offset, count); // upload CPU vertices → GPU
meshDraw(&mesh, offset, count); // draw; pass -1 for count to draw all
meshDispose(&mesh);
```
**Key distinction**: `meshFlush` uploads data to GPU memory; `meshDraw` issues the draw call. For static geometry (chunk meshes) you call `meshFlush` once on load, then `meshDraw` every frame. For dynamic geometry (spritebatch) you `meshFlush` + `meshDraw` each frame.
`meshvertex_t` (`display/mesh/meshvertex.h`) contains:
- `float_t uv[2]` — texture coordinates
- `float_t pos[3]` — position
- Optionally `color_t color` if `MESH_ENABLE_COLOR` is defined (off by default)
Primitive mesh generators live alongside `mesh.h`: `quad.h`, `plane.h`, `cube.h`, `sphere.h`, `capsule.h`, `triprism.h`.
---
## Shader (`display/shader/`)
`shader_t` is `shaderplatform_t` (GLSL program on GL, TEV state block on Dolphin).
```c
shaderInit(&shader, &definition);
shaderBind(&shader);
shaderSetMatrix(&shader, "uModel", modelMat);
shaderSetTexture(&shader, "uTexture", &texture);
shaderSetColor(&shader, "uColor", COLOR_WHITE);
shaderSetMaterial(&shader, &material);
shaderDispose(&shader);
```
### Shader list (`display/shader/shaderlist.h`)
The engine maintains a small set of built-in shaders in `SHADER_LIST_DEFS[]`. Currently only one is defined:
- `SHADER_LIST_SHADER_UNLIT``SHADER_UNLIT` — unlit textured/colored rendering, used for all world and entity drawing.
`shaderListInit()` compiles/uploads all built-in shaders and sets shared projection/view matrices. Call once after display init.
### Materials (`display/shader/shadermaterial.h`)
`shadermaterial_t` is a union of all shader-specific material structs. Currently only `shaderunlitmaterial_t`:
```c
shadermaterial_t mat = {
.unlit = {
.color = COLOR_WHITE,
.texture = &myTexture, // NULL for solid color
}
};
shaderSetMaterial(&SHADER_UNLIT, &mat);
```
---
## Texture (`display/texture/`)
```c
textureInit(&texture, width, height, format, data);
textureDispose(&texture);
```
Width and height **must be powers of two** (asserted at init time).
`textureformat_t` is `textureformatplatform_t`. Supported formats vary by platform; the common ones are `TEXTURE_FORMAT_RGBA` and `TEXTURE_FORMAT_PALETTE`.
`texturedata_t` is a union:
```c
// RGBA:
data.rgbaColors = colorArray;
// Paletted:
data.paletted.indices = indexArray;
data.paletted.palette = &palette; // palette color count must be power of two
```
**Built-in textures** (defined in `texture.c`, no asset loading needed):
- `TEXTURE_WHITE` — 4×4 solid white
- `TEXTURE_TEST` — 4×4 black/magenta checkerboard
### Palette (`display/texture/palette.h`)
Up to `PALETTE_COUNT` (6) global palettes in `PALETTES[]`, each holding up to `PALETTE_COLOR_COUNT` (255) `color_t` entries.
### Tileset (`display/texture/tileset.h`)
A tileset slices a texture into a grid of equal-sized tiles. Used by fonts and UI frames. The tileset does not own the texture — it references a `texture_t *`.
---
## SpriteBatch (`display/spritebatch/`)
The primary 2D/billboard drawing primitive. Accumulates `spritebatchsprite_t` quads and flushes them in batches of `SPRITEBATCH_FLUSH_COUNT` (16) sprites at a time.
```c
// Per frame:
spriteBatchClear();
spriteBatchBuffer(sprites, count, &SHADER_UNLIT, material); // auto-flushes when batch full
spriteBatchFlush(); // flush remaining
// Low-level: write directly to an external mesh (for baking static geometry):
spriteBatchBufferToMesh(sprites, count, vertices, verticesSize);
```
`spritebatchsprite_t`:
```c
typedef struct {
vec3 min, max; // 3D bounding box
vec2 uvMin, uvMax; // texture region
} spritebatchsprite_t;
```
The global `SPRITEBATCH` and its vertex backing array `SPRITEBATCH_VERTICES[]` are defined externally to the struct to satisfy alignment requirements on certain platforms.
---
## Text (`display/text/`)
Text rendering uses `FONT_DEFAULT` (loaded during `textInit()`), which references a texture and a tileset. Characters start at ASCII `!` (`TEXT_CHAR_START`).
```c
textDraw(x, y, "Hello", COLOR_WHITE, &FONT_DEFAULT);
textMeasure("Hello", &FONT_DEFAULT, &outWidth, &outHeight);
// Single-char sprite for manual layout:
spritebatchsprite_t s = textGetSprite(pos, 'A', &FONT_DEFAULT);
```
`font_t` holds a `texture_t *` and a `tileset_t *` — both are owned by the asset system, not the font struct.
+93
View File
@@ -0,0 +1,93 @@
# Input System
Source: `src/dusk/input/`
The input system decouples physical hardware buttons from logical game actions via a binding layer. Actions are defined in `src/dusk/input/input.csv` and code-generated into `inputaction_t` enum values — see [architecture.md](architecture.md#code-generation-from-csv).
---
## Concepts
**Button** (`inputbutton_t`) — a physical input source: a keyboard scancode, gamepad button, gamepad axis, or pointer axis. The available button types depend on which `DUSK_INPUT_*` defines are active for the target platform.
**Action** (`inputaction_t`) — a logical game input (e.g. `INPUT_ACTION_UP`, `INPUT_ACTION_CONFIRM`, `INPUT_ACTION_RAGEQUIT`). Each action accumulates a float value `[0.0, 1.0]` from all buttons bound to it.
**Binding** — a many-to-one mapping from buttons to actions. Bindings are registered at runtime with `inputBind(button, action)`.
---
## Querying actions
```c
// Boolean helpers (current frame):
inputIsDown(action) // value > 0 this frame
inputPressed(action) // down this frame but not last
inputReleased(action) // down last frame but not this
// Last frame state:
inputWasDown(action)
// Raw float value:
inputGetCurrentValue(action) // [0.0, 1.0]
inputGetLastValue(action)
// Axis helpers — combine two opposing actions into a signed float:
float_t h = inputAxis(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT); // -1.0 to 1.0
inputAxis2D(negX, posX, negY, posY, result); // fills vec2
inputAngle2D(negX, posX, negY, posY, result); // atan2-based normalized direction
// Deadzone:
float_t clean = inputDeadzone(rawValue, 0.1f);
```
---
## Dynamic values (`DUSK_TIME_DYNAMIC`)
On platforms with variable frame rates, each action also tracks `dynamicDelta`-scaled values:
```c
inputGetCurrentValueDynamic(action)
inputGetLastValueDynamic(action)
```
These account for the actual time elapsed since the last frame, so movement calculated from them is frame-rate independent.
---
## Events on actions
Each `inputactiondata_t` exposes `onPressed` and `onReleased` events:
```c
eventSubscribe(&INPUT.actions[INPUT_ACTION_CONFIRM].onPressed, myCallback, myUser);
```
The callback signature is `void cb(void *params, void *user)`. `params` is always `NULL` for input events.
---
## Buttons and bindings
Physical buttons are typed via `inputbuttontype_t`:
| Constant | When available | Payload |
|---|---|---|
| `INPUT_BUTTON_TYPE_KEYBOARD` | `DUSK_INPUT_KEYBOARD` | `inputscancode_t` |
| `INPUT_BUTTON_TYPE_GAMEPAD` | `DUSK_INPUT_GAMEPAD` | `inputgamepadbutton_t` |
| `INPUT_BUTTON_TYPE_GAMEPAD_AXIS` | `DUSK_INPUT_GAMEPAD` | axis + positive direction flag |
| `INPUT_BUTTON_TYPE_POINTER` | `DUSK_INPUT_POINTER` | `inputpointeraxis_t` |
Button names and default bindings are defined in `input.csv`. Look up a button by name:
```c
inputbutton_t btn = inputButtonGetByName("keyboard_w");
inputBind(btn, INPUT_ACTION_UP);
```
`INPUT_BUTTON_DATA[]` holds runtime state (current/last raw values) for every physical button.
---
## Platform platform-specific reads
`inputButtonGetValuePlatform(button)` is the one required platform function — it returns the current raw `[0.0, 1.0]` value for a button. The platform implementations live in `src/dusk{platform}/input/`.
+149
View File
@@ -0,0 +1,149 @@
# Cutscenes
Two distinct layers: a low-level engine sequencer (`src/dusk/cutscene/`) and a higher-level RPG wrapper (`src/dusk/rpg/cutscene/`). Almost all game code works with the RPG layer.
---
## Engine sequencer (`src/dusk/cutscene/`)
`cutscene_t CUTSCENE` is a minimal event runner with up to `CUTSCENE_EVENT_COUNT_MAX` (16) `cutsceneevent_t` slots. Each event has three callbacks:
```c
typedef struct {
errorret_t (*onStart)(void);
errorret_t (*onUpdate)(void);
errorret_t (*onEnd)(void);
} cutsceneevent_t;
```
API:
```c
cutscenePlay(events, count); // copy events array and start from index 0
cutsceneAdvance(); // end current event, start next (deactivates after last)
cutsceneStop(); // abort immediately
cutsceneIsActive(); // bool
```
This layer is primarily used by the RPG cutscene system — game code doesn't normally touch it directly.
---
## RPG cutscene layer (`src/dusk/rpg/cutscene/`)
### Data structures
A `cutscene_t` is just a pointer to an item array and a count:
```c
typedef struct cutscene_s {
const cutsceneitem_t *items;
uint8_t itemCount;
} cutscene_t;
```
A `cutsceneitem_t` is a tagged union of all item types:
```c
typedef struct cutsceneitem_s {
cutsceneitemtype_t type;
union {
cutscenetext_t text; // display text in textbox
cutscenecallback_t callback; // call a void(*)(void) function
cutscenewait_t wait; // pause for a fixed_t duration (seconds)
const cutscene_t *cutscene; // nest another cutscene
};
} cutsceneitem_t;
```
### Item types
| Type constant | Payload | Behaviour |
|---|---|---|
| `CUTSCENE_ITEM_TYPE_TEXT` | `cutscenetext_t``text[256]` + `rpgtextboxpos_t position` | Shows textbox; advances on player confirm input |
| `CUTSCENE_ITEM_TYPE_CALLBACK` | `cutscenecallback_t` (function pointer) | Calls the function once, then immediately advances |
| `CUTSCENE_ITEM_TYPE_WAIT` | `cutscenewait_t` (a `fixed_t` in seconds) | Counts down `animTime` each frame, then advances |
| `CUTSCENE_ITEM_TYPE_CUTSCENE` | `const cutscene_t *` | Plays the nested cutscene before continuing |
### Runtime state
`cutscenesystem_t CUTSCENE_SYSTEM` tracks:
- `scene` — pointer to the active `cutscene_t`
- `currentItem` — index into `scene->items[]`
- `data` — per-item runtime data (`cutsceneitemdata_t`, currently just `cutscenewaitdata_t`)
- `mode` — the current `cutscenemode_t`
API:
```c
cutsceneSystemStartCutscene(cutscene); // begin playing a cutscene
cutsceneSystemNext(); // advance to next item
cutsceneSystemUpdate(); // called each frame from rpgUpdate
cutsceneSystemGetCurrentItem(); // inspect active item
```
### Cutscene mode (`cutscenemode.h`)
Each item can run in one of three modes:
```c
CUTSCENE_MODE_NONE // no cutscene active
CUTSCENE_MODE_FULL_FREEZE // pause everything (not yet used)
CUTSCENE_MODE_INPUT_FREEZE // player input blocked (default: CUTSCENE_MODE_INITIAL)
CUTSCENE_MODE_GAMEPLAY // player can still move during cutscene
```
`cutsceneModeIsInputAllowed()` is checked by `entityUpdate()` before invoking the movement callback — the player cannot walk when in INPUT_FREEZE mode.
### Defining a cutscene
Cutscenes are defined as `static const` arrays in header files under `rpg/cutscene/scene/`. Example (`testcutscene.h`):
```c
static const cutsceneitem_t MY_CUTSCENE_ITEMS[] = {
{
.type = CUTSCENE_ITEM_TYPE_TEXT,
.text = { .text = "Hello!", .position = RPG_TEXTBOX_POS_BOTTOM }
},
{
.type = CUTSCENE_ITEM_TYPE_WAIT,
.wait = FIXED(1.5f)
},
{
.type = CUTSCENE_ITEM_TYPE_CUTSCENE,
.cutscene = &ANOTHER_CUTSCENE
},
};
static const cutscene_t MY_CUTSCENE = {
.items = MY_CUTSCENE_ITEMS,
.itemCount = sizeof(MY_CUTSCENE_ITEMS) / sizeof(cutsceneitem_t)
};
```
Attach to an NPC via its interact component:
```c
entity->interact.type = ENTITY_INTERACT_CUTSCENE;
entity->interact.data.cutscene = &MY_CUTSCENE;
```
---
## Textbox (`src/dusk/rpg/rpgtextbox.h`)
`rpgtextbox_t RPG_TEXTBOX` is the global textbox state:
```c
typedef struct {
rpgtextboxpos_t position; // RPG_TEXTBOX_POS_TOP or RPG_TEXTBOX_POS_BOTTOM
bool_t visible;
char_t text[RPG_TEXTBOX_MAX_CHARS]; // 256 chars
} rpgtextbox_t;
```
API:
```c
rpgTextboxShow(position, text); // copies text, sets visible = true
rpgTextboxHide(); // sets visible = false
rpgTextboxIsVisible(); // bool
```
The textbox state is read by `ui/uitextbox.c` during the UI render pass to draw the dialogue box on screen. `rpgtextbox.c` itself does no rendering.
+140
View File
@@ -0,0 +1,140 @@
# Entities
Source: `src/dusk/rpg/entity/`
---
## Storage
Entities live in a single fixed global array:
```c
entity_t ENTITIES[ENTITY_COUNT]; // ENTITY_COUNT = 64
```
A slot is "empty" when `entity->type == ENTITY_TYPE_NULL`. Never allocate entity memory dynamically — always find a free slot with `entityGetAvailable()`, which returns its index (`0xFF` if none free).
---
## `entity_t` structure
```c
typedef struct entity_s {
uint8_t id; // index in ENTITIES[]
entitytype_t type; // ENTITY_TYPE_NULL / PLAYER / NPC
entitytypedata_t data; // union: player_t | npc_t
entitydir_t direction; // facing direction (N/S/E/W)
fixed_t position[3]; // current sub-tile position (x, y, z)
fixed_t lastPosition[3]; // position before last move (for interpolation)
entityanim_t animation; // IDLE / TURN / WALK
fixed_t animTime; // countdown timer for current animation
entityinteract_t interact; // optional interact component
} entity_t;
```
---
## Type system
Entity types are defined in `entitytype.h` using the enum+integer-typedef pattern:
```c
typedef enum { ENTITY_TYPE_NULL, ENTITY_TYPE_PLAYER, ENTITY_TYPE_NPC, ENTITY_TYPE_COUNT } entitytype_enum_t;
typedef uint8_t entitytype_t;
```
Each type has a `entitycallback_t` entry in the `ENTITY_CALLBACKS[ENTITY_TYPE_COUNT]` static table:
```c
typedef struct {
void (*init)(entity_t *entity);
void (*movement)(entity_t *entity);
bool_t (*interact)(entity_t *player, entity_t *entity);
} entitycallback_t;
```
Callbacks not applicable to a type are `NULL`; `entityUpdate()` guards against this before calling.
Type-specific data sits in `entitytypedata_t` (a union of `player_t` and `npc_t`). Currently both are stubs (`void *nothing`).
---
## Direction (`entitydir.h`)
```c
ENTITY_DIR_NORTH / EAST / SOUTH / WEST
```
Aliases: `UP = NORTH`, `DOWN = SOUTH`, `LEFT = WEST`, `RIGHT = EAST`.
Utilities:
- `entityDirGetOpposite(dir)` — returns the opposite direction.
- `entityDirGetRelative(dir, &relX, &relY)` — fills in the ±1 XY delta for that direction.
- `assertValidEntityDir(dir, msg)` — assertion macro.
---
## Animation (`entityanim.h`)
```c
ENTITY_ANIM_IDLE // standing still
ENTITY_ANIM_TURN // turning to a new direction (ENTITY_ANIM_TURN_DURATION = FIXED(0.06))
ENTITY_ANIM_WALK // mid-step (ENTITY_ANIM_WALK_DURATION = FIXED(0.1))
```
`entityAnimUpdate(entity)` decrements `animTime` each frame and transitions back to `IDLE` when it reaches zero.
`entityCanWalk(entity)` / `entityCanTurn(entity)` both return true only when `animation == ENTITY_ANIM_IDLE`.
The renderer interpolates between `lastPosition` and `position` using `animTime / WALK_DURATION` to produce smooth motion even at low frame rates.
---
## Movement
`entityWalk(entity, direction)`:
1. Converts `entity->position` to a `worldpos_t` (truncates fractional part).
2. Applies the directional delta to get `newPos`.
3. Checks the current and target tiles for ramp raise/fall logic (see [world.md](world.md)).
4. Checks `ENTITIES[]` for another entity occupying `newPos` — blocks if found.
5. On success: copies `position` to `lastPosition`, updates `position` to `newPos` (via `worldPosToFixed`), sets `animation = ENTITY_ANIM_WALK`.
`entityTurn(entity, direction)`: sets `direction` and starts a brief turn animation.
---
## Interaction (`entityinteract.h`)
The `entityinteract_t` component is embedded in every entity. It is optional — set `type = ENTITY_INTERACT_NULL` for non-interactable entities.
```c
typedef enum {
ENTITY_INTERACT_NULL,
ENTITY_INTERACT_CUTSCENE, // plays a cutscene_t *
ENTITY_INTERACT_PRINT, // prints a short message[32]
} entityinteracttype_t;
```
`entityInteractWith(player, target)` dispatches:
1. If the interact component's `type != NULL`, handles it (starts the cutscene or prints the message).
2. Otherwise falls back to `ENTITY_CALLBACKS[type].interact` if set.
---
## Player (`player.h` / `player.c`)
`playerInit()` is called via `ENTITY_CALLBACKS[ENTITY_TYPE_PLAYER].init`.
`playerInput(entity)` is the movement callback. It reads `PLAYER_INPUT_DIR_MAP[]` — a static table mapping input actions (`INPUT_ACTION_UP/DOWN/LEFT/RIGHT`) to entity directions — and calls `entityWalk` or `entityTurn` accordingly.
The player entity is normally `ENTITIES[0]` but there is no hardcoded assumption about its index beyond being initialized with `ENTITY_TYPE_PLAYER`.
---
## NPC (`npc.h` / `npc.c`)
`npcInit()`, `npcMovement()`, and `npcInteract()` provide the NPC type callbacks. Currently stubs; movement does nothing, interact returns false.
+18
View File
@@ -0,0 +1,18 @@
# RPG Layer
The RPG layer lives in `src/dusk/rpg/` and is the game-logic tier above the engine. It is initialized and ticked by `engine.c` via `rpgInit` / `rpgUpdate` / `rpgDispose`. The `rpg_t` struct is currently a stub; all meaningful state lives in the subsystems below.
## Contents
- [world.md](world.md) — scene manager, overworld map, chunks, tiles, coordinate system, camera
- [entity.md](entity.md) — entity pool, types, direction, animation, interaction, player, NPC
- [cutscene.md](cutscene.md) — cutscene system, item types, mode control, textbox
- [story.md](story.md) — story flags, items, inventory, backpack, save system
## Scene system
The scene manager (`src/dusk/scene/`) sits above the RPG layer and owns the single active scene. Scenes are identified by `scenetype_t` and registered in `SCENE_TYPES[]` (`scene/scenetype.c`) as `scenecallbacks_t` (init / update / render / dispose).
`scenedata_t` is a union so all scene structs share memory. `sceneSet(type)` defers the transition — the old scene disposes before the new one inits.
Currently the only scene is `SCENE_TYPE_OVERWORLD``src/dusk/scene/overworld/sceneoverworld.c`.
+124
View File
@@ -0,0 +1,124 @@
# Story, Items & Save
---
## Story flags (`src/dusk/rpg/story/`)
Story flags are the primary mechanism for tracking game-world state (quest progress, one-time events, unlocks). Each flag is a `uint8_t` value (`storyflagvalue_t`), so they can hold booleans or small counts.
### Defining flags
Flags are defined in `src/dusk/rpg/story/storyflag.csv`:
```
id,description,initial
test,"Test flag for debugging purposes",1
```
The build tool generates:
- A `storyflag_t` enum (e.g. `STORY_FLAG_TEST`) in the generated header.
- `STORY_FLAG_VALUES[]` — the runtime array, pre-populated with the `initial` column values.
To add a flag: add a row to the CSV. The build re-runs the Python tool automatically on the next CMake build.
### Access
```c
storyflagvalue_t v = storyFlagGet(STORY_FLAG_TEST); // macro: array read
storyFlagSet(STORY_FLAG_TEST, 1); // function: also marks save dirty
```
`storyFlagGet` is a macro that directly indexes `STORY_FLAG_VALUES[]` — no function call overhead.
---
## Items (`src/dusk/rpg/item/`)
### Item definitions
Items are defined in `src/dusk/rpg/item/item.csv`. The build tool generates `itemid_t` enum values and item metadata. `itemid_t` is a generated `uint8_t` typedef.
### Inventory (`inventory.h`)
`inventory_t` is a generic container backed by a caller-supplied `inventorystack_t` array:
```c
typedef struct {
itemid_t item;
uint8_t quantity; // max ITEM_STACK_QUANTITY_MAX (255)
} inventorystack_t;
typedef struct {
inventorystack_t *storage;
uint8_t storageSize;
} inventory_t;
```
Key operations:
```c
inventoryInit(&inv, storageArray, size);
inventoryAdd(&inv, ITEM_POTION, 3);
inventoryRemove(&inv, ITEM_POTION);
inventorySet(&inv, ITEM_POTION, 10);
inventoryGetCount(&inv, ITEM_POTION); // returns 0 if not present
inventoryItemExists(&inv, ITEM_POTION);
inventoryIsFull(&inv);
inventorySort(&inv, INVENTORY_SORT_BY_ID, false);
```
`inventory_t` itself holds no data — the backing array is always external. This avoids fixed-size struct limits and lets different inventories (backpack, shop, chest) share the same logic.
### Backpack (`backpack.h`)
The player's inventory is the global `BACKPACK` instance:
```c
extern inventorystack_t BACKPACK_STORAGE[BACKPACK_STORAGE_SIZE_MAX]; // 20 slots
extern inventory_t BACKPACK;
backpackInit(); // wires BACKPACK_STORAGE into BACKPACK
```
---
## Save system (`src/dusk/save/`)
The save system is stubbed out — it exists and compiles but is commented out of engine init (`engine.c`). What follows describes the design as implemented.
### Slots
`save_t SAVE` holds `SAVE_FILE_COUNT_MAX` slots:
```c
typedef struct {
savefile_t files[SAVE_FILE_COUNT_MAX];
saveplatform_t platform; // platform-specific state (paths, card handles)
} save_t;
```
### Streams
`savestream_t` (`save/savestream.h`) is a raw byte cursor used to serialize/deserialize `savefile_t`. Platform backends in `src/dusk{platform}/save/` implement the actual I/O:
- Linux: filesystem files in a save directory.
- GameCube/Wii: memory card via libogc.
### API
```c
saveInit();
saveLoad(slot); // reads platform storage → savefile_t
saveWrite(slot); // writes savefile_t → platform storage
saveDelete(slot);
saveExists(slot); // bool
saveGet(slot); // returns savefile_t *
saveDispose();
```
---
## Locale / i18n (`src/dusk/locale/`)
Translations are loaded from `.po` files in `assets/locale/` (e.g. `en_US.po`). `localemanager.c` manages the active locale and exposes a key→string lookup. `assetlocaleloader.c` parses the PO format via the asset system.
All player-visible strings must go through the locale system rather than being hardcoded. The locale is loaded asynchronously via the asset system so it is available before the first scene renders.
+114
View File
@@ -0,0 +1,114 @@
# World
Source: `src/dusk/rpg/overworld/`
---
## Coordinate system
Three nested coordinate spaces, each defined in `worldpos.h`:
| Type | Description | Unit |
|---|---|---|
| `worldpos_t` | Tile-level absolute position `{x, y, z}` | `worldunit_t` (int16) |
| `chunkpos_t` | Chunk-grid position `{x, y, z}` | `chunkunit_t` (int16) |
| `fixed_t[3]` | Smooth sub-tile position used by entities | Q24.8 fixed-point |
One chunk = `CHUNK_WIDTH × CHUNK_HEIGHT × CHUNK_DEPTH` tiles (16 × 16 × 8).
The loaded world window = `MAP_CHUNK_WIDTH × MAP_CHUNK_HEIGHT × MAP_CHUNK_DEPTH` chunks (5 × 5 × 3).
Conversion helpers (all in `worldpos.c`):
```c
worldPosToChunkPos(&worldPos, &chunkPos); // tile → chunk grid
chunkPosToWorldPos(&chunkPos, &worldPos); // chunk grid → tile origin
worldPosToChunkTileIndex(&worldPos); // tile → index within its chunk
chunkPosToIndex(&chunkPos); // chunk grid → linear index in MAP.chunks[]
worldPosToFixed(&worldPos, fixedOut); // tile → entity fixed position
fixedToWorldPos(fixedPos); // entity fixed → tile (truncates frac)
```
---
## Tiles
Defined in `tile.h` as a plain `tile_t` enum:
```
TILE_SHAPE_NULL — empty / unloaded
TILE_SHAPE_GROUND — solid flat tile
TILE_SHAPE_RAMP_* — directional ramps (N/S/E/W + diagonals NE/NW/SE/SW)
```
Key predicates:
- `tileIsWalkable(tile)` — true for GROUND and all ramp shapes.
- `tileIsRamp(tile)` — true only for ramp shapes.
Entity walk code (`entity.c`) checks both the current tile and the target tile to decide whether the entity steps forward flat, raises one Z level (walking up a ramp), or falls one Z level (stepping onto a downward ramp from above).
---
## Chunks
`chunk_t` (`chunk.h`) holds:
- `position` — its `chunkpos_t` in the world grid
- `tiles[CHUNK_TILE_COUNT]` — flat array of `tile_t`, indexed by `chunkGetTileIndex()`
- `vertices[CHUNK_VERTEX_COUNT]` / `mesh` — pre-baked mesh uploaded to GPU on load
- `entities[CHUNK_ENTITY_COUNT_MAX]` — indices into `ENTITIES[]` currently in this chunk (sentinel `0xFF`)
- `testColor` — temporary debug color (checkerboard), will be replaced by real tileset data
Tile layout within a chunk is `z * W*H + y * W + x` (Z-major, row-major in XY).
---
## Map
`map_t MAP` (`map.h`) is the single global map instance.
```c
chunk_t chunks[MAP_CHUNK_COUNT]; // flat storage — index is NOT world position
chunk_t *chunkOrder[MAP_CHUNK_COUNT]; // draw-order sorted pointers into chunks[]
chunkpos_t chunkPosition; // world-grid origin of the loaded window
bool_t loaded;
```
### Load / unload
`mapInit()` allocates chunk meshes and performs the initial load of all chunks in the starting window.
`mapPositionSet(newPos)` shifts the window:
1. Determines which of the `MAP_CHUNK_COUNT` slots remain within the new window vs. fall outside it.
2. Calls `mapChunkUnload()` on every chunk that falls outside (nulls its entity slots, zeroes `vertCount`).
3. Reuses freed slots for newly-in-range chunks; calls `mapChunkLoad()` on each.
4. Rebuilds `chunkOrder[]` in XYZ order for the new position.
### Chunk load (current stub)
`mapChunkLoad()` currently:
- Fills all tiles with `TILE_SHAPE_GROUND`
- Assigns a checkerboard debug color based on chunk XY parity
- Bakes a flat sprite-batch quad mesh for the z=0 layer and uploads it via `meshFlush()`
- Skips mesh generation for z > 0 chunks (they're empty)
### Tile lookup
```c
tile_t mapGetTile(const worldpos_t position);
```
Converts `position` to its chunk, looks up the chunk in `chunkOrder`, then indexes into `chunk->tiles[]`. Returns `TILE_SHAPE_NULL` for any out-of-bounds position or when the map is not loaded.
---
## Camera
`rpgcamera_t RPG_CAMERA` (`rpgcamera.h`) has two modes:
```c
RPG_CAMERA_MODE_FREE // free worldpos; camera.free holds the position
RPG_CAMERA_MODE_FOLLOW_ENTITY // tracks ENTITIES[followEntityId]
```
`rpgCameraGetPosition()` returns the active world tile position in either mode.
The scene renderer (`sceneoverworld.c`) uses `rpgCameraGetPosition()` to build the `glm_lookat` view matrix. When following an entity, it sub-tile interpolates between `entity->lastPosition` and `entity->position` using `entity->animTime / ENTITY_ANIM_WALK_DURATION` to smooth movement.
+96
View File
@@ -0,0 +1,96 @@
# Save & Locale
---
## Save system (`src/dusk/save/`)
Slot-based persistent storage. Currently disabled in engine init (commented out in `engine.c`) — the system is fully implemented but not yet wired up.
### Slots
Up to `SAVE_FILE_COUNT_MAX` (3) save slots. The global `SAVE` holds all slots:
```c
saveInit();
saveExists(slot); // bool_t — check before load
saveLoad(slot); // read from platform storage → SAVE.files[slot]
saveWrite(slot); // write SAVE.files[slot] → platform storage
saveDelete(slot);
savefile_t *f = saveGet(slot);
saveDispose();
```
### Save file format
`savefile_t` is the serialized struct stored per slot. Currently minimal:
```c
typedef struct {
char_t header[3]; // "DSK"
uint32_t version; // SAVE_FILE_VERSION = 1
bool_t exists;
} savefile_t;
```
Extend this struct to add game-specific save data (player position, story flags, etc.).
### Stream serialization (`save/savestream.h`)
`savestream_t` is a cursor used to read/write a save slot's bytes. It CRC32-checksums all data written through it and verifies the checksum on read.
Write a save:
```c
savestream_t stream;
// (platform opens stream for slot)
saveFileWriteHeader(&stream, SAVE_FILE_HEADER);
saveFileWriteVersion(&stream, SAVE_FILE_VERSION);
saveFileWriteBool(&stream, myFlag);
saveFileWriteInt32(&stream, myInt);
saveFileWriteString(&stream, myString, sizeof(myString));
saveStreamFinalizeWriteImpl(&stream); // writes CRC
```
Read a save:
```c
saveFileReadHeader(&stream, headerBuf);
saveFileReadVersion(&stream, &version);
saveFileReadBool(&stream, &myFlag);
saveFileReadInt32(&stream, &myInt);
saveFileReadString(&stream, myString, sizeof(myString));
saveStreamVerifyChecksumImpl(&stream, slot); // returns error if CRC mismatch
```
All multi-byte values are stored in little-endian byte order. The `saveFile*` macros are thin wrappers over the `*Impl` functions that integrate `errorChain` — always use the macros.
### Platform backends
Each `src/dusk{platform}/save/` provides `saveplatform_t` (e.g. a file path on Linux, a memory-card handle on GameCube). The stream implementations (`savestream{platform}.c`) do the actual I/O.
---
## Locale / i18n (`src/dusk/locale/`)
Translations are stored as GNU `.po` files in `assets/locale/`. Only `en_US.po` currently exists.
### Loading
`localemanager_t LOCALE` tracks the active locale and its in-progress asset entry:
```c
localeManagerInit(); // loads en_US by default
localeManagerSetLocale(&LOCALE_EN_US); // switch locale (async load)
localeManagerDispose();
```
`LOCALE_EN_US` is a predefined `localeinfo_t` constant (`name = "en-US"`, `file = "locale/en_US.po"`).
### Looking up strings
```c
char_t buf[128];
localeManagerGetText("my.key", buf, sizeof(buf), 1, /* format args */ );
```
The macro handles plural forms and `printf`-style format arguments. Pass plural `1` for singular, any other value for plural.
`assetlocaleloader.c` parses the `.po` format (msgid / msgstr pairs) into a key→string table during the async asset load phase.
+403
View File
@@ -0,0 +1,403 @@
# Coding Style
All source is C11. Everything below is derived from the existing codebase — match it exactly.
---
## File structure
### Headers (`.h`)
```c
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "direct/dependency.h"
```
- `#pragma once` always, never `#ifndef` guards.
- No blank line between the license block and `#pragma once`.
- One blank line between `#pragma once` and the first `#include`.
### Sources (`.c`)
```c
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "thisfile.h"
#include "assert/assert.h"
#include "util/memory.h"
```
- First include is always the matching `.h` for this `.c` file.
- Remaining includes follow with no separator unless logically grouped (then one blank line between groups — see [Include order](#include-order)).
---
## Include order
In `.c` files, include in this order with a blank line between each group:
1. The matching header (e.g. `#include "entity.h"`)
2. Core utilities (`assert/assert.h`, `util/memory.h`, `util/math.h`, etc.)
3. Engine subsystems (`display/...`, `input/...`, etc.)
4. Domain subsystems (`rpg/...`, `scene/...`, etc.)
In `.h` files, only include what the header directly requires. Never include more than necessary to make the type definitions in that header compile.
All include paths are relative to `src/dusk/` (the root include directory). Use the full path:
```c
#include "rpg/overworld/map.h" // correct
#include "map.h" // wrong
```
---
## Line length
80-character limit. Break before it, not after.
Multi-parameter function signatures break one param per line, with 2-space indent, closing `)` on its own line before `{`:
```c
errorret_t textureInit(
texture_t *texture,
const int32_t width,
const int32_t height,
const textureformat_t format,
const texturedata_t data
) {
```
Same rule for calls that don't fit on one line:
```c
assertTrue(
data.paletted.palette->count ==
mathNextPowTwo(data.paletted.palette->count),
"Palette color count must be a power of 2"
);
```
---
## Indentation and spacing
- **2 spaces** per indent level. No tabs.
- No space between a control keyword and its `(`:
```c
if(x) { // correct
if (x) { // wrong
```
- No space between a function name and its `(` in either declarations or calls.
- Opening brace on the same line:
```c
void entityUpdate(entity_t *entity) {
if(x) {
for(int i = 0; i < n; i++) {
```
- Closing brace always on its own line, except `} else {` and `} while(...)`.
- One blank line between function definitions in `.c` files.
- No trailing whitespace.
---
## Naming
| Kind | Convention | Example |
|---|---|---|
| Types (struct/union/typedef) | `snake_case_t` | `entity_t`, `worldpos_t` |
| Struct tags | `struct name_s` | `struct entity_s` |
| Union tags | `union name_u` | `union texturedata_u` |
| Enum tags (when typedef'd separately) | `name_enum_t` | `entitytype_enum_t` |
| Functions | `subsystemVerb` (camelCase, noun-first) | `entityInit`, `mapGetTile` |
| Macro constants | `UPPER_SNAKE_CASE` | `CHUNK_WIDTH`, `FIXED_ONE` |
| Function-like macros | `camelCase` (same as functions) | `errorThrow`, `assertNotNull` |
| Global subsystem instances | `UPPER_SNAKE_CASE` | `ENGINE`, `MAP`, `ENTITIES` |
| Local variables | `camelCase` | `tileNew`, `spriteCount` |
| Parameters | `camelCase` | `texture`, `worldPos` |
Subsystem prefix always comes first in function names: `textureInit`, `shaderBind`, `spriteBatchFlush`. The verb describes the action: `Init`, `Update`, `Dispose`, `Get`, `Set`, `Is`, etc.
---
## Typedefs
### Structs
```c
typedef struct {
uint8_t id;
entitytype_t type;
} entity_t;
```
Use a named tag (`struct entity_s`) only when forward declaration is required:
```c
typedef struct entity_s {
// ...
} entity_t;
```
### Unions
```c
typedef union texturedata_u {
struct {
uint8_t *indices;
palette_t *palette;
} paletted;
color_t *rgbaColors;
} texturedata_t;
```
### Enums
When the enum values need to be a compact integer (common for arrays and flags), declare the enum separately and typedef an integer type:
```c
typedef enum {
ENTITY_TYPE_NULL,
ENTITY_TYPE_PLAYER,
ENTITY_TYPE_NPC,
ENTITY_TYPE_COUNT
} entitytype_enum_t;
typedef uint8_t entitytype_t; // actual type used everywhere
```
Always include `_NULL` as the first value (zero) and `_COUNT` as the last value.
---
## `#define` constants
All-caps, underscores. Wrap multi-token expressions in parentheses:
```c
#define CHUNK_WIDTH 16
#define CHUNK_HEIGHT CHUNK_WIDTH
#define CHUNK_TILE_COUNT (CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_DEPTH)
```
Multi-line macros: backslash continuation, body indented 2 spaces, closing line has no backslash:
```c
#define errorThrow(message, ...) \
return errorThrowImpl(\
&ERROR_STATE, ERROR_NOT_OK, __FILE__, __func__, __LINE__, (message), \
##__VA_ARGS__ \
)
```
---
## `const` usage
Mark every pointer and value parameter `const` unless the function modifies it:
```c
void entityTurn(entity_t *entity, const entitydir_t direction);
errorret_t textureInit(texture_t *texture, const int32_t width, ...);
```
`entity_t *entity` is non-const because the function writes to it; `direction` is const because it is read-only.
---
## `void` in no-argument functions
Use `(void)` in definitions and declarations of zero-parameter functions:
```c
errorret_t engineUpdate(void);
errorret_t spriteBatchFlush(void);
```
---
## Unused parameters
Do **not** use `(void)param;` casts to suppress unused-parameter warnings. They are
redundant noise. If a callback signature is fixed by a function-pointer type and the
parameter is genuinely unused, just leave it — do not suppress:
```c
// correct — parameter unused, no cast
errorret_t sceneTestUpdate(scenedata_t *data) {
errorOk();
}
// wrong
errorret_t sceneTestUpdate(scenedata_t *data) {
(void)data;
errorOk();
}
```
---
## Global subsystem state
Each subsystem exposes a single global instance declared `extern` in the header and defined (once) in the `.c` file:
```c
// entity.h
extern entity_t ENTITIES[ENTITY_COUNT];
// entity.c
entity_t ENTITIES[ENTITY_COUNT];
```
Never define a subsystem global as `static` in a header.
---
## Assertions
Place assertions at the very top of a function, before any logic:
```c
void entityInit(entity_t *entity, const entitytype_t type) {
assertNotNull(entity, "Entity pointer cannot be NULL");
assertTrue(type < ENTITY_TYPE_COUNT, "Invalid entity type");
// ... actual logic
}
```
Available assertion macros (from `assert/assert.h`):
- `assertNotNull(ptr, msg)`
- `assertNull(ptr, msg)`
- `assertTrue(expr, msg)`
- `assertFalse(expr, msg)`
- `assertUnreachable(msg)`
- `assertStringEqual(a, b, msg)`
- `assertIsMainThread(msg)` / `assertNotMainThread(msg)`
---
## Error handling style
Functions that can fail return `errorret_t`. Three patterns:
```c
// Propagate a child call's failure and return from this function:
errorChain(someCall());
// Return success:
errorOk();
// Return failure:
errorThrow("Descriptive message %s", variable);
```
`errorChain` is used inline — do not capture the result first:
```c
errorChain(textureInitPlatform(texture, width, height, format, data)); // correct
errorret_t r = textureInitPlatform(...); errorChain(r); // wrong
```
---
## Struct initialization
Use C99 designated initializers for any struct literal with more than one field:
```c
static const entitycallback_t ENTITY_CALLBACKS[ENTITY_TYPE_COUNT] = {
[ENTITY_TYPE_NULL] = { NULL },
[ENTITY_TYPE_PLAYER] = {
.init = playerInit,
.movement = playerInput
},
};
```
```c
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = NULL
}
};
```
---
## Fixed-size array iteration
Prefer pointer arithmetic with `do/while` over index loops for iterating through fixed global arrays:
```c
entity_t *ent = ENTITIES;
do {
if(ent->type == ENTITY_TYPE_NULL) continue;
// ...
} while(++ent, ent < &ENTITIES[ENTITY_COUNT]);
```
Use `for` loops when an index variable is actually needed.
---
## Comments
Comments explain *why*, not *what*. One short inline comment is fine; multi-line block comments for non-obvious invariants only.
```c
// Walking up a ramp — only the direction the ramp faces is valid.
if(tileIsRamp(tileCurrent) && ...) {
```
Section labels inside long functions are acceptable:
```c
// Chunks
{
...
}
// Entities
{
...
}
```
Doc comments on public functions use Javadoc style with `@param` / `@return`:
```c
/**
* Gets the tile at the given world position.
*
* @param position The world position.
* @return The tile at that position, or TILE_NULL if the chunk is unloaded.
*/
tile_t mapGetTile(const worldpos_t position);
```
---
## Platform-conditional code
Use the `DUSK_*` compile-definition macros set by `cmake/targets/<target>.cmake`:
```c
#ifdef DUSK_THREAD_PTHREAD
#include "thread/thread.h"
extern pthread_t ASSERT_MAIN_THREAD_ID;
#endif
```
Never use `#ifdef __linux__`, `#ifdef _WIN32`, etc. directly — go through the engine macros.
+177
View File
@@ -0,0 +1,177 @@
# Engine Systems
Smaller systems that support the engine but don't warrant their own file each.
---
## Time (`src/dusk/time/`)
`dusktime_t TIME` tracks fixed and dynamic delta time.
```c
TIME.delta // fixed_t: always DUSK_TIME_STEP (16ms default) on fixed-rate platforms
TIME.time // fixed_t: total elapsed time in seconds
```
On platforms with `DUSK_TIME_DYNAMIC` (Linux/SDL2):
```c
TIME.dynamicDelta // fixed_t: actual time since last frame
TIME.dynamicTime // fixed_t: total elapsed (dynamic)
TIME.dynamicUpdate // bool_t: true when a real tick occurred
```
Call `timeUpdate()` once per frame (before input/logic). `timeGetEpoch()` returns the current wall-clock time as a `dusktimeepoch_t`.
### Epoch time (`time/timeepoch.h`)
`dusktimeepoch_t` stores a Unix timestamp (double) with timezone offset. Utilities:
```c
dusktimeepoch_t e = timeGetEpoch();
timeEpochGetHours(e) // 023
timeEpochGetMinutes(e) // 059
timeEpochGetSeconds(e) // 059
timeEpochGetDayOfMonth(e) // 030
timeEpochGetMonth(e) // 011
timeEpochGetYear(e)
// Format: %Y year, %m month, %d day, %H hour, %M minute, %S second
timeEpochFormat(e, "%Y-%m-%d %H:%M:%S", buf, sizeof(buf));
// Compare: returns -1, 0, 1
timeEpochCompare(a, b);
// Timezone shift:
dusktimeepoch_t local = timeEpochSwitchTimeZone(e, offsetHours);
```
---
## Thread (`src/dusk/thread/`)
Currently only the pthread backend (`DUSK_THREAD_PTHREAD`) exists. Thread objects are `thread_t` — used primarily by the asset loader.
```c
threadInit(&thread, myCallback); // myCallback: void (*)(thread_t *)
threadStart(&thread); // blocks until thread is RUNNING
threadStop(&thread); // requests stop, blocks until STOPPED
// Inside the thread callback:
while(!threadShouldStop(&thread)) { /* work */ }
```
State flow: `STOPPED → STARTING → RUNNING → (STOP_REQUESTED) → STOPPED`.
### Mutex (`thread/threadmutex.h`)
```c
threadMutexInit(&lock);
threadMutexLock(&lock);
threadMutexUnlock(&lock);
threadMutexTryLock(&lock); // non-blocking; returns false if already held
threadMutexWaitLock(&lock); // release lock and sleep until signalled
threadMutexSignal(&lock); // wake a thread waiting on this mutex
threadMutexDispose(&lock);
```
### Thread-local storage
`THREAD_LOCAL` expands to `__thread` (GCC) on pthread platforms. Used for the per-thread error state (`ERROR_STATE` in `error/error.h`).
---
## Event (`src/dusk/event/`)
A fixed-capacity multicast callback list.
```c
// Declare backing arrays (choose a size):
eventcallback_t cbs[4];
void *users[4];
event_t myEvent;
eventInit(&myEvent, cbs, users, 4);
eventSubscribe(&myEvent, myCallback, myUser);
eventUnsubscribe(&myEvent, myCallback);
eventInvoke(&myEvent, params); // calls all subscribers; params passed as-is
```
Callback signature: `void cb(void *params, void *user)`.
`event_t` does not own its callback/user arrays. Always declare them alongside the event in the same struct or as static arrays.
---
## Console (`src/dusk/console/`)
`CONSOLE` is a scrolling in-game terminal for debug output. On POSIX platforms (`DUSK_CONSOLE_POSIX`) it also polls stdin in a thread so commands can be typed during a running session.
```c
consolePrint("Value is %d", x); // printf-style; thread-safe
consoleDraw(); // renders visible history lines to screen
```
Configuration constants (`consoledefs.h`):
- `CONSOLE_LINE_MAX` — 512 chars per line
- `CONSOLE_HISTORY_MAX` — 16 lines of scrollback
- `CONSOLE_EXEC_BUFFER_MAX` — 32 pending exec commands
`CONSOLE.visible` controls whether `consoleDraw()` actually renders anything.
---
## Log (`src/dusk/log/`)
Two simple output functions, implemented per-platform:
```c
logDebug("format %s", arg); // debug output (stdout on Linux, debug channel on consoles)
logError("format %s", arg); // error output; may pause execution on some platforms
```
These go directly to the platform's native output and are not buffered by the console history.
---
## System / Platform (`src/dusk/system/`)
`systemInit()` runs platform-specific startup (e.g. Wii PAD init, PSP kernel setup). Must be the first call in `engineInit()`.
```c
systemplatform_t p = systemGetPlatform(); // SYSTEM_PLATFORM_LINUX, _PSP, etc.
systemdialogtype_t d = systemGetActiveDialogType();
// SYSTEM_DIALOG_TYPE_NONE / RENDER_BLOCKING / TICK_BLOCKING
```
The full platform list is defined via X-macro in `system/systemplatformlist.h`:
| Constant | Value |
|---|---|
| `SYSTEM_PLATFORM_LINUX` | 0 |
| `SYSTEM_PLATFORM_KNULLI` | 1 |
| `SYSTEM_PLATFORM_PSP` | 2 |
| `SYSTEM_PLATFORM_GAMECUBE` | 3 |
| `SYSTEM_PLATFORM_WII` | 4 |
---
## Network (`src/dusk/network/`)
`network_t NETWORK` manages platform connection state. The engine calls `networkInit` / `networkUpdate` / `networkDispose`; game code uses the request API:
```c
networkRequestConnection(onConnected, onFailed, onDisconnect, user);
networkRequestDisconnection(onComplete, user);
networkIsConnected(); // bool_t
```
State machine: `DISCONNECTED → CONNECTING → CONNECTED → DISCONNECTING → DISCONNECTED`.
Network address info (after connection):
```c
networkinfo_t info = networkGetInfo();
// info.type = NETWORK_TYPE_IPV4 / IPV6
// info.ipv4.ip[4] or info.ipv6.ip[16]
```
Platform backends implement `networkPlatformInit/Update/Dispose/IsConnected`. Currently only Linux (socket-based) and PSP/Vita are implemented.
+123
View File
@@ -0,0 +1,123 @@
# UI System
Source: `src/dusk/ui/`
The UI system is an immediate-mode layer drawn on top of the game scene each frame. Elements register themselves; `uiUpdate()` ticks all elements and `uiRender()` draws them. All coordinates are in screen pixels.
---
## Lifecycle
```
uiInit() → uiTextboxInit() // init order matters — textbox depends on display being ready
uiUpdate() // each frame, before rendering
uiRender() // each frame, after scene render
uiDispose()
uiTextboxDispose()
```
---
## Element registration (`ui/uielement.h`)
Elements are stored in `UI_ELEMENTS[]`. Each has a type and a `draw` callback:
```c
typedef struct {
uielementtype_t type;
errorret_t (*draw)();
} uielement_t;
```
Currently `UI_ELEMENT_TYPE_NATIVE` elements call their `draw` function directly. New debug/HUD elements are registered by adding to this array.
---
## Textbox (`ui/uitextbox.h`)
`UI_TEXTBOX` is the global dialogue box. It word-wraps text, paginates it, and plays a typewriter scroll effect.
```c
uiTextboxSetText("Long dialogue string..."); // wraps to charsPerLine, paginates
uiTextboxUpdate(); // each frame: advance scroll, check input
uiTextboxDraw(); // draw box + text
// Pagination:
uiTextboxPageIsComplete() // true when all chars of current page are visible
uiTextboxHasNextPage()
uiTextboxNextPage()
// Subscibe to page events:
eventSubscribe(&UI_TEXTBOX.onPageComplete, cb, user);
eventSubscribe(&UI_TEXTBOX.onLastPage, cb, user);
```
`UI_TEXTBOX.advanceAction` defaults to the input action that advances dialogue — set it before calling `uiTextboxInit()` if the default doesn't suit.
Layout constants:
- `UI_TEXTBOX_TEXT_MAX` — 1024 chars
- `UI_TEXTBOX_LINES_MAX` — 64 lines
- `UI_TEXTBOX_LINES_PER_PAGE_MAX` — 3 lines visible at once
- `UI_TEXTBOX_SCROLL_CHARS_PER_TICK` — 1 char per tick (typewriter speed)
The textbox uses `UI_TEXTBOX.frame` (a `uiframe_t`) for its border rendering and `UI_TEXTBOX.font` for text.
---
## UI Frame (`ui/uiframe.h`)
9-slice bordered box rendered with a tileset:
```c
uiFrameInit(&frame);
uiFrameDraw(&frame, x, y, width, height);
uiFrameDispose(&frame);
```
The tileset is loaded from the asset system during `uiFrameInit()`. The 9 slices are arranged in the tileset grid as: top-left corner, top edge, top-right corner, left edge, fill, right edge, bottom-left, bottom edge, bottom-right.
---
## Loading overlay (`ui/uiloading.h`)
`UI_LOADING` is a full-screen loading indicator with fade-in/fade-out transitions:
```c
uiLoadingShow(onShownCallback, user); // fade in; calls callback when fully opaque
uiLoadingHide(onHiddenCallback, user); // fade out; calls callback when fully transparent
uiLoadingUpdate(delta); // each frame
uiLoadingDraw(); // each frame, over everything
```
`UI_LOADING_FADE_DURATION` is `FIXED(0.5f)` seconds. Subscribe to `UI_LOADING.onTransitionEnd` for completion events.
---
## Full-box overlay (`ui/uifullbox.h`)
Two global full-screen color overlays: `UI_FULLBOX_UNDER` (drawn before game content) and `UI_FULLBOX_OVER` (drawn after). Used for scene transitions (fade to black, etc.):
```c
uiFullboxTransition(
&UI_FULLBOX_OVER,
COLOR_TRANSPARENT, COLOR_BLACK,
FIXED(0.5f),
EASING_IN_OUT_CUBIC
);
eventSubscribe(&UI_FULLBOX_OVER.onTransitionEnd, myCallback, NULL);
uiFullboxUnderDraw(); // draw under layer
uiFullboxOverDraw(); // draw over layer
```
---
## FPS counter (`ui/uifps.h`)
`UIFPS` tracks a rolling average FPS. `uiFPSDraw()` renders it in the corner. Currently drawn as part of the debug HUD (not wired to an element slot).
---
## Player position HUD (`ui/uiplayerpos.h`)
`uiplayerpos.c` draws the player's current world tile coordinates. Debug overlay, currently drawn directly in the scene render.
+162
View File
@@ -0,0 +1,162 @@
# Utilities
Source: `src/dusk/util/`
---
## String (`util/string.h`)
**Always use these instead of stdlib equivalents** (`strcmp`, `strcpy`, `sprintf`, etc.).
```c
stringCopy(dest, src, destSize); // safe strncpy; always null-terminates
stringCompare(a, b); // -1 / 0 / 1
stringEquals(a, b); // bool_t
stringCompareInsensitive(a, b); // case-insensitive -1 / 0 / 1
stringTrim(str); // in-place strip leading/trailing whitespace
stringFindLastChar(str, c); // last occurrence pointer or NULL
stringFormat(dest, destSize, fmt, ...); // snprintf wrapper; pass NULL dest to get length
stringFormatVA(dest, destSize, fmt, args); // va_list version
stringIsWhitespace(c); // bool_t
// Parse:
stringToI32(str, &out) bool_t
stringToI64(str, &out) bool_t
stringToI16(str, &out) bool_t
stringToU16(str, &out) bool_t
stringToF32(str, &out) bool_t
// Suffix checks:
stringEndsWith(str, suffix) bool_t
stringEndsWithCaseInsensitive(str, suffix) bool_t
stringIncludesString(haystack, needle) bool_t
```
---
## Memory (`util/memory.h`)
**Always use these instead of `malloc`/`free`/`memcpy`/`memset` directly.**
```c
memoryAllocate(size) void * // malloc + tracks pointer count
memoryAlign(alignment, size) void * // aligned malloc
memoryFree(ptr) // free + decrements count
memoryReallocate(&ptr, size) // realloc
memoryResize(&ptr, oldSize, newSize) // realloc + copy (safe reshape)
memoryTrack(ptr) // track externally-malloc'd pointer
memoryCopy(dest, src, size) // memcpy
memoryMove(dest, src, size) // memmove
memorySet(dest, value, size) // memset
memoryZero(dest, size) // memset 0
memoryCompare(a, b, size) int_t // memcmp
// Useful for uploading vertex data with different source/dest layouts:
memoryCopyInterleaved(dest, destStride, src, srcStride, elementSize, count);
memoryCopyRangeSafe(dest, start, end, sizeMax); // copy with bounds check
memoryGetAllocatedCount() size_t // current malloc'd block count
```
---
## Math (`util/math.h`)
```c
mathNextPowTwo(value) uint32_t // next power of two >= value
mathMax(a, b) // macro
mathMin(a, b) // macro
mathClamp(x, lower, upper) // macro
mathAbs(amt) // macro
mathModFloat(x, y) float_t // always non-negative modulo
mathLerp(a, b, t) float_t // linear interpolation (floats)
```
For fixed-point lerp use `fixedLerp(a, b, t)` from `util/fixed.h`.
`MATH_PI` is defined as `M_PI`.
---
## Fixed-point (`util/fixed.h`)
Q24.8 format: 24-bit integer part, 8-bit fractional part (`int32_t`). See [architecture.md](architecture.md#fixed-point-math) for the full API.
Quick reference:
```c
FIXED(1.5f) // compile-time literal
fixedFromI32(3) // runtime int → fixed
fixedToFloat(f) // fixed → float (only for GL/platform APIs)
fixedMul(a, b) // multiplication (not just addition)
fixedDiv(a, b) // division
fixedLerp(a, b, t) // lerp where t ∈ [0, FIXED_ONE]
```
---
## Array (`util/array.h`)
```c
arrayReverse(array, count, size); // in-place reverse; size = sizeof(element)
```
---
## Sort (`util/sort.h`)
```c
sortQuick(array, count, size, compare); // quicksort
sortBubble(array, count, size, compare); // bubble sort (small arrays)
sort(array, count, size, compare); // macro alias for sortQuick
// Convenience uint8_t sorter:
sortArrayU8(array, count);
int sortArrayU8Compare(const void *a, const void *b); // comparator
```
`sortcompare_t` matches `qsort` comparator signature: `int (*)(const void *, const void *)`.
---
## Reference counting (`util/ref.h`)
```c
refInit(&ref, dataPtr, onLock, onUnlock, onAllUnlocked);
refLock(&ref); // increments count, calls onLock
bool_t hit_zero = refUnlock(&ref); // decrements; calls onAllUnlocked when 0
```
Used internally by the asset entry system to track how many callers hold a reference to a loaded asset entry.
---
## CRC32 (`util/crypt.h`)
```c
// One-shot:
uint32_t crc = cryptCRC32(data, size);
// Streaming:
uint32_t acc = cryptCRC32Begin();
cryptCRC32Update(&acc, chunk1, len1);
cryptCRC32Update(&acc, chunk2, len2);
uint32_t final = cryptCRC32End(acc);
```
Used by the save stream to checksum save files.
---
## Endian (`util/endian.h`)
All serialized data (save files, asset headers) is little-endian. Convert to/from host byte order:
```c
uint32_t val = endianLittleToHost32(rawU32);
uint16_t val = endianLittleToHost16(rawU16);
float_t val = endianLittleToHostFloat(rawFloat);
```
`isHostLittleEndian()` returns a bool at runtime. The compile-time defines `DUSK_PLATFORM_ENDIAN_LITTLE` / `DUSK_PLATFORM_ENDIAN_BIG` are set by `cmake/targets/<target>.cmake`.
+48 -415
View File
@@ -1,432 +1,65 @@
# Dusk — Claude Code rules # CLAUDE.md
## File headers This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Every C, H, and JS file starts with:
```c ## Project
/**
* Copyright (c) 2026 Dominic Masters Dusk is a C11 RPG game targeting resource-constrained hardware (PSP, GameCube, Wii, PS Vita, Knulli handhelds) and Linux/OpenGL. All game code lives in `src/dusk/`; platform-specific backends live in `src/dusk{platform}/` (e.g. `src/duskgl/`, `src/duskpsp/`, `src/duskdolphin/`).
*
* This software is released under the MIT License. Assets are zipped into `dusk.dsk` at build time and loaded at runtime via the asset system.
* https://opensource.org/licenses/MIT
*/ ## Build
```bash
# Linux (host)
./scripts/build-linux.sh # outputs build-linux/Dusk
# Other targets (require Docker)
./scripts/build-psp-docker.sh
./scripts/build-gamecube-docker.sh
./scripts/build-wii-docker.sh
./scripts/build-knulli-docker.sh
``` ```
JS files use `//` comment style instead. Each script is a thin wrapper around:
```bash
--- cmake -S . -B build-<target> -DDUSK_TARGET_SYSTEM=<target>
cmake --build build-<target> -- -j$(nproc)
## C conventions
### Types
Always use the project-defined aliases instead of bare C primitives:
| Use | Not |
|-----------|--------------|
| `bool_t` | `bool` |
| `int_t` | `int` |
| `float_t` | `float` |
| `char_t` | `char` |
Use `uint8_t`, `uint16_t`, `int32_t`, etc. for fixed-width integers.
All struct and enum types end in `_t` (`animation_t`, `errorret_t`, …).
### Naming
- **Functions** — snake_case, prefixed with their module:
`assetLock()`, `entityPositionInit()`, `moduleAssetBatchCtor()`
- **Struct fields** — camelCase: `keyframeCount`, `localPosition`
- **Macros / constants** — UPPER_SNAKE_CASE:
`ENTITY_ID_INVALID`, `ERROR_OK`, `COMPONENT_TYPE_COUNT`
- **Files** — snake_case matching the primary type: `entityposition.c`,
`moduleassetbatch.c`
### Header files (`.h`)
- Use `#pragma once` — no include guards.
- Declare every public function, `#define`, and `extern` global.
- Write a JSDoc block (`/** … */`) above every declaration explaining
purpose, `@param`s, and `@returns`.
- Only include headers that the `.h` file itself strictly requires for
the types it exposes. Move everything else to the `.c` file.
Do not use forward declarations as a workaround — use the real
include in the `.c` file instead.
### Implementation files (`.c`)
- Contain function bodies only; no declarations.
- Pull in whatever additional includes the implementation needs.
- Do not use `static` or `inline` on **functions**. Every function,
including internal helpers, must be declared in the matching `.h` and
defined in the `.c` file. Internal helpers belong near the bottom of
the `.c` file, not at the top with a `static` qualifier.
`static` and `inline` on functions are only appropriate when the
function body is written directly inside a `.h` file.
`static` on **variables** (file-scope state) is fine and expected.
### Formatting
- Hard-wrap all lines at **80 characters**.
### Error handling
Return `errorret_t` from fallible functions. Use these macros:
```c
errorOk(); // return success
errorThrow("msg %d", val); // return failure with message
errorChain(someCall()); // propagate failure, continue on success
errorIsOk(ret) / errorIsNotOk(ret) // test a result
errorCatch(ret); // handle + free an error
``` ```
Never return raw error codes or use `errno` for in-engine errors. ## Tests
### Memory ```bash
Use the project allocator — never raw `malloc`/`free`: ./scripts/test-linux.sh # builds and runs all tests
```c # Manually run a single test binary after building:
memoryAllocate(size) // allocate ./build-tests/test/<module>/test_<name>
memoryFree(ptr) // free
memoryZero(dest, size) // zero a block
memoryCopy(dest, src, size) // copy
``` ```
### Asserts Tests use [cmocka](https://cmocka.org/) and are only compiled when `DUSK_BUILD_TESTS=ON`. Test sources live under `test/`.
Prefer specific assert macros over bare `assert()`:
```c ## Key conventions
assertNotNull(ptr, "msg");
assertTrue(cond, "msg");
assertFalse(cond, "msg");
assertUnreachable("msg");
assertIsMainThread("msg");
```
--- - Use `stringCompare`, `stringCopy`, `stringEquals`, etc. from `util/string.h` — never `strcmp`, `strcpy`, and friends directly.
- All functions that can fail return `errorret_t`. Use `errorThrow(...)`, `errorChain(call())`, and `errorOk()` macros — see `error/error.h`.
## Build system - Positions and game-world values use `fixed_t` (Q24.8 fixed-point, `int32_t`) — not `float`. Use `FIXED(x)` for literals and the `fixedFrom*`/`fixedTo*` helpers in `util/fixed.h`.
Each subdirectory has its own `CMakeLists.txt` that adds sources with:
```cmake
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
myfile.c
)
```
Never add source files to the root `CMakeLists.txt` directly.
---
## Platform support
### Targets
Set `DUSK_TARGET_SYSTEM` at CMake configure time to select a platform:
| `DUSK_TARGET_SYSTEM` | Macro defined | Platform |
|----------------------|-------------------|------------------|
| `linux` | `DUSK_LINUX` | Linux desktop |
| `knulli` | `DUSK_KNULLI` | Knulli (handheld)|
| `psp` | `DUSK_PSP` | Sony PSP |
| `vita` | `DUSK_VITA` | PlayStation Vita |
| `gamecube` | `DUSK_GAMECUBE` | Nintendo GameCube|
| `wii` | `DUSK_WII` | Nintendo Wii |
### Layer structure
```
src/dusk/ core, platform-agnostic game logic
src/duskgl/ OpenGL abstraction (Linux, Knulli, PSP, Vita)
src/dusksdl2/ SDL2 window + input (Linux, Knulli, PSP, Vita)
src/dusklinux/ Linux + Knulli platform impl
src/duskpsp/ PSP platform impl
src/duskvita/ Vita platform impl
src/duskdolphin/ GameCube / Wii platform impl (no SDL2/OpenGL)
```
Dolphin is the only target that bypasses SDL2 and OpenGL entirely —
it uses native GameCube/Wii rendering and input APIs.
### Platform guards
Use the compile-time macros for platform-specific code:
```c
#ifdef DUSK_PSP
// PSP-only path
#elif defined(DUSK_GAMECUBE) || defined(DUSK_WII)
// GameCube / Wii path
#else
// Generic / Linux fallback
#endif
```
Additional capability macros set per-target:
`DUSK_SDL2`, `DUSK_OPENGL`, `DUSK_OPENGL_ES`, `DUSK_OPENGL_LEGACY`,
`DUSK_INPUT_GAMEPAD`, `DUSK_INPUT_KEYBOARD`, `DUSK_INPUT_POINTER`,
`DUSK_PLATFORM_ENDIAN_BIG` / `DUSK_PLATFORM_ENDIAN_LITTLE`.
### Abstraction pattern
Platform-specific implementations are wired in via `#define` macros in
each platform's `displayplatform.h` / `inputplatform.h` etc., which
the core calls through. Functions that a platform does not support are
simply left undefined — the core guards calls with `#ifdef`.
### Adding platform-specific code
- Put it under `src/dusk<platform>/` in the matching subsystem folder.
- Gate any core call-site with the appropriate `#ifdef DUSK_<PLATFORM>`
or capability macro.
- Keep the `src/dusk/` core free of platform ifdefs — delegate through
the platform header macros instead.
---
## Adding a new asset loader type
1. Add an enum value to `assetloadertype_t` (before `_COUNT`) in
`src/dusk/asset/loader/assetloader.h`.
2. Add fields to the input/loading/output unions in `assetloader.h`.
3. Implement `assetXxxLoaderSync`, `assetXxxLoaderAsync`, and
`assetXxxDispose` in a new `src/dusk/asset/loader/xxx/` directory.
4. Register the three callbacks in `ASSET_LOADER_CALLBACKS[]` in
`src/dusk/asset/loader/assetloader.c`.
5. If user-facing, create a JS module (see below) and a `.d.ts` file.
---
## Adding a new entity component
1. Create `src/dusk/entity/component/<category>/entityMyComp.h/.c` with
struct `entityMyComp_t`, `entityMyCompInit()`, and optionally
`entityMyCompDispose()`.
2. Add the include to `src/dusk/entity/componentlist.h` header block.
3. Add a row to `src/dusk/entity/componentlist.h`:
```c
X(MYCOMP, entityMyComp_t, myComp, entityMyCompInit, NULL, NULL)
```
This auto-generates the enum, union field, and definition entry.
4. If JS-facing, create the script module and `.d.ts` (see below).
---
## Adding a new script (JS) module
1. Create `src/dusk/script/module/<category>/moduleMyMod.h/.c`.
- Declare `extern scriptproto_t MODULE_MYMOD_PROTO;` in the header.
- Use `moduleBaseFunction(name)` to define JS-callable functions.
- Register props/funcs in `moduleMyModInit()` with
`scriptProtoDefineProp` / `scriptProtoDefineFunc` /
`scriptProtoDefineStaticFunc`.
2. `#include` the header in
`src/dusk/script/module/modulelist.c` and call
`moduleMyModInit()` in `moduleListInit()` (and `Dispose` in
`moduleListDispose()`).
3. For component modules also register in
`src/dusk/script/module/entity/component/modulecomponentlist.c`
so `entity.add()` returns the typed wrapper.
4. Create `types/<category>/mymod.d.ts` and add a
`/// <reference path="..." />` line to `types/index.d.ts`.
---
## Script module type declarations
Whenever a `src/dusk/script/module/**/*.c` file is created or modified,
check whether the corresponding `types/**/*.d.ts` needs updating and
apply any changes before finishing the task.
---
## JavaScript (asset scripts)
- Use `var` for module-level state; `const` for values that never
change.
- Always use semicolons.
- Scene objects are plain objects (`var scene = {}`) with assigned
methods.
- Export via `module.exports = scene`.
- Async scene init should use `async function` and `await`.
---
## Coding style ## Coding style
### ASCII only See [`.claude/style.md`](.claude/style.md) for the full style guide: indentation, line length, naming, typedefs, defines, include order, `const` usage, assertion placement, error handling, struct initialization, and platform conditionals.
Source files (`.c`, `.h`, `.js`) must contain only ASCII characters (U+0000U+007F).
Non-ASCII characters are banned even in comments and string literals.
Use ASCII-only substitutes instead:
- `--` or `-` instead of `` (em dash)
- `->` instead of `` (arrow)
- `x` or `*` instead of `×` (multiplication)
Only non-script asset files (e.g. `.po` locale files) may contain non-ASCII text. ## Architecture & systems
### Indentation | Doc | Covers |
2 spaces. No tabs. |---|---|
| [`.claude/architecture.md`](.claude/architecture.md) | Platform abstraction pattern, subsystem lifecycle, error handling, code-generation pipeline |
### Keyword and operator spacing | [`.claude/display.md`](.claude/display.md) | Rendering pipeline: display state, screen, framebuffer, mesh, shader, texture, spritebatch, text |
No space between a keyword or function name and its opening parenthesis: | [`.claude/input.md`](.claude/input.md) | Input actions, buttons, bindings, axis helpers, events |
| [`.claude/asset.md`](.claude/asset.md) | Asset archive, entry lifecycle, loader types, async/sync split, low-level file I/O |
```c | [`.claude/ui.md`](.claude/ui.md) | UI element system, textbox, frames, loading overlay, fullbox transitions, FPS counter |
if(!ptr) return; | [`.claude/animation.md`](.claude/animation.md) | Keyframe animation, easing functions |
for(uint8_t i = 0; i < count; i++) { | [`.claude/systems.md`](.claude/systems.md) | Time, threading, mutex, events, console, logging, system/platform, network |
while(entry->state != DONE) { | [`.claude/util.md`](.claude/util.md) | String, memory, math, fixed-point, array, sort, ref counting, CRC32, endian |
switch(type) { | [`.claude/save.md`](.claude/save.md) | Save slots, stream serialization with CRC, locale/i18n |
sizeof(assetbatch_t) | [`.claude/rpg/index.md`](.claude/rpg/index.md) | RPG layer overview → [world](.claude/rpg/world.md), [entities](.claude/rpg/entity.md), [cutscenes](.claude/rpg/cutscene.md), [story/items](.claude/rpg/story.md) |
memoryZero(ptr, size) | [`.claude/display-refactor.md`](.claude/display-refactor.md) | Planned render-queue refactor (Saturn port context) |
```
Spaces around all binary operators and after every comma:
```c
pos->flags |= ENTITY_POSITION_FLAG_WORLD_DIRTY;
(size_t)end - (size_t)start
foo(a, b, c)
```
### Braces
Opening brace on the **same line** as the statement (K&R style) for all
constructs — functions, `if`, `else`, `for`, `while`, `switch`:
```c
void assetEntryLock(assetentry_t *entry) {
...
}
if(dirty) {
...
} else {
...
}
```
### Guard returns
Short guards go on one line with no braces:
```c
if(!ptr) return;
if(!b || !b->batch) return jerry_undefined();
if(!(flags & DIRTY)) return;
```
### Blank lines
- One blank line between functions; no blank line at the start or end of
a function body.
- One blank line between logical blocks inside a function body.
- No trailing blank lines at the end of a file.
### Pointer placement
`*` is attached to the variable name, not the type:
```c
assetentry_t *entry
const char_t *name
void *ptr
uint8_t *d = (uint8_t *)dest;
```
### Casts
Space between cast and operand:
```c
(assetbatch_t *)user
(uint8_t *)dest
(textureformat_t)v
```
### Return
No parentheses around the return value:
```c
return ptr;
return MEMORY_POINTERS_IN_USE;
```
### switch / case
`case` indented 2 spaces from `switch`; body indented 2 more from `case`:
```c
switch(type) {
case ASSET_LOADER_TYPE_TEXTURE:
descs[i].input.texture = (textureformat_t)v;
break;
default:
break;
}
```
### Multi-line function signatures
When parameters don't fit on one line, put each on its own line indented
2 spaces; the closing `) {` (definition) or `);` (declaration) goes on
its own line at column 0:
```c
void assetEntryInit(
assetentry_t *entry,
const char_t *name,
const assetloadertype_t type,
assetloaderinput_t *input
) {
errorret_t memoryCompare(
const void *a,
const void *b,
const size_t size
);
```
### Structs and enums
Anonymous inner struct or enum with a `typedef`, `_t` suffix, closing
brace and name on the same line:
```c
typedef struct {
errorcode_t code;
char_t *message;
} errorstate_t;
typedef enum {
ASSET_LOADER_TYPE_NULL,
ASSET_LOADER_TYPE_COUNT
} assetloadertype_t;
```
### Designated initialisers
Spaces inside braces; `.field = value`:
```c
jsassetentry_t e = { .entry = entry };
assetbatchloadedpend_t init = { .batch = batch };
```
### Ternary operator
Spaces around `?` and `:`:
```c
const float val = psx > 0.0f ? pt[0][0] / psx : 0.0f;
```
### const placement
`const` before the type, `*` attached to the variable:
```c
const char_t *name
const void *src
const size_t size
```
### Comments in `.c` files
- Do not use section dividers (`/* ---- ... ---- */`). Just let the
functions follow one another with a single blank line between them.
- Multi-line explanatory comments inside function bodies use `//` lines:
```c
// Script modules are freed; orphaned JS wrapper objects now get GC'd
// so their finalizers fire before assetDispose() checks ref counts.
jerry_heap_gc(JERRY_GC_PRESSURE_HIGH);
```
- Do not use `/* */` for inline or inline-block comments inside `.c`
function bodies.
### Comments in `.h` files
Every public declaration gets a Javadoc block (`/** … */`) with
`@param` and `@returns` where relevant. Keep it on the lines immediately
above the declaration with no blank line in between.
---
## Tests
- Tests live in `test/` mirroring `src/dusk/` structure.
- Use cmocka; include `dusktest.h`.
- Test functions: `static void test_something(void **state)`.
- After each test, assert `memoryGetAllocatedCount() == 0` to catch
leaks.
- Build with `-DDUSK_BUILD_TESTS=ON`.
@@ -0,0 +1,28 @@
# Copyright (c) 2025 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
display.c
)
# Subdirectories
add_subdirectory(framebuffer)
add_subdirectory(mesh)
add_subdirectory(screen)
add_subdirectory(shader)
add_subdirectory(spritebatch)
add_subdirectory(text)
add_subdirectory(texture)
# Color definitions
dusk_run_python(
dusk_color_defs
tools.color.csv
--csv ${CMAKE_CURRENT_SOURCE_DIR}/color.csv
--output ${DUSK_GENERATED_HEADERS_DIR}/display/color.h
)
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} dusk_color_defs)
@@ -0,0 +1,23 @@
name,r,g,b,a
black,0,0,0,1
white,1,1,1,1
red,1,0,0,1
green,0,1,0,1
blue,0,0,1,1
yellow,1,1,0,1
cyan,0,1,1,1
magenta,1,0,1,1
transparent,0,0,0,0
transparent_white,1,1,1,0
transparent_black,0,0,0,0
gray,0.5,0.5,0.5,1
light_gray,0.75,0.75,0.75,1
dark_gray,0.25,0.25,0.25,1
orange,1,0.65,0,1
purple,0.5,0,0.5,1
brown,0.6,0.4,0.2,1
pink,1,0.75,0.8,1
lime,0.75,1,0,1
navy,0,0,0.5,1
teal,0,0.5,0.5,1
cornflower_blue,0.39,0.58,0.93,1
1 name r g b a
2 black 0 0 0 1
3 white 1 1 1 1
4 red 1 0 0 1
5 green 0 1 0 1
6 blue 0 0 1 1
7 yellow 1 1 0 1
8 cyan 0 1 1 1
9 magenta 1 0 1 1
10 transparent 0 0 0 0
11 transparent_white 1 1 1 0
12 transparent_black 0 0 0 0
13 gray 0.5 0.5 0.5 1
14 light_gray 0.75 0.75 0.75 1
15 dark_gray 0.25 0.25 0.25 1
16 orange 1 0.65 0 1
17 purple 0.5 0 0.5 1
18 brown 0.6 0.4 0.2 1
19 pink 1 0.75 0.8 1
20 lime 0.75 1 0 1
21 navy 0 0 0.5 1
22 teal 0 0.5 0.5 1
23 cornflower_blue 0.39 0.58 0.93 1
@@ -0,0 +1,116 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "display/display.h"
#include "display/framebuffer/framebuffer.h"
#include "scene/scene.h"
#include "display/spritebatch/spritebatch.h"
#include "display/mesh/quad.h"
#include "display/mesh/cube.h"
#include "display/mesh/sphere.h"
#include "display/mesh/plane.h"
#include "display/mesh/capsule.h"
#include "display/mesh/triprism.h"
#include "display/screen/screen.h"
#include "ui/ui.h"
#include "display/text/text.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "asset/asset.h"
#include "display/shader/shaderlist.h"
#include "time/time.h"
display_t DISPLAY = { 0 };
errorret_t displayInit(void) {
memoryZero(&DISPLAY, sizeof(DISPLAY));
#ifdef displayPlatformInit
errorChain(displayPlatformInit());
#endif
errorChain(displaySetState((displaystate_t){ .flags = 0 }));
errorChain(textureInit(
&TEXTURE_WHITE, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_WHITE_PIXELS }
));
errorChain(textureInit(
&TEXTURE_TEST, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_TEST_PIXELS }
));
// Standard meshes
errorChain(quadInit());
errorChain(cubeInit());
errorChain(sphereInit());
errorChain(planeInit());
errorChain(capsuleInit());
errorChain(triPrismInit());
errorChain(frameBufferInitBackBuffer());
errorChain(spriteBatchInit());
errorChain(textInit());
errorChain(screenInit());
// Setup initial shader with default values
errorChain(shaderListInit());
errorOk();
}
errorret_t displayUpdate(void) {
#ifdef displayPlatformUpdate
errorChain(displayPlatformUpdate());
#endif
// Reset state
spriteBatchClear();
errorChain(frameBufferBind(NULL));
// Bind screen and render scene
errorChain(screenBind());
frameBufferClear(
FRAMEBUFFER_CLEAR_COLOR | FRAMEBUFFER_CLEAR_DEPTH,
SCREEN.background
);
errorChain(sceneRender());
// Finish up
screenUnbind();
screenRender();
// Swap and return.
#ifdef displayPlatformSwap
errorChain(displayPlatformSwap());
#endif
errorOk();
}
errorret_t displaySetState(displaystate_t state) {
#ifdef displayPlatformSetState
errorChain(displayPlatformSetState(state));
#endif
errorOk();
}
errorret_t displayDispose(void) {
errorChain(shaderListDispose());
errorChain(spriteBatchDispose());
screenDispose();
errorChain(textDispose());
errorChain(textureDispose(&TEXTURE_WHITE));
errorChain(textureDispose(&TEXTURE_TEST));
#ifdef displayPlatformDispose
displayPlatformDispose();
#endif
// For now, we just return an OK error.
errorOk();
}
@@ -0,0 +1,65 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "display/displayplatform.h"
// Expecting some definitions to be provided
#ifndef DUSK_DISPLAY_SIZE_DYNAMIC
#ifndef DUSK_DISPLAY_WIDTH
#error "DUSK_DISPLAY_WIDTH must be defined."
#endif
#ifndef DUSK_DISPLAY_HEIGHT
#error "DUSK_DISPLAY_HEIGHT must be defined"
#endif
#define DUSK_DISPLAY_WIDTH_DEFAULT DUSK_DISPLAY_WIDTH
#define DUSK_DISPLAY_HEIGHT_DEFAULT DUSK_DISPLAY_HEIGHT
#else
#ifndef DUSK_DISPLAY_WIDTH_DEFAULT
#error "DUSK_DISPLAY_WIDTH_DEFAULT must be defined."
#endif
#ifndef DUSK_DISPLAY_HEIGHT_DEFAULT
#error "DUSK_DISPLAY_HEIGHT_DEFAULT must be defined."
#endif
#ifdef DUSK_DISPLAY_WIDTH
#error "DUSK_DISPLAY_WIDTH should not be defined."
#endif
#ifdef DUSK_DISPLAY_HEIGHT
#error "DUSK_DISPLAY_HEIGHT should not be defined."
#endif
#endif
// Main Display Struct, platform-speicifc
typedef displayplatform_t display_t;
extern display_t DISPLAY;
/**
* Initializes the display system.
* @return An errorret_t indicating success or failure.
*/
errorret_t displayInit(void);
/**
* Tells the display system to actually draw the frame.
* @return An errorret_t indicating success or failure.
*/
errorret_t displayUpdate(void);
/**
* Sets the display state.
*
* @param state The state to set.
* @return An errorret_t indicating success or failure.
*/
errorret_t displaySetState(displaystate_t state);
/**
* Disposes of the display system.
* @return An errorret_t indicating success or failure.
*/
errorret_t displayDispose(void);
@@ -0,0 +1,17 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#define DISPLAY_STATE_FLAG_CULL (1 << 0)
#define DISPLAY_STATE_FLAG_DEPTH_TEST (1 << 1)
#define DISPLAY_STATE_FLAG_BLEND (1 << 2)
typedef struct {
uint8_t flags;
} displaystate_t;
+2 -4
View File
@@ -9,12 +9,10 @@ set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF CACHE BOOL "" FORCE)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_C OFF CACHE BOOL "" FORCE) set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_C OFF CACHE BOOL "" FORCE)
find_package(SDL2 REQUIRED) find_package(SDL2 REQUIRED)
find_package(OpenGL REQUIRED)
target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
${SDL2_LIBRARIES} ${SDL2_LIBRARIES}
SDL2 SDL2
pthread pthread
OpenGL::GL
zip zip
bz2 bz2
z z
@@ -28,6 +26,7 @@ target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
pspge pspge
pspctrl pspctrl
pspgu pspgu
pspgum
pspaudio pspaudio
pspaudiolib pspaudiolib
psputility psputility
@@ -47,14 +46,13 @@ target_include_directories(${DUSK_BINARY_TARGET_NAME} PRIVATE
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_SDL2 DUSK_SDL2
DUSK_OPENGL
DUSK_PSP DUSK_PSP
DUSK_INPUT_GAMEPAD DUSK_INPUT_GAMEPAD
DUSK_PLATFORM_ENDIAN_LITTLE DUSK_PLATFORM_ENDIAN_LITTLE
DUSK_OPENGL_LEGACY
DUSK_DISPLAY_WIDTH=480 DUSK_DISPLAY_WIDTH=480
DUSK_DISPLAY_HEIGHT=272 DUSK_DISPLAY_HEIGHT=272
DUSK_THREAD_PTHREAD DUSK_THREAD_PTHREAD
DUSK_TIME_DYNAMIC
) )
# Postbuild, create .pbp file for PSP. # Postbuild, create .pbp file for PSP.
+186
View File
@@ -0,0 +1,186 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Resolve YAUL_INSTALL_ROOT (already set by the toolchain file, but guard
# in case cmake/targets/ is loaded standalone for IDE tooling).
if(NOT DEFINED YAUL_INSTALL_ROOT)
if(DEFINED ENV{YAUL_INSTALL_ROOT})
set(YAUL_INSTALL_ROOT "$ENV{YAUL_INSTALL_ROOT}")
else()
set(YAUL_INSTALL_ROOT "/opt/yaul")
endif()
endif()
# Yaul installs headers/libs under the arch-prefix sysroot subdirectory:
# ${YAUL_INSTALL_ROOT}/sh2eb-elf/include/
# ${YAUL_INSTALL_ROOT}/sh2eb-elf/lib/
# Cross-compiled zlib and libzip are installed to the same sysroot.
set(_YAUL_SYSROOT "${YAUL_INSTALL_ROOT}/sh2eb-elf")
set(_YAUL_BIN "${YAUL_INSTALL_ROOT}/bin")
# ---------------------------------------------------------------------------
# Bypass system find_package calls for libraries we cross-compile into the
# sh2eb-elf sysroot and install into ${_YAUL_SYSROOT}.
# ---------------------------------------------------------------------------
# zlib
if(NOT TARGET ZLIB::ZLIB)
add_library(ZLIB::ZLIB INTERFACE IMPORTED GLOBAL)
set_target_properties(ZLIB::ZLIB PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${_YAUL_SYSROOT}/include"
INTERFACE_LINK_LIBRARIES "${_YAUL_SYSROOT}/lib/libz.a"
)
endif()
set(ZLIB_FOUND TRUE CACHE BOOL "" FORCE)
set(ZLIB_INCLUDE_DIR "${_YAUL_SYSROOT}/include" CACHE PATH "" FORCE)
set(ZLIB_LIBRARY "${_YAUL_SYSROOT}/lib/libz.a" CACHE FILEPATH "" FORCE)
# libzip — pre-installed into the sh2eb-elf sysroot; skip Findlibzip.cmake.
set(libzip_FOUND TRUE CACHE BOOL "libzip found (Saturn sysroot)" FORCE)
find_path(_sat_zip_inc NAMES zip.h
PATHS "${_YAUL_SYSROOT}/include"
NO_DEFAULT_PATH
)
if(_sat_zip_inc)
target_include_directories(${DUSK_LIBRARY_TARGET_NAME} PRIVATE "${_sat_zip_inc}")
endif()
# ---------------------------------------------------------------------------
# Compile definitions
# ---------------------------------------------------------------------------
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SATURN
DUSK_INPUT_GAMEPAD
DUSK_PLATFORM_ENDIAN_BIG
DUSK_DISPLAY_WIDTH=320
DUSK_DISPLAY_HEIGHT=224
DUSK_THREAD_NONE
)
# ---------------------------------------------------------------------------
# Compile options
# ---------------------------------------------------------------------------
target_compile_options(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
-m2 -mb
-fno-builtin
-fomit-frame-pointer
-w
)
# ---------------------------------------------------------------------------
# Include paths
# ---------------------------------------------------------------------------
target_include_directories(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
"${_YAUL_SYSROOT}/include"
"${_YAUL_SYSROOT}/include/yaul"
)
# ---------------------------------------------------------------------------
# Link libraries
# ---------------------------------------------------------------------------
target_link_directories(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
"${_YAUL_SYSROOT}/lib"
)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
# --start-group/--end-group allow circular archive references
# (e.g. libyaul allocator symbols referenced by libzip / yyjson objects).
-Wl,--start-group
"${_YAUL_SYSROOT}/lib/libyaul.a"
"${_YAUL_SYSROOT}/lib/libzip.a"
"${_YAUL_SYSROOT}/lib/libz.a"
# GCC soft-float / soft-divide runtime (SH-2 has no FPU or hw divider).
# -lgcc is resolved by the compiler driver even with -nodefaultlibs.
-lgcc
-Wl,--end-group
)
# Yaul linker script (Saturn SH-2 memory map) and startup objects.
# Startup objects must precede all other objects so use target_link_options
# (those flags appear before the object-file list in cmake's link command).
target_link_options(${DUSK_BINARY_TARGET_NAME} PRIVATE
"-T${_YAUL_SYSROOT}/lib/ldscripts/yaul.x"
"${_YAUL_SYSROOT}/lib/crt0.o"
"${_YAUL_SYSROOT}/lib/init.o"
# Provide SH-2 stack top addresses required by crt0.o/cpu_dual_entries.o.
# RAM region: 0x06004000 .. 0x06100000 (~1 MB).
# Master stack grows down from the very top; slave CPU gets 4 KB below.
"-Wl,--defsym=___master_stack=0x06100000"
"-Wl,--defsym=___slave_stack=0x060FF000"
)
# ---------------------------------------------------------------------------
# Post-build: ELF → binary → Saturn disc image (ISO + CUE)
# ---------------------------------------------------------------------------
set(DUSK_SAT_BIN "${CMAKE_BINARY_DIR}/Dusk.bin")
set(DUSK_SAT_IP_BIN "${CMAKE_BINARY_DIR}/IP.BIN")
set(DUSK_SAT_CD_DIR "${CMAKE_BINARY_DIR}/cd")
set(DUSK_SAT_AUDIO_DIR "${CMAKE_BINARY_DIR}/audio-tracks")
set(DUSK_SAT_ISO "${CMAKE_BINARY_DIR}/Dusk.iso")
set(DUSK_SAT_CUE "${CMAKE_BINARY_DIR}/Dusk.cue")
# Step 1: ELF → flat binary (loaded into Work RAM by IP.BIN)
add_custom_command(TARGET ${DUSK_BINARY_TARGET_NAME} POST_BUILD
COMMAND "${_YAUL_BIN}/sh2eb-elf-objcopy"
-O binary
"$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>"
"${DUSK_SAT_BIN}"
COMMENT "Converting ELF → ${DUSK_SAT_BIN}"
)
# Step 2: flat binary → IP.BIN (boot header with region security blobs)
# make-ip writes IP.BIN into dirname(arg1), so it lands at ${CMAKE_BINARY_DIR}/IP.BIN.
# Pass -1 for 1st-read-size so make-ip uses the actual file size.
add_custom_command(TARGET ${DUSK_BINARY_TARGET_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E env
"YAUL_INSTALL_ROOT=${YAUL_INSTALL_ROOT}"
"YAUL_ARCH_SH_PREFIX=sh2eb-elf"
"${_YAUL_BIN}/make-ip"
"${DUSK_SAT_BIN}"
"V1.000"
"20260101"
"JTUE"
"J"
"DUSK"
"0x06100000"
"0x060FF000"
"0x06004000"
"-1"
COMMENT "Generating IP.BIN"
)
# Step 3: build CD filesystem tree and create ISO 9660 image
add_custom_command(TARGET ${DUSK_BINARY_TARGET_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_SAT_CD_DIR}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_SAT_AUDIO_DIR}"
COMMAND ${CMAKE_COMMAND} -E copy "${DUSK_SAT_BIN}" "${DUSK_SAT_CD_DIR}/A.BIN"
# Asset archive — read at runtime via cdfs + zip_source_buffer
COMMAND ${CMAKE_COMMAND} -E copy "${DUSK_ASSETS_ZIP}" "${DUSK_SAT_CD_DIR}/DUSK.DSK"
# ISO 9660 requires these auxiliary text files
COMMAND ${CMAKE_COMMAND} -E touch "${DUSK_SAT_CD_DIR}/ABS.TXT"
COMMAND ${CMAKE_COMMAND} -E touch "${DUSK_SAT_CD_DIR}/BIB.TXT"
COMMAND ${CMAKE_COMMAND} -E touch "${DUSK_SAT_CD_DIR}/CPY.TXT"
COMMAND ${CMAKE_COMMAND} -E env
"YAUL_INSTALL_ROOT=${YAUL_INSTALL_ROOT}"
"MAKE_ISO_XORRISOFS=/usr/bin/xorrisofs"
"${_YAUL_BIN}/make-iso"
"${DUSK_SAT_CD_DIR}"
"${DUSK_SAT_IP_BIN}"
"${CMAKE_BINARY_DIR}"
"Dusk"
COMMENT "Generating ${DUSK_SAT_ISO}"
)
# Step 4: ISO → CUE sheet (rename .iso → .bin for a classic BIN/CUE pair
# if desired; emulators accept .iso+.cue as-is)
add_custom_command(TARGET ${DUSK_BINARY_TARGET_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E env
"YAUL_INSTALL_ROOT=${YAUL_INSTALL_ROOT}"
"${_YAUL_BIN}/make-cue"
"${DUSK_SAT_AUDIO_DIR}"
"${DUSK_SAT_ISO}"
COMMENT "Generating ${DUSK_SAT_CUE}"
)
+63
View File
@@ -0,0 +1,63 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
#
# CMake toolchain file for Sega Saturn (Hitachi SH-2, big-endian)
# using the Yaul homebrew SDK. Set YAUL_INSTALL_ROOT or the
# YAUL_INSTALL_ROOT environment variable before invoking cmake.
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_PROCESSOR sh2)
# Resolve Yaul install root
if(NOT DEFINED YAUL_INSTALL_ROOT)
if(DEFINED ENV{YAUL_INSTALL_ROOT})
set(YAUL_INSTALL_ROOT "$ENV{YAUL_INSTALL_ROOT}"
CACHE PATH "Yaul SDK root" FORCE)
else()
set(YAUL_INSTALL_ROOT "/opt/yaul"
CACHE PATH "Yaul SDK root" FORCE)
endif()
endif()
# Yaul SH-2 cross-compiler prefix is sh2eb-elf (big-endian SH-2 ELF).
# Binaries live in ${YAUL_INSTALL_ROOT}/bin/; headers/libs under
# ${YAUL_INSTALL_ROOT}/sh2eb-elf/{include,lib}/.
set(_YAUL_BIN "${YAUL_INSTALL_ROOT}/bin")
set(CMAKE_C_COMPILER "${_YAUL_BIN}/sh2eb-elf-gcc")
set(CMAKE_CXX_COMPILER "${_YAUL_BIN}/sh2eb-elf-g++")
set(CMAKE_AR "${_YAUL_BIN}/sh2eb-elf-ar")
set(CMAKE_RANLIB "${_YAUL_BIN}/sh2eb-elf-ranlib")
set(CMAKE_STRIP "${_YAUL_BIN}/sh2eb-elf-strip")
set(CMAKE_OBJCOPY "${_YAUL_BIN}/sh2eb-elf-objcopy")
set(CMAKE_LINKER "${_YAUL_BIN}/sh2eb-elf-ld")
set(CMAKE_CROSSCOMPILING TRUE)
# Tell CMake not to try to run built executables
set(CMAKE_CROSSCOMPILING_EMULATOR "" CACHE STRING "" FORCE)
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
# Sysroot — Yaul installs headers/libs under the arch-prefix subdirectory
set(_YAUL_SYSROOT "${YAUL_INSTALL_ROOT}/sh2eb-elf")
set(CMAKE_FIND_ROOT_PATH "${_YAUL_SYSROOT}")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
# SH-2 core flags: big-endian (-mb), SH-2 ISA (-m2), no FPU.
# -ffunction-sections/-fdata-sections enable --gc-sections to eliminate
# unreachable code at the function level (e.g. yyjson FILE* API paths).
set(_SAT_C_FLAGS "-m2 -mb -fno-builtin -fomit-frame-pointer -ffunction-sections -fdata-sections -Os")
set(CMAKE_C_FLAGS_INIT "${_SAT_C_FLAGS}")
# Linker flags: gc-sections, no startup/default libs (Yaul provides crt0/init;
# we supply all needed libraries explicitly). -nodefaultlibs prevents cmake/gcc
# from injecting -lc (which does not exist in the Yaul sysroot).
# --start-group/--end-group are placed in target_link_libraries in
# targets/saturn.cmake so they actually wrap the archive list.
set(CMAKE_EXE_LINKER_FLAGS_INIT
"-Wl,--gc-sections -nostartfiles -nodefaultlibs")
+368
View File
@@ -0,0 +1,368 @@
FROM ubuntu:22.04
LABEL org.opencontainers.image.description="Dusk Engine — Sega Saturn build environment (sh2eb-elf cross-compiler + Yaul SDK)"
ENV DEBIAN_FRONTEND=noninteractive
ENV YAUL_INSTALL_ROOT=/opt/yaul
# All variables required by Yaul's env.mk
ENV YAUL_ARCH_SH_PREFIX=sh2eb-elf
ENV YAUL_PROG_SH_PREFIX=sh2eb-elf
ENV YAUL_ARCH_M68K_PREFIX=m68keb-elf
ENV YAUL_BUILD_ROOT=/tmp/yaul-build
ENV YAUL_BUILD=build
ENV YAUL_OPTION_MALLOC_IMPL=tlsf
ENV PATH="${YAUL_INSTALL_ROOT}/bin:${PATH}"
# Toolchain source versions
ARG BINUTILS_VER=2.40
ARG GCC_VER=12.3.0
# ---------------------------------------------------------------------------
# 1. Host build tools
# ---------------------------------------------------------------------------
RUN apt-get update && apt-get install -y \
build-essential \
cmake \
git \
wget \
curl \
xz-utils \
python3 \
python3-pip \
python3-polib \
python3-pil \
python3-dotenv \
texinfo \
bison \
flex \
libgmp-dev \
libmpfr-dev \
libmpc-dev \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p "${YAUL_INSTALL_ROOT}"
# ---------------------------------------------------------------------------
# 2. Download cross-compiler sources
# ---------------------------------------------------------------------------
RUN cd /tmp && \
wget -q "https://ftp.gnu.org/gnu/binutils/binutils-${BINUTILS_VER}.tar.xz" && \
wget -q "https://ftp.gnu.org/gnu/gcc/gcc-${GCC_VER}/gcc-${GCC_VER}.tar.xz" && \
tar xf "binutils-${BINUTILS_VER}.tar.xz" && \
tar xf "gcc-${GCC_VER}.tar.xz" && \
rm "binutils-${BINUTILS_VER}.tar.xz" "gcc-${GCC_VER}.tar.xz"
# Download GCC prerequisites (gmp, mpfr, mpc if not packaged)
RUN cd /tmp/gcc-${GCC_VER} && contrib/download_prerequisites
# ---------------------------------------------------------------------------
# 3. sh2eb-elf binutils (SH-2 big-endian)
# ---------------------------------------------------------------------------
RUN mkdir -p /tmp/build-sh-binutils && cd /tmp/build-sh-binutils && \
/tmp/binutils-${BINUTILS_VER}/configure \
--target=sh2eb-elf \
--prefix="${YAUL_INSTALL_ROOT}" \
--disable-nls \
--disable-multilib \
--disable-werror \
&& make -j"$(nproc)" && make install && \
rm -rf /tmp/build-sh-binutils
# ---------------------------------------------------------------------------
# 4. sh2eb-elf GCC stage 1 (compiler only, no C library yet)
# ---------------------------------------------------------------------------
RUN mkdir -p /tmp/build-sh-gcc1 && cd /tmp/build-sh-gcc1 && \
/tmp/gcc-${GCC_VER}/configure \
--target=sh2eb-elf \
--prefix="${YAUL_INSTALL_ROOT}" \
--enable-languages=c,c++ \
--without-headers \
--with-newlib \
--disable-nls \
--disable-shared \
--disable-multilib \
--disable-decimal-float \
--disable-threads \
--disable-libatomic \
--disable-libgomp \
--disable-libquadmath \
--disable-libssp \
--disable-libvtv \
--disable-libstdcxx \
&& make -j"$(nproc)" all-gcc all-target-libgcc \
&& make install-gcc install-target-libgcc && \
rm -rf /tmp/build-sh-gcc1
# Newlib does not recognise the sh2eb CPU name, and Yaul ships its own C
# runtime in libyaul/libc/ anyway. Stage 1 (compiler + libgcc) is all
# we need; Yaul's specs file overrides *startfile:/*endfile:/*lib: to empty
# so nothing from a host C library is linked in.
# ---------------------------------------------------------------------------
# 7. m68k-elf binutils (Saturn 68EC000 sound CPU)
# ---------------------------------------------------------------------------
RUN mkdir -p /tmp/build-m68k-binutils && cd /tmp/build-m68k-binutils && \
/tmp/binutils-${BINUTILS_VER}/configure \
--target=m68k-elf \
--prefix="${YAUL_INSTALL_ROOT}" \
--disable-nls \
--disable-multilib \
--disable-werror \
&& make -j"$(nproc)" && make install && \
rm -rf /tmp/build-m68k-binutils
# ---------------------------------------------------------------------------
# 8. m68k-elf GCC (compiler only; Yaul provides its own sound startup)
# ---------------------------------------------------------------------------
RUN mkdir -p /tmp/build-m68k-gcc && cd /tmp/build-m68k-gcc && \
/tmp/gcc-${GCC_VER}/configure \
--target=m68k-elf \
--prefix="${YAUL_INSTALL_ROOT}" \
--enable-languages=c \
--without-headers \
--with-newlib \
--disable-nls \
--disable-shared \
--disable-multilib \
--disable-libssp \
&& make -j"$(nproc)" all-gcc && make install-gcc && \
rm -rf /tmp/build-m68k-gcc
# Clean up source tarballs/trees
RUN rm -rf /tmp/binutils-${BINUTILS_VER} /tmp/gcc-${GCC_VER}
# ---------------------------------------------------------------------------
# 9. Create m68keb-elf symlinks
# Yaul expects YAUL_ARCH_M68K_PREFIX=m68keb-elf but we built m68k-elf.
# m68k is always big-endian, so m68k-elf == m68keb-elf semantically.
# ---------------------------------------------------------------------------
RUN for tool in "${YAUL_INSTALL_ROOT}/bin/m68k-elf-"*; do \
base="$(basename "$tool")"; \
newname="${YAUL_INSTALL_ROOT}/bin/m68keb-elf-${base#m68k-elf-}"; \
ln -sf "$tool" "$newname"; \
done
# ---------------------------------------------------------------------------
# 10. Clone and install libyaul
# ---------------------------------------------------------------------------
RUN git clone --depth 1 --recurse-submodules \
https://github.com/yaul-org/libyaul.git /tmp/yaul && \
mkdir -p /tmp/yaul-build && \
cd /tmp/yaul && \
YAUL_INSTALL_ROOT="${YAUL_INSTALL_ROOT}" \
YAUL_ARCH_SH_PREFIX=sh2eb-elf \
YAUL_PROG_SH_PREFIX=sh2eb-elf \
YAUL_ARCH_M68K_PREFIX=m68keb-elf \
YAUL_BUILD_ROOT=/tmp/yaul-build \
YAUL_BUILD=build \
YAUL_OPTION_MALLOC_IMPL=tlsf \
make install && \
rm -rf /tmp/yaul /tmp/yaul-build
# ---------------------------------------------------------------------------
# 11. Provide a freestanding stdint.h in the Yaul sysroot.
# GCC 12 --without-headers installs a stdint.h wrapper that emits
# `#include_next <stdint.h>`, but Yaul's sysroot has no system stdint.h
# to satisfy that lookup. Yaul's own errno.h (and anything it pulls in)
# will fail to compile in any external cmake project without this stub.
# ---------------------------------------------------------------------------
RUN test -f "${YAUL_INSTALL_ROOT}/sh2eb-elf/include/stdint.h" || \
cp /opt/yaul/lib/gcc/sh2eb-elf/12.3.0/include/stdint-gcc.h \
"${YAUL_INSTALL_ROOT}/sh2eb-elf/include/stdint.h" 2>/dev/null || \
printf '%s\n' \
'#pragma once' \
'#ifndef __STDINT_H' \
'#define __STDINT_H' \
'typedef signed char int8_t;' \
'typedef signed short int16_t;' \
'typedef signed int int32_t;' \
'typedef signed long long int64_t;' \
'typedef unsigned char uint8_t;' \
'typedef unsigned short uint16_t;' \
'typedef unsigned int uint32_t;' \
'typedef unsigned long long uint64_t;' \
'typedef int8_t int_least8_t;' \
'typedef int16_t int_least16_t;' \
'typedef int32_t int_least32_t;' \
'typedef int64_t int_least64_t;' \
'typedef uint8_t uint_least8_t;' \
'typedef uint16_t uint_least16_t;' \
'typedef uint32_t uint_least32_t;' \
'typedef uint64_t uint_least64_t;' \
'typedef int32_t int_fast8_t;' \
'typedef int32_t int_fast16_t;' \
'typedef int32_t int_fast32_t;' \
'typedef int64_t int_fast64_t;' \
'typedef uint32_t uint_fast8_t;' \
'typedef uint32_t uint_fast16_t;' \
'typedef uint32_t uint_fast32_t;' \
'typedef uint64_t uint_fast64_t;' \
'typedef int32_t intptr_t;' \
'typedef uint32_t uintptr_t;' \
'typedef int64_t intmax_t;' \
'typedef uint64_t uintmax_t;' \
'#define INT8_MIN (-128)' \
'#define INT16_MIN (-32768)' \
'#define INT32_MIN (-2147483647-1)' \
'#define INT64_MIN (-9223372036854775807LL-1)' \
'#define INT8_MAX (127)' \
'#define INT16_MAX (32767)' \
'#define INT32_MAX (2147483647)' \
'#define INT64_MAX (9223372036854775807LL)' \
'#define UINT8_MAX (255U)' \
'#define UINT16_MAX (65535U)' \
'#define UINT32_MAX (4294967295U)' \
'#define UINT64_MAX (18446744073709551615ULL)' \
'#define INTPTR_MIN INT32_MIN' \
'#define INTPTR_MAX INT32_MAX' \
'#define UINTPTR_MAX UINT32_MAX' \
'#define INTMAX_MIN INT64_MIN' \
'#define INTMAX_MAX INT64_MAX' \
'#define UINTMAX_MAX UINT64_MAX' \
'#define SIZE_MAX UINT32_MAX' \
'#define INT8_C(c) (c)' \
'#define INT16_C(c) (c)' \
'#define INT32_C(c) (c)' \
'#define INT64_C(c) (c ## LL)' \
'#define UINT8_C(c) (c ## U)' \
'#define UINT16_C(c) (c ## U)' \
'#define UINT32_C(c) (c ## U)' \
'#define UINT64_C(c) (c ## ULL)' \
'#define INTMAX_C(c) (c ## LL)' \
'#define UINTMAX_C(c)(c ## ULL)' \
'#endif' \
> "${YAUL_INSTALL_ROOT}/sh2eb-elf/include/stdint.h"
# ---------------------------------------------------------------------------
# 11b. Stubs for non-standard / bare-metal-missing headers.
# Yaul's sysroot only ships a minimal libc; third-party libraries such as
# libzip need these POSIX/GNU headers to compile.
# ---------------------------------------------------------------------------
RUN printf '#pragma once\n#include <stdlib.h>\n' \
> "${YAUL_INSTALL_ROOT}/sh2eb-elf/include/malloc.h" && \
printf '#pragma once\n#include <string.h>\n' \
> "${YAUL_INSTALL_ROOT}/sh2eb-elf/include/memory.h" && \
printf '%s\n' \
'#pragma once' \
'#ifndef _TIME_H' \
'#define _TIME_H' \
'typedef long time_t;' \
'typedef long clock_t;' \
'#define CLOCKS_PER_SEC 1000L' \
'struct tm {' \
' int tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year;' \
' int tm_wday, tm_yday, tm_isdst;' \
'};' \
'static inline time_t time(time_t *t) { if(t) *t=0; return 0; }' \
'static inline time_t mktime(struct tm *t) { (void)t; return 0; }' \
'static inline struct tm *localtime(const time_t *t) { (void)t; return 0; }' \
'static inline struct tm *gmtime(const time_t *t) { (void)t; return 0; }' \
'#endif' \
> "${YAUL_INSTALL_ROOT}/sh2eb-elf/include/time.h" && \
printf '%s\n' \
'#pragma once' \
'#ifndef _SYS_STAT_H' \
'#define _SYS_STAT_H' \
'#include <sys/types.h>' \
'#include <time.h>' \
'typedef unsigned int dev_t;' \
'typedef unsigned int ino_t;' \
'typedef unsigned short nlink_t;' \
'typedef long blksize_t;' \
'typedef long blkcnt_t;' \
'struct stat {' \
' dev_t st_dev; ino_t st_ino; mode_t st_mode; nlink_t st_nlink;' \
' uid_t st_uid; gid_t st_gid; dev_t st_rdev; off_t st_size;' \
' blksize_t st_blksize; blkcnt_t st_blocks;' \
' time_t st_atime, st_mtime, st_ctime;' \
'};' \
'static inline int stat(const char *p, struct stat *b){(void)p;(void)b;return -1;}' \
'static inline int fstat(int f, struct stat *b){(void)f;(void)b;return -1;}' \
'#define S_ISREG(m) (((m)&0170000)==0100000)' \
'#define S_ISDIR(m) (((m)&0170000)==0040000)' \
'#define S_IRUSR 0400' '#define S_IWUSR 0200' '#define S_IXUSR 0100' \
'#endif' \
> "${YAUL_INSTALL_ROOT}/sh2eb-elf/include/sys/stat.h"
# ---------------------------------------------------------------------------
# 12. sat-xc.cmake — shared CMake toolchain for zlib and libzip.
# CMAKE_SYSROOT tells cmake to pass --sysroot to the compiler so that
# GCC's #include_next wrappers resolve against the Yaul sysroot headers.
# ---------------------------------------------------------------------------
RUN printf '%s\n' \
'set(CMAKE_SYSTEM_NAME Generic)' \
'set(CMAKE_SYSTEM_PROCESSOR sh2)' \
"set(CMAKE_C_COMPILER \"${YAUL_INSTALL_ROOT}/bin/sh2eb-elf-gcc\")" \
"set(CMAKE_AR \"${YAUL_INSTALL_ROOT}/bin/sh2eb-elf-ar\")" \
"set(CMAKE_RANLIB \"${YAUL_INSTALL_ROOT}/bin/sh2eb-elf-ranlib\")" \
"set(CMAKE_SYSROOT \"${YAUL_INSTALL_ROOT}/sh2eb-elf\")" \
'set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)' \
'set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)' \
'set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)' \
'set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)' \
> /tmp/sat-xc.cmake
# ---------------------------------------------------------------------------
# 13. Cross-compile zlib for sh2eb-elf (inflate/deflate core only).
# We compile the nine core source files directly rather than via cmake
# to avoid the gz* files whose POSIX gzip-streaming API is both unused
# (libzip only needs inflate/deflate) and cannot compile on bare metal
# (gzguts.h -> errno.h -> stdint.h chain, and zutil.h includes gzguts.h
# unless NO_GZIP is defined).
# ---------------------------------------------------------------------------
RUN wget -q https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz -O /tmp/zlib.tar.gz && \
tar xf /tmp/zlib.tar.gz -C /tmp && \
cd /tmp/zlib-1.3.1 && \
for f in adler32.c compress.c crc32.c deflate.c infback.c \
inffast.c inflate.c inftrees.c trees.c uncompr.c zutil.c; do \
"${YAUL_INSTALL_ROOT}/bin/sh2eb-elf-gcc" \
-m2 -mb -fno-builtin -O2 -DNO_GZIP -DSTDC -I. -c "$f" -o "${f%.c}.o"; \
done && \
"${YAUL_INSTALL_ROOT}/bin/sh2eb-elf-ar" rcs \
"${YAUL_INSTALL_ROOT}/sh2eb-elf/lib/libz.a" \
adler32.o compress.o crc32.o deflate.o infback.o inffast.o \
inflate.o inftrees.o trees.o uncompr.o zutil.o && \
install -m644 zlib.h zconf.h "${YAUL_INSTALL_ROOT}/sh2eb-elf/include/" && \
rm -rf /tmp/zlib-1.3.1 /tmp/zlib.tar.gz
# ---------------------------------------------------------------------------
# 14. Cross-compile libzip for sh2eb-elf (reuses /tmp/sat-xc.cmake above)
# ---------------------------------------------------------------------------
RUN wget -q https://github.com/nih-at/libzip/releases/download/v1.10.1/libzip-1.10.1.tar.gz -O /tmp/libzip.tar.gz && \
tar xf /tmp/libzip.tar.gz -C /tmp && \
cmake -S /tmp/libzip-1.10.1 -B /tmp/libzip-build \
-DCMAKE_TOOLCHAIN_FILE=/tmp/sat-xc.cmake \
-DCMAKE_INSTALL_PREFIX="${YAUL_INSTALL_ROOT}/sh2eb-elf" \
-DCMAKE_FIND_ROOT_PATH="${YAUL_INSTALL_ROOT}/sh2eb-elf" \
-DCMAKE_C_FLAGS="-m2 -mb -fno-builtin -O2" \
-DZLIB_LIBRARY="${YAUL_INSTALL_ROOT}/sh2eb-elf/lib/libz.a" \
-DZLIB_INCLUDE_DIR="${YAUL_INSTALL_ROOT}/sh2eb-elf/include" \
-DENABLE_BZIP2=OFF \
-DENABLE_LZMA=OFF \
-DENABLE_ZSTD=OFF \
-DENABLE_OPENSSL=OFF \
-DENABLE_GNUTLS=OFF \
-DBUILD_SHARED_LIBS=OFF \
-DBUILD_EXAMPLES=OFF \
-DBUILD_DOCUMENTATION=OFF \
-DBUILD_REGRESS=OFF \
-DBUILD_TOOLS=OFF \
-DHAVE_CLONEFILE=0 \
-DHAVE_ARC4RANDOM=0 \
-DHAVE_GETPROGNAME=0 \
&& cmake --build /tmp/libzip-build -- -j"$(nproc)" \
&& cmake --install /tmp/libzip-build \
&& rm -rf /tmp/libzip-1.10.1 /tmp/libzip-build /tmp/sat-xc.cmake \
; rm -f /tmp/libzip.tar.gz /tmp/zlib.tar.gz 2>/dev/null ; true
# ---------------------------------------------------------------------------
# 15. Disc-image tools (separate layer so it does not invalidate the
# expensive cross-compiler cache layers above on changes).
# xorriso provides xorrisofs, needed by Yaul's make-iso script.
# ---------------------------------------------------------------------------
RUN apt-get update && apt-get install -y xorriso && rm -rf /var/lib/apt/lists/*
WORKDIR /workdir
VOLUME ["/workdir"]
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker build -t dusk-saturn -f docker/saturn/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-saturn /bin/bash -c "./scripts/build-saturn.sh"
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
set -e
if [ -z "$YAUL_INSTALL_ROOT" ]; then
if [ -d "/opt/yaul" ]; then
export YAUL_INSTALL_ROOT=/opt/yaul
else
echo "YAUL_INSTALL_ROOT is not set. Please set it to your Yaul SDK installation."
exit 1
fi
fi
mkdir -p build-saturn
# Remove stale cache so toolchain flag changes (CMAKE_*_FLAGS_INIT) take effect.
rm -f build-saturn/CMakeCache.txt
cmake -S . -B build-saturn \
-DDUSK_TARGET_SYSTEM=saturn \
-DCMAKE_TOOLCHAIN_FILE="cmake/toolchains/saturn.cmake" \
-DYAUL_INSTALL_ROOT="${YAUL_INSTALL_ROOT}"
cmake --build build-saturn -- -j"$(nproc)"
+61
View File
@@ -0,0 +1,61 @@
#!/bin/bash
# psp-debug.sh — build (optional), reset, and run Dusk on a live PSP.
#
# Prerequisites:
# usbhostfs_pc running (served from the build-psp/ dir, as host0:).
# PSP must be running psplink (visible on PSP screen).
#
# Usage:
# ./scripts/psp-debug.sh # reset + run
# ./scripts/psp-debug.sh --build # rebuild via docker first, then run
#
# PSP stdout streams to this terminal via pspsh (logDebug, printf, etc.).
# Run from a real terminal — pspsh needs stdin connected to a TTY.
#
# IMPORTANT: crashes put the PSP hardware in a bad state.
# Always reset before relaunching. If reset doesn't respond, power-cycle the PSP.
set -euo pipefail
PSPSH="pspsh"
PRX_HOST="host0:/Dusk.prx"
RESET_SLEEP=3
# ---- rebuild (optional) -----------------------------------------------------
if [[ "${1:-}" == "--build" || "${1:-}" == "-b" ]]; then
echo "==> Building PSP (docker)..."
"$(dirname "$0")/build-psp-docker.sh"
echo ""
fi
# ---- sanity checks ----------------------------------------------------------
if ! command -v "$PSPSH" &>/dev/null; then
echo "ERROR: pspsh not found in PATH"
echo " Add /home/yourwishes/pspdev/bin to PATH or set PSPSH= in this script."
exit 1
fi
if ! nc -z localhost 10000 2>/dev/null; then
echo "ERROR: psplink is not reachable on localhost:10000."
echo " Ensure usbhostfs_pc is running and the PSP shows the psplink prompt."
exit 1
fi
# ---- reset any running process ----------------------------------------------
echo "==> Resetting PSP..."
"$PSPSH" -e "reset"
echo " Waiting ${RESET_SLEEP}s for PSP to settle..."
sleep "$RESET_SLEEP"
# ---- launch + stream output -------------------------------------------------
# Pre-send the exec command, then relay /dev/tty so pspsh keeps a live stdin.
# PSP stdout flows through pspsh directly to this terminal.
# Ctrl-C to stop.
echo "==> Launching $PRX_HOST"
echo " (PSP stdout streams here — Ctrl-C to stop)"
echo "------------------------------------------------------------"
{ printf 'exec %s\n' "$PRX_HOST"; cat /dev/tty; } | "$PSPSH"
+3 -1
View File
@@ -13,7 +13,6 @@ if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
elseif(DUSK_TARGET_SYSTEM STREQUAL "psp") elseif(DUSK_TARGET_SYSTEM STREQUAL "psp")
add_subdirectory(duskpsp) add_subdirectory(duskpsp)
add_subdirectory(dusksdl2) add_subdirectory(dusksdl2)
add_subdirectory(duskgl)
elseif(DUSK_TARGET_SYSTEM STREQUAL "vita") elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
add_subdirectory(duskvita) add_subdirectory(duskvita)
@@ -23,4 +22,7 @@ elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube") elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube")
add_subdirectory(duskdolphin) add_subdirectory(duskdolphin)
elseif(DUSK_TARGET_SYSTEM STREQUAL "saturn")
add_subdirectory(dusksaturn)
endif() endif()
-1
View File
@@ -56,7 +56,6 @@ add_subdirectory(animation)
add_subdirectory(event) add_subdirectory(event)
add_subdirectory(assert) add_subdirectory(assert)
add_subdirectory(asset) add_subdirectory(asset)
add_subdirectory(cutscene)
add_subdirectory(console) add_subdirectory(console)
add_subdirectory(display) add_subdirectory(display)
add_subdirectory(log) add_subdirectory(log)
+11 -4
View File
@@ -6,7 +6,7 @@
#include "animation.h" #include "animation.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/math.h" #include "util/fixed.h"
void animationInit( void animationInit(
animation_t *anim, animation_t *anim,
@@ -21,7 +21,7 @@ void animationInit(
anim->keyframeCount = keyframeCount; anim->keyframeCount = keyframeCount;
} }
float_t animationGetValue(animation_t *anim, const float_t time) { fixed_t animationGetValue(animation_t *anim, const fixed_t time) {
assertNotNull(anim, "Animation pointer cannot be null."); assertNotNull(anim, "Animation pointer cannot be null.");
assertNotNull(anim->keyframes, "Keyframes pointer cannot be null."); assertNotNull(anim->keyframes, "Keyframes pointer cannot be null.");
assertTrue(anim->keyframeCount > 0, "Keyframe count invalid."); assertTrue(anim->keyframeCount > 0, "Keyframe count invalid.");
@@ -47,6 +47,13 @@ float_t animationGetValue(animation_t *anim, const float_t time) {
} }
} while(true); } while(true);
float_t t = (time - start->time) / (end->time - start->time); fixed_t span = fixedSub(end->time, start->time);
return mathLerp(start->value, end->value, easingApply(start->easing, t)); fixed_t progress = span != 0
? fixedDiv(fixedSub(time, start->time), span)
: FIXED_ONE;
return fixedLerp(
start->value,
end->value,
easingApply(start->easing, progress)
);
} }
+1 -1
View File
@@ -31,4 +31,4 @@ void animationInit(
* @param time The time at which to get the value, in seconds. * @param time The time at which to get the value, in seconds.
* @return The value of the animation at the given time. * @return The value of the animation at the given time.
*/ */
float_t animationGetValue(animation_t *anim, const float_t time); fixed_t animationGetValue(animation_t *anim, const fixed_t time);
+66 -46
View File
@@ -6,6 +6,11 @@
#include "easing.h" #include "easing.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/math.h" #include "util/math.h"
#include "util/fixed.h"
#define EASING_C1 1.70158f
#define EASING_C2 (EASING_C1 * 1.525f)
#define EASING_C3 (EASING_C1 + 1.0f)
const easingfn_t EASING_FUNCTIONS[EASING_COUNT] = { const easingfn_t EASING_FUNCTIONS[EASING_COUNT] = {
easingLinear, easingLinear,
@@ -26,86 +31,101 @@ const easingfn_t EASING_FUNCTIONS[EASING_COUNT] = {
easingInOutBack, easingInOutBack,
}; };
float_t easingApply(const easingtype_t type, const float_t t) { fixed_t easingApply(const easingtype_t type, const fixed_t t) {
assertTrue(type < EASING_COUNT, "Invalid easing type"); assertTrue(type < EASING_COUNT, "Invalid easing type");
return EASING_FUNCTIONS[type](t); return EASING_FUNCTIONS[type](t);
} }
float_t easingLinear(const float_t t) { fixed_t easingLinear(const fixed_t t) {
return t; return t;
} }
float_t easingInSine(const float_t t) { fixed_t easingInSine(const fixed_t t) {
return 1.0f - cosf(t * MATH_PI * 0.5f); float_t f = fixedToFloat(t);
return fixedFromFloat(1.0f - cosf(f * MATH_PI * 0.5f));
} }
float_t easingOutSine(const float_t t) { fixed_t easingOutSine(const fixed_t t) {
return sinf(t * MATH_PI * 0.5f); float_t f = fixedToFloat(t);
return fixedFromFloat(sinf(f * MATH_PI * 0.5f));
} }
float_t easingInOutSine(const float_t t) { fixed_t easingInOutSine(const fixed_t t) {
return -(cosf(MATH_PI * t) - 1.0f) * 0.5f; float_t f = fixedToFloat(t);
return fixedFromFloat(-(cosf(MATH_PI * f) - 1.0f) * 0.5f);
} }
float_t easingInQuad(const float_t t) { fixed_t easingInQuad(const fixed_t t) {
return t * t; float_t f = fixedToFloat(t);
return fixedFromFloat(f * f);
} }
float_t easingOutQuad(const float_t t) { fixed_t easingOutQuad(const fixed_t t) {
float_t u = 1.0f - t; float_t f = fixedToFloat(t);
return 1.0f - u * u; float_t u = 1.0f - f;
return fixedFromFloat(1.0f - u * u);
} }
float_t easingInOutQuad(const float_t t) { fixed_t easingInOutQuad(const fixed_t t) {
if(t < 0.5f) return 2.0f * t * t; float_t f = fixedToFloat(t);
float_t u = -2.0f * t + 2.0f; if(f < 0.5f) return fixedFromFloat(2.0f * f * f);
return 1.0f - u * u * 0.5f; float_t u = -2.0f * f + 2.0f;
return fixedFromFloat(1.0f - u * u * 0.5f);
} }
float_t easingInCubic(const float_t t) { fixed_t easingInCubic(const fixed_t t) {
return t * t * t; float_t f = fixedToFloat(t);
return fixedFromFloat(f * f * f);
} }
float_t easingOutCubic(const float_t t) { fixed_t easingOutCubic(const fixed_t t) {
float_t u = 1.0f - t; float_t f = fixedToFloat(t);
return 1.0f - u * u * u; float_t u = 1.0f - f;
return fixedFromFloat(1.0f - u * u * u);
} }
float_t easingInOutCubic(const float_t t) { fixed_t easingInOutCubic(const fixed_t t) {
if(t < 0.5f) return 4.0f * t * t * t; float_t f = fixedToFloat(t);
float_t u = -2.0f * t + 2.0f; if(f < 0.5f) return fixedFromFloat(4.0f * f * f * f);
return 1.0f - u * u * u * 0.5f; float_t u = -2.0f * f + 2.0f;
return fixedFromFloat(1.0f - u * u * u * 0.5f);
} }
float_t easingInQuart(const float_t t) { fixed_t easingInQuart(const fixed_t t) {
return t * t * t * t; float_t f = fixedToFloat(t);
return fixedFromFloat(f * f * f * f);
} }
float_t easingOutQuart(const float_t t) { fixed_t easingOutQuart(const fixed_t t) {
float_t u = 1.0f - t; float_t f = fixedToFloat(t);
return 1.0f - u * u * u * u; float_t u = 1.0f - f;
return fixedFromFloat(1.0f - u * u * u * u);
} }
float_t easingInOutQuart(const float_t t) { fixed_t easingInOutQuart(const fixed_t t) {
if(t < 0.5f) return 8.0f * t * t * t * t; float_t f = fixedToFloat(t);
float_t u = -2.0f * t + 2.0f; if(f < 0.5f) return fixedFromFloat(8.0f * f * f * f * f);
return 1.0f - u * u * u * u * 0.5f; float_t u = -2.0f * f + 2.0f;
return fixedFromFloat(1.0f - u * u * u * u * 0.5f);
} }
float_t easingInBack(const float_t t) { fixed_t easingInBack(const fixed_t t) {
return EASING_C3 * t * t * t - EASING_C1 * t * t; float_t f = fixedToFloat(t);
return fixedFromFloat(EASING_C3 * f * f * f - EASING_C1 * f * f);
} }
float_t easingOutBack(const float_t t) { fixed_t easingOutBack(const fixed_t t) {
float_t u = t - 1.0f; float_t f = fixedToFloat(t);
return 1.0f + EASING_C3 * u * u * u + EASING_C1 * u * u; float_t u = f - 1.0f;
return fixedFromFloat(1.0f + EASING_C3 * u * u * u + EASING_C1 * u * u);
} }
float_t easingInOutBack(const float_t t) { fixed_t easingInOutBack(const fixed_t t) {
if(t < 0.5f) { float_t f = fixedToFloat(t);
float_t u = 2.0f * t; if(f < 0.5f) {
return u * u * ((EASING_C2 + 1.0f) * u - EASING_C2) * 0.5f; float_t u = 2.0f * f;
return fixedFromFloat(u * u * ((EASING_C2 + 1.0f) * u - EASING_C2) * 0.5f);
} }
float_t u = 2.0f * t - 2.0f; float_t u = 2.0f * f - 2.0f;
return (u * u * ((EASING_C2 + 1.0f) * u + EASING_C2) + 2.0f) * 0.5f; return fixedFromFloat((u * u * ((EASING_C2 + 1.0f) * u + EASING_C2) + 2.0f) * 0.5f);
} }
+21 -25
View File
@@ -5,11 +5,7 @@
#pragma once #pragma once
#include "dusk.h" #include "dusk.h"
#include "util/fixed.h"
#define EASING_PI 3.14159265358979323846f
#define EASING_C1 1.70158f
#define EASING_C2 (EASING_C1 * 1.525f)
#define EASING_C3 (EASING_C1 + 1.0f)
typedef enum { typedef enum {
EASING_LINEAR, EASING_LINEAR,
@@ -32,7 +28,7 @@ typedef enum {
EASING_COUNT EASING_COUNT
} easingtype_t; } easingtype_t;
typedef float_t (*easingfn_t)(const float_t t); typedef fixed_t (*easingfn_t)(const fixed_t t);
extern const easingfn_t EASING_FUNCTIONS[EASING_COUNT]; extern const easingfn_t EASING_FUNCTIONS[EASING_COUNT];
@@ -40,24 +36,24 @@ extern const easingfn_t EASING_FUNCTIONS[EASING_COUNT];
* Applies the specified easing function to t. * Applies the specified easing function to t.
* *
* @param type The easing type to apply. * @param type The easing type to apply.
* @param t The input time, in the range [0, 1]. * @param t The input progress in [0, FIXED_ONE].
* @return The eased value, in the range [0, 1]. * @return The eased value in [0, FIXED_ONE].
*/ */
float_t easingApply(const easingtype_t type, const float_t t); fixed_t easingApply(const easingtype_t type, const fixed_t t);
float_t easingLinear(const float_t t); fixed_t easingLinear(const fixed_t t);
float_t easingInSine(const float_t t); fixed_t easingInSine(const fixed_t t);
float_t easingOutSine(const float_t t); fixed_t easingOutSine(const fixed_t t);
float_t easingInOutSine(const float_t t); fixed_t easingInOutSine(const fixed_t t);
float_t easingInQuad(const float_t t); fixed_t easingInQuad(const fixed_t t);
float_t easingOutQuad(const float_t t); fixed_t easingOutQuad(const fixed_t t);
float_t easingInOutQuad(const float_t t); fixed_t easingInOutQuad(const fixed_t t);
float_t easingInCubic(const float_t t); fixed_t easingInCubic(const fixed_t t);
float_t easingOutCubic(const float_t t); fixed_t easingOutCubic(const fixed_t t);
float_t easingInOutCubic(const float_t t); fixed_t easingInOutCubic(const fixed_t t);
float_t easingInQuart(const float_t t); fixed_t easingInQuart(const fixed_t t);
float_t easingOutQuart(const float_t t); fixed_t easingOutQuart(const fixed_t t);
float_t easingInOutQuart(const float_t t); fixed_t easingInOutQuart(const fixed_t t);
float_t easingInBack(const float_t t); fixed_t easingInBack(const fixed_t t);
float_t easingOutBack(const float_t t); fixed_t easingOutBack(const fixed_t t);
float_t easingInOutBack(const float_t t); fixed_t easingInOutBack(const fixed_t t);
+3 -2
View File
@@ -5,9 +5,10 @@
#pragma once #pragma once
#include "easing.h" #include "easing.h"
#include "util/fixed.h"
typedef struct { typedef struct {
float_t time; fixed_t time;
float_t value; fixed_t value;
easingtype_t easing; easingtype_t easing;
} keyframe_t; } keyframe_t;
+1 -1
View File
@@ -12,6 +12,6 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
# Subdirs # Subdirs
add_subdirectory(display) # add_subdirectory(display) # disabled: pending rop-based asset loader rewrite
add_subdirectory(locale) add_subdirectory(locale)
add_subdirectory(json) add_subdirectory(json)
-18
View File
@@ -10,24 +10,6 @@
assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = { assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
[ASSET_LOADER_TYPE_NULL] = { 0 }, [ASSET_LOADER_TYPE_NULL] = { 0 },
[ASSET_LOADER_TYPE_MESH] = {
.loadSync = assetMeshLoaderSync,
.loadAsync = assetMeshLoaderAsync,
.dispose = assetMeshDispose
},
[ASSET_LOADER_TYPE_TEXTURE] = {
.loadSync = assetTextureLoaderSync,
.loadAsync = assetTextureLoaderAsync,
.dispose = assetTextureDispose
},
[ASSET_LOADER_TYPE_TILESET] = {
.loadSync = assetTilesetLoaderSync,
.loadAsync = assetTilesetLoaderAsync,
.dispose = assetTilesetDispose
},
[ASSET_LOADER_TYPE_LOCALE] = { [ASSET_LOADER_TYPE_LOCALE] = {
.loadSync = assetLocaleLoaderSync, .loadSync = assetLocaleLoaderSync,
.loadAsync = assetLocaleLoaderAsync, .loadAsync = assetLocaleLoaderAsync,
-17
View File
@@ -6,44 +6,27 @@
*/ */
#pragma once #pragma once
#include "asset/loader/display/assetmeshloader.h"
#include "asset/loader/display/assettextureloader.h"
#include "asset/loader/display/assettilesetloader.h"
#include "asset/loader/locale/assetlocaleloader.h" #include "asset/loader/locale/assetlocaleloader.h"
#include "asset/loader/json/assetjsonloader.h" #include "asset/loader/json/assetjsonloader.h"
typedef enum { typedef enum {
ASSET_LOADER_TYPE_NULL, ASSET_LOADER_TYPE_NULL,
ASSET_LOADER_TYPE_MESH,
ASSET_LOADER_TYPE_TEXTURE,
ASSET_LOADER_TYPE_TILESET,
ASSET_LOADER_TYPE_LOCALE, ASSET_LOADER_TYPE_LOCALE,
ASSET_LOADER_TYPE_JSON, ASSET_LOADER_TYPE_JSON,
ASSET_LOADER_TYPE_COUNT ASSET_LOADER_TYPE_COUNT
} assetloadertype_t; } assetloadertype_t;
typedef union { typedef union {
assetmeshloaderinput_t mesh;
assettextureloaderinput_t texture;
assettilesetloaderinput_t tileset;
assetlocaleloaderinput_t locale; assetlocaleloaderinput_t locale;
assetjsonloaderinput_t json; assetjsonloaderinput_t json;
} assetloaderinput_t; } assetloaderinput_t;
typedef union { typedef union {
assetmeshloaderloading_t mesh;
assettextureloaderloading_t texture;
assettilesetloaderloading_t tileset;
assetlocaleloaderloading_t locale; assetlocaleloaderloading_t locale;
assetjsonloaderloading_t json; assetjsonloaderloading_t json;
} assetloaderloading_t; } assetloaderloading_t;
typedef union { typedef union {
assetmeshoutput_t mesh;
assettextureoutput_t texture;
assettilesetoutput_t tileset;
assetlocaleoutput_t locale; assetlocaleoutput_t locale;
assetjsonoutput_t json; assetjsonoutput_t json;
} assetloaderoutput_t; } assetloaderoutput_t;
@@ -99,8 +99,8 @@ errorret_t assetTilesetLoaderSync(assetloading_t *loading) {
assetLoaderErrorThrow(loading, "Row count cannot be 0"); assetLoaderErrorThrow(loading, "Row count cannot be 0");
} }
out->uv[0] = endianLittleToHostFloat(*(float *)(data + 16)); out->uv[0] = endianLittleToHostFloat(*(float_t *)(data + 16));
out->uv[1] = endianLittleToHostFloat(*(float *)(data + 20)); out->uv[1] = endianLittleToHostFloat(*(float_t *)(data + 20));
if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) { if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) {
memoryFree(data); memoryFree(data);
@@ -816,17 +816,24 @@ errorret_t assetLocaleGetStringWithArgs(
case 'f': case 'f':
if( if(
args[nextArg].type != ASSET_LOCALE_ARG_FLOAT && args[nextArg].type != ASSET_LOCALE_ARG_FLOAT &&
args[nextArg].type != ASSET_LOCALE_ARG_INT args[nextArg].type != ASSET_LOCALE_ARG_INT &&
args[nextArg].type != ASSET_LOCALE_ARG_FIXED
) { ) {
memoryFree(format); memoryFree(format);
errorThrow("Expected float or int locale argument for ID: %s", id); errorThrow(
"Expected float, fixed, or int locale argument for ID: %s",
id
);
} }
float_t floatValue = ( float_t floatValue;
args[nextArg].type == ASSET_LOCALE_ARG_FLOAT ? if(args[nextArg].type == ASSET_LOCALE_ARG_FLOAT) {
args[nextArg].floatValue : floatValue = args[nextArg].floatValue;
(float_t)args[nextArg].intValue } else if(args[nextArg].type == ASSET_LOCALE_ARG_FIXED) {
); floatValue = fixedToFloat(args[nextArg].fixedValue);
} else {
floatValue = (float_t)args[nextArg].intValue;
}
written = snprintf( written = snprintf(
valueBuffer, valueBuffer,
@@ -7,6 +7,7 @@
#pragma once #pragma once
#include "asset/assetfile.h" #include "asset/assetfile.h"
#include "util/fixed.h"
typedef struct assetloading_s assetloading_t; typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t; typedef struct assetentry_s assetentry_t;
@@ -51,7 +52,8 @@ typedef enum {
typedef enum { typedef enum {
ASSET_LOCALE_ARG_STRING, ASSET_LOCALE_ARG_STRING,
ASSET_LOCALE_ARG_INT, ASSET_LOCALE_ARG_INT,
ASSET_LOCALE_ARG_FLOAT ASSET_LOCALE_ARG_FLOAT,
ASSET_LOCALE_ARG_FIXED
} assetlocaleargtype_t; } assetlocaleargtype_t;
/** /**
@@ -67,6 +69,7 @@ typedef struct {
const char_t *stringValue; const char_t *stringValue;
int32_t intValue; int32_t intValue;
float_t floatValue; float_t floatValue;
fixed_t fixedValue;
}; };
} assetlocalearg_t; } assetlocalearg_t;
+1 -14
View File
@@ -12,9 +12,6 @@
#include "input/input.h" #include "input/input.h"
#include "log/log.h" #include "log/log.h"
#include "engine/engine.h" #include "engine/engine.h"
#include "display/shader/shaderunlit.h"
#include "display/text/text.h"
#include "display/spritebatch/spritebatch.h"
console_t CONSOLE; console_t CONSOLE;
@@ -64,17 +61,7 @@ void consoleUpdate(void) {
} }
errorret_t consoleDraw(void) { errorret_t consoleDraw(void) {
if(!CONSOLE.visible) errorOk(); errorOk();
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
errorChain(textDraw(
0, FONT_DEFAULT.tileset->tileHeight * i,
CONSOLE.line[i],
COLOR_RED,
&FONT_DEFAULT
));
}
return spriteBatchFlush();
} }
void consoleDispose(void) { void consoleDispose(void) {
-96
View File
@@ -1,96 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include "cutscene.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "console/console.h"
#include "time/time.h"
cutscene_t CUTSCENE;
errorret_t cutsceneInit(void) {
memoryZero(&CUTSCENE, sizeof(cutscene_t));
errorOk();
}
errorret_t cutsceneUpdate(void) {
#ifdef DUSK_TIME_DYNAMIC
if(TIME.dynamicUpdate) {
errorOk();
}
#endif
if(!CUTSCENE.active) errorOk();
cutsceneevent_t *event = &CUTSCENE.events[CUTSCENE.eventCurrent];
if(event->onUpdate) errorChain(event->onUpdate());
errorOk();
}
errorret_t cutscenePlay(
const cutsceneevent_t *events,
const uint8_t eventCount
) {
assertNotNull(events, "Events cannot be null");
assertTrue(eventCount > 0, "Event count must be greater than zero");
assertTrue(
eventCount <= CUTSCENE_EVENT_COUNT_MAX,
"Event count exceeds CUTSCENE_EVENT_COUNT_MAX"
);
if(CUTSCENE.active) {
errorChain(cutsceneStop());
}
memoryCopy(CUTSCENE.events, events, sizeof(cutsceneevent_t) * eventCount);
CUTSCENE.eventCount = eventCount;
CUTSCENE.eventCurrent = 0;
CUTSCENE.active = true;
cutsceneevent_t *firstEvent = &CUTSCENE.events[0];
if(firstEvent->onStart) errorChain(firstEvent->onStart());
errorOk();
}
errorret_t cutsceneAdvance(void) {
if(!CUTSCENE.active) errorOk();
cutsceneevent_t *currentEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
if(currentEvent->onEnd) errorChain(currentEvent->onEnd());
CUTSCENE.eventCurrent++;
if(CUTSCENE.eventCurrent >= CUTSCENE.eventCount) {
if(CUTSCENE.onStop) errorChain(CUTSCENE.onStop());
CUTSCENE.active = false;
errorOk();
}
cutsceneevent_t *nextEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
if(nextEvent->onStart) errorChain(nextEvent->onStart());
consolePrint("Cutscene advance");
errorOk();
}
errorret_t cutsceneStop(void) {
if(!CUTSCENE.active) errorOk();
cutsceneevent_t *currentEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
if(currentEvent->onEnd) errorChain(currentEvent->onEnd());
if(CUTSCENE.onStop) errorChain(CUTSCENE.onStop());
CUTSCENE.active = false;
errorOk();
}
errorret_t cutsceneDispose(void) {
errorChain(cutsceneStop());
errorOk();
}
bool_t cutsceneIsActive(void) {
return CUTSCENE.active;
}
-85
View File
@@ -1,85 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#pragma once
#include "error/error.h"
#define CUTSCENE_EVENT_COUNT_MAX 16
typedef struct {
errorret_t (*onStart)(void);
errorret_t (*onEnd)(void);
errorret_t (*onUpdate)(void);
} cutsceneevent_t;
typedef struct {
cutsceneevent_t events[CUTSCENE_EVENT_COUNT_MAX];
uint8_t eventCount;
uint8_t eventCurrent;
errorret_t (*onStop)(void);
bool_t active;
} cutscene_t;
extern cutscene_t CUTSCENE;
/**
* Initializes the cutscene manager.
*
* @return Any error state that happened.
*/
errorret_t cutsceneInit(void);
/**
* Ticks the active cutscene event, calling its onUpdate callback.
* Does nothing when no cutscene is playing.
*
* @return Any error state that happened.
*/
errorret_t cutsceneUpdate(void);
/**
* Copies the given event array and begins playing from the first
* event. If a cutscene is already playing it is stopped first.
*
* @param events Array of events to copy.
* @param eventCount Number of events. Must be > 0 and
* <= CUTSCENE_EVENT_COUNT_MAX.
* @return Any error state that happened.
*/
errorret_t cutscenePlay(
const cutsceneevent_t *events,
const uint8_t eventCount
);
/**
* Ends the current event and starts the next one.
* Marks the cutscene as inactive after the last event ends.
* Does nothing when no cutscene is playing.
*
* @return Any error state that happened.
*/
errorret_t cutsceneAdvance(void);
/**
* Ends the current event and stops the cutscene immediately.
* Does nothing when no cutscene is playing.
*
* @return Any error state that happened.
*/
errorret_t cutsceneStop(void);
/**
* Disposes of the cutscene manager, stopping any active cutscene.
*
* @return Any error state that happened.
*/
errorret_t cutsceneDispose(void);
/**
* Returns whether a cutscene is currently playing.
*
* @return true if a cutscene is active.
*/
bool_t cutsceneIsActive(void);
+3 -12
View File
@@ -1,24 +1,14 @@
# Copyright (c) 2025 Dominic Masters # Copyright (c) 2026 Dominic Masters
# #
# This software is released under the MIT License. # This software is released under the MIT License.
# https://opensource.org/licenses/MIT # https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
display.c display.c
screen.c
) )
# Subdirectories
add_subdirectory(framebuffer)
add_subdirectory(mesh)
add_subdirectory(screen)
add_subdirectory(shader)
add_subdirectory(spritebatch)
add_subdirectory(text)
add_subdirectory(texture)
# Color definitions
dusk_run_python( dusk_run_python(
dusk_color_defs dusk_color_defs
tools.color.csv tools.color.csv
@@ -26,3 +16,4 @@ dusk_run_python(
--output ${DUSK_GENERATED_HEADERS_DIR}/display/color.h --output ${DUSK_GENERATED_HEADERS_DIR}/display/color.h
) )
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} dusk_color_defs) add_dependencies(${DUSK_LIBRARY_TARGET_NAME} dusk_color_defs)
add_subdirectory(render)
+5 -81
View File
@@ -6,111 +6,35 @@
*/ */
#include "display/display.h" #include "display/display.h"
#include "display/framebuffer/framebuffer.h" #include "display/render/ropbuffer.h"
#include "scene/scene.h" #include "scene/scene.h"
#include "display/spritebatch/spritebatch.h"
#include "display/mesh/quad.h"
#include "display/mesh/cube.h"
#include "display/mesh/sphere.h"
#include "display/mesh/plane.h"
#include "display/mesh/capsule.h"
#include "display/mesh/triprism.h"
#include "display/screen/screen.h"
#include "ui/ui.h"
#include "display/text/text.h"
#include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h"
#include "asset/asset.h"
#include "display/shader/shaderlist.h"
#include "time/time.h"
display_t DISPLAY = { 0 }; display_t DISPLAY = { 0 };
errorret_t displayInit(void) { errorret_t displayInit(void) {
memoryZero(&DISPLAY, sizeof(DISPLAY)); memoryZero(&DISPLAY, sizeof(DISPLAY));
#ifdef displayPlatformInit #ifdef displayPlatformInit
errorChain(displayPlatformInit()); errorChain(displayPlatformInit());
#endif #endif
errorChain(displaySetState((displaystate_t){ .flags = 0 }));
errorChain(textureInit(
&TEXTURE_WHITE, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_WHITE_PIXELS }
));
errorChain(textureInit(
&TEXTURE_TEST, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_TEST_PIXELS }
));
// Standard meshes
errorChain(quadInit());
errorChain(cubeInit());
errorChain(sphereInit());
errorChain(planeInit());
errorChain(capsuleInit());
errorChain(triPrismInit());
errorChain(frameBufferInitBackBuffer());
errorChain(spriteBatchInit());
errorChain(textInit());
errorChain(screenInit());
// Setup initial shader with default values
errorChain(shaderListInit());
errorOk(); errorOk();
} }
errorret_t displayUpdate(void) { errorret_t displayUpdate(void) {
#ifdef displayPlatformUpdate ropBufferReset(&ROPBUFFER);
errorChain(displayPlatformUpdate());
#endif
// Reset state
spriteBatchClear();
errorChain(frameBufferBind(NULL));
// Bind screen and render scene
errorChain(screenBind());
frameBufferClear(
FRAMEBUFFER_CLEAR_COLOR | FRAMEBUFFER_CLEAR_DEPTH,
SCREEN.background
);
errorChain(sceneRender()); errorChain(sceneRender());
#ifdef displayPlatformFlush
// Finish up errorChain(displayPlatformFlush(&ROPBUFFER));
screenUnbind(); #endif
screenRender();
// Swap and return.
#ifdef displayPlatformSwap #ifdef displayPlatformSwap
errorChain(displayPlatformSwap()); errorChain(displayPlatformSwap());
#endif #endif
errorOk(); errorOk();
} }
errorret_t displaySetState(displaystate_t state) {
#ifdef displayPlatformSetState
errorChain(displayPlatformSetState(state));
#endif
errorOk();
}
errorret_t displayDispose(void) { errorret_t displayDispose(void) {
errorChain(shaderListDispose());
errorChain(spriteBatchDispose());
screenDispose();
errorChain(textDispose());
errorChain(textureDispose(&TEXTURE_WHITE));
errorChain(textureDispose(&TEXTURE_TEST));
#ifdef displayPlatformDispose #ifdef displayPlatformDispose
displayPlatformDispose(); displayPlatformDispose();
#endif #endif
// For now, we just return an OK error.
errorOk(); errorOk();
} }
+1 -48
View File
@@ -7,59 +7,12 @@
#pragma once #pragma once
#include "display/displayplatform.h" #include "display/displayplatform.h"
#include "display/displaystate.h"
// Expecting some definitions to be provided
#ifndef DUSK_DISPLAY_SIZE_DYNAMIC
#ifndef DUSK_DISPLAY_WIDTH
#error "DUSK_DISPLAY_WIDTH must be defined."
#endif
#ifndef DUSK_DISPLAY_HEIGHT
#error "DUSK_DISPLAY_HEIGHT must be defined"
#endif
#define DUSK_DISPLAY_WIDTH_DEFAULT DUSK_DISPLAY_WIDTH
#define DUSK_DISPLAY_HEIGHT_DEFAULT DUSK_DISPLAY_HEIGHT
#else
#ifndef DUSK_DISPLAY_WIDTH_DEFAULT
#error "DUSK_DISPLAY_WIDTH_DEFAULT must be defined."
#endif
#ifndef DUSK_DISPLAY_HEIGHT_DEFAULT
#error "DUSK_DISPLAY_HEIGHT_DEFAULT must be defined."
#endif
#ifdef DUSK_DISPLAY_WIDTH
#error "DUSK_DISPLAY_WIDTH should not be defined."
#endif
#ifdef DUSK_DISPLAY_HEIGHT
#error "DUSK_DISPLAY_HEIGHT should not be defined."
#endif
#endif
// Main Display Struct, platform-speicifc
typedef displayplatform_t display_t; typedef displayplatform_t display_t;
extern display_t DISPLAY; extern display_t DISPLAY;
/**
* Initializes the display system.
* @return An errorret_t indicating success or failure.
*/
errorret_t displayInit(void); errorret_t displayInit(void);
/**
* Tells the display system to actually draw the frame.
* @return An errorret_t indicating success or failure.
*/
errorret_t displayUpdate(void); errorret_t displayUpdate(void);
/**
* Sets the display state.
*
* @param state The state to set.
* @return An errorret_t indicating success or failure.
*/
errorret_t displaySetState(displaystate_t state);
/**
* Disposes of the display system.
* @return An errorret_t indicating success or failure.
*/
errorret_t displayDispose(void); errorret_t displayDispose(void);
@@ -3,8 +3,8 @@
# This software is released under the MIT License. # This software is released under the MIT License.
# https://opensource.org/licenses/MIT # https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
framebuffergl.c ropbuffer.c
render.c
) )
+134
View File
@@ -0,0 +1,134 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "display/render/render.h"
#include "display/render/renderplatform.h"
void renderClear(color_t color) {
ropclear_t *cmd = ropBufferAlloc(&ROPBUFFER, ROP_CLEAR);
cmd->color = color;
}
void renderSprite(
int16_t x, int16_t y, int16_t w, int16_t h,
int16_t depth,
rtexture_t texture, color_t tint
) {
ropsprite_t *cmd = ropBufferAlloc(&ROPBUFFER, ROP_DRAW_SPRITE);
cmd->header.depth = depth;
cmd->x = x;
cmd->y = y;
cmd->w = w;
cmd->h = h;
cmd->uvX = 0;
cmd->uvY = 0;
cmd->uvW = 255;
cmd->uvH = 255;
cmd->tint = tint;
cmd->texture = texture;
}
void renderSetProjection(fixed_t fovY, fixed_t aspect, fixed_t nearZ, fixed_t farZ) {
ropprojection_t *cmd = ropBufferAlloc(&ROPBUFFER, ROP_SET_PROJECTION);
cmd->fovY = fovY;
cmd->aspect = aspect;
cmd->nearZ = nearZ;
cmd->farZ = farZ;
}
void renderSetView(
int16_t eyeX, int16_t eyeY, int16_t eyeZ,
int16_t tgtX, int16_t tgtY, int16_t tgtZ
) {
ropview_t *cmd = ropBufferAlloc(&ROPBUFFER, ROP_SET_VIEW);
cmd->eyeX = eyeX; cmd->eyeY = eyeY; cmd->eyeZ = eyeZ;
cmd->tgtX = tgtX; cmd->tgtY = tgtY; cmd->tgtZ = tgtZ;
}
void renderQuad3D(
int16_t cx, int16_t cy, int16_t cz,
int16_t rx, int16_t ry, int16_t rz,
int16_t ux, int16_t uy, int16_t uz,
int16_t depth,
rtexture_t texture, color_t tint
) {
ropquad3d_t *cmd = ropBufferAlloc(&ROPBUFFER, ROP_DRAW_QUAD_3D);
cmd->header.depth = depth;
cmd->cx = cx; cmd->cy = cy; cmd->cz = cz;
cmd->rx = rx; cmd->ry = ry; cmd->rz = rz;
cmd->ux = ux; cmd->uy = uy; cmd->uz = uz;
cmd->uvX = 0; cmd->uvY = 0;
cmd->uvW = 255; cmd->uvH = 255;
cmd->tint = tint;
cmd->texture = texture;
}
rtexture_t renderTextureCreate(
uint16_t w, uint16_t h,
const uint8_t *indices, const color_t *palette
) {
#ifdef renderPlatformTextureCreate
return renderPlatformTextureCreate(w, h, indices, palette);
#else
return RTEXTURE_NONE;
#endif
}
void renderTextureDispose(rtexture_t tex) {
#ifdef renderPlatformTextureDispose
renderPlatformTextureDispose(tex);
#endif
}
color_t *renderTextureGetPalette(rtexture_t tex) {
#ifdef renderPlatformTextureGetPalette
return renderPlatformTextureGetPalette(tex);
#else
return NULL;
#endif
}
uint8_t *renderTextureGetIndices(rtexture_t tex) {
#ifdef renderPlatformTextureGetIndices
return renderPlatformTextureGetIndices(tex);
#else
return NULL;
#endif
}
rtilemapchunk_t renderTilemapChunkCreate(
uint16_t chunkW, uint16_t chunkH,
uint16_t tileW, uint16_t tileH,
rtexture_t tileset,
const uint8_t *tileIndices
) {
#ifdef renderPlatformTilemapChunkCreate
return renderPlatformTilemapChunkCreate(
chunkW, chunkH, tileW, tileH, tileset, tileIndices
);
#else
return RTILEMAPCHUNK_INVALID;
#endif
}
void renderTilemapChunkDispose(rtilemapchunk_t chunk) {
#ifdef renderPlatformTilemapChunkDispose
renderPlatformTilemapChunkDispose(chunk);
#endif
}
void renderTilemapChunk(
int16_t x, int16_t y,
int16_t depth,
rtilemapchunk_t chunk
) {
roptilemapc_t *cmd = ropBufferAlloc(&ROPBUFFER, ROP_DRAW_TILEMAP_CHUNK);
cmd->header.depth = depth;
cmd->x = x;
cmd->y = y;
cmd->chunk = chunk;
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "display/render/rop.h"
#include "display/render/ropbuffer.h"
#include "display/render/rtexture.h"
#include "display/render/rtilemapchunk.h"
/* ---- 2D ------------------------------------------------------------------ */
void renderClear(color_t color);
void renderSprite(
int16_t x, int16_t y, int16_t w, int16_t h,
int16_t depth,
rtexture_t texture, color_t tint
);
/* ---- 3D ------------------------------------------------------------------ */
void renderSetProjection(
fixed_t fovY, fixed_t aspect, fixed_t nearZ, fixed_t farZ
);
void renderSetView(
int16_t eyeX, int16_t eyeY, int16_t eyeZ,
int16_t tgtX, int16_t tgtY, int16_t tgtZ
);
/* World-space quad: center + right half-extent + up half-extent. */
void renderQuad3D(
int16_t cx, int16_t cy, int16_t cz,
int16_t rx, int16_t ry, int16_t rz,
int16_t ux, int16_t uy, int16_t uz,
int16_t depth,
rtexture_t texture, color_t tint
);
/* ---- Textures ------------------------------------------------------------ */
/* 8-bit indexed palette texture. palette must contain exactly 256 entries. */
rtexture_t renderTextureCreate(
uint16_t w, uint16_t h,
const uint8_t *indices, const color_t *palette
);
void renderTextureDispose(rtexture_t tex);
/* Mutable access to the CPU-side palette and index arrays.
* Write to these pointers directly; the next draw call picks up the changes.
* GL re-uploads to the GPU texture lazily at bind (dirty flag); PSP/Dolphin
* re-convert their native format (ABGR/CI8) at bind time from these arrays. */
color_t *renderTextureGetPalette(rtexture_t tex); /* color_t[256] */
uint8_t *renderTextureGetIndices(rtexture_t tex); /* uint8_t[w*h], row-major */
/* ---- Tilemap chunks ------------------------------------------------------- */
/* Build a pre-baked chunk from a tile-index array. The backend constructs
* its native draw structure (VAO+VBO on GL, display list on PSP/GX/N64) once
* at create time; subsequent renderTilemapChunk() calls cost only one ROP
* entry and one native draw call per chunk.
*
* chunkW/chunkH — chunk size in tiles
* tileW/tileH — pixel dimensions of one tile in the tileset texture
* tileset — palettized texture containing all tiles packed in a grid
* tileIndices — chunkW*chunkH uint8_t values; each is a tile index into the
* tileset grid (row-major, tile 0 = top-left of tileset) */
rtilemapchunk_t renderTilemapChunkCreate(
uint16_t chunkW, uint16_t chunkH,
uint16_t tileW, uint16_t tileH,
rtexture_t tileset,
const uint8_t *tileIndices
);
void renderTilemapChunkDispose(rtilemapchunk_t chunk);
/* Emit a ROP_DRAW_TILEMAP_CHUNK entry. x/y are the screen-space pixel position
* of the chunk's top-left corner. */
void renderTilemapChunk(
int16_t x, int16_t y,
int16_t depth,
rtilemapchunk_t chunk
);
+120
View File
@@ -0,0 +1,120 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "display/color.h"
#include "display/render/rtexture.h"
#include "display/render/rtilemapchunk.h"
#include "util/fixed.h"
/* Fixed size for all 2D/state opcodes. 3D quads use ROP_SIZE_3D. */
#define ROP_SIZE 32
#define ROP_SIZE_3D 64
typedef enum {
ROP_NOP = 0,
ROP_CLEAR,
ROP_DRAW_SPRITE, /* 2D screen-space quad ROP_SIZE */
ROP_SET_PROJECTION, /* perspective / ortho params ROP_SIZE */
ROP_SET_VIEW, /* camera eye + target ROP_SIZE */
ROP_DRAW_QUAD_3D, /* world-space textured quad ROP_SIZE_3D */
ROP_DRAW_TILEMAP_CHUNK, /* pre-built tile chunk handle ROP_SIZE */
ROP_COUNT
} ropop_t;
#define ROP_FLAG_BLEND ((uint8_t)(1 << 0))
/* Returns the byte size of a given opcode. */
static inline uint32_t ropOpSize(ropop_t op) {
if(op == ROP_DRAW_QUAD_3D) return ROP_SIZE_3D;
return ROP_SIZE;
}
/* 4-byte header that starts every opcode. */
typedef struct {
uint8_t op;
uint8_t flags;
int16_t depth;
} ropheader_t;
_Static_assert(sizeof(ropheader_t) == 4, "ropheader_t must be 4 bytes");
/* ROP_CLEAR — 32 bytes */
typedef struct {
ropheader_t header; /* 4 */
color_t color; /* 4 */
uint8_t pad[24];/* 24 */
} ropclear_t;
_Static_assert(sizeof(ropclear_t) == ROP_SIZE, "ropclear_t must be ROP_SIZE bytes");
/* ROP_DRAW_SPRITE — 32 bytes, screen-space pixel coordinates */
typedef struct {
ropheader_t header; /* 4 */
int16_t x, y; /* 4 */
int16_t w, h; /* 4 */
uint8_t uvX, uvY; /* 2 */
uint8_t uvW, uvH; /* 2 */
color_t tint; /* 4 */
uint16_t texture; /* 2 handle, 0 = white */
uint16_t palette; /* 2 */
uint8_t pad[8]; /* 8 */
} ropsprite_t;
_Static_assert(sizeof(ropsprite_t) == ROP_SIZE, "ropsprite_t must be ROP_SIZE bytes");
/* ROP_SET_PROJECTION — 32 bytes. fovY==0 means orthographic. */
typedef struct {
ropheader_t header; /* 4 */
fixed_t fovY; /* 4 radians; 0 = ortho */
fixed_t aspect; /* 4 w/h */
fixed_t nearZ; /* 4 */
fixed_t farZ; /* 4 */
uint8_t pad[12]; /* 12 */
} ropprojection_t;
_Static_assert(sizeof(ropprojection_t) == ROP_SIZE, "ropprojection_t must be ROP_SIZE bytes");
/* ROP_SET_VIEW — 32 bytes. Camera eye position and look-at target. */
typedef struct {
ropheader_t header; /* 4 */
int16_t eyeX, eyeY, eyeZ; /* 6 */
int16_t tgtX, tgtY, tgtZ; /* 6 */
uint8_t pad[16]; /* 16 */
} ropview_t;
_Static_assert(sizeof(ropview_t) == ROP_SIZE, "ropview_t must be ROP_SIZE bytes");
/* ROP_DRAW_QUAD_3D — 64 bytes.
* Quad defined by center + two half-extent vectors.
* Corners: center ± right ± up
*/
typedef struct {
ropheader_t header; /* 4 */
int16_t cx, cy, cz; /* 6 center */
int16_t rx, ry, rz; /* 6 right half-ext */
int16_t ux, uy, uz; /* 6 up half-ext */
uint8_t uvX, uvY; /* 2 */
uint8_t uvW, uvH; /* 2 */
color_t tint; /* 4 */
uint16_t texture; /* 2 handle, 0=white */
uint8_t pad[32]; /* 32 */
} ropquad3d_t;
_Static_assert(sizeof(ropquad3d_t) == ROP_SIZE_3D, "ropquad3d_t must be ROP_SIZE_3D bytes");
/* ROP_DRAW_TILEMAP_CHUNK — 32 bytes.
* References a pre-built backend chunk by handle; x/y are the screen-space
* pixel offset applied at draw time. */
typedef struct {
ropheader_t header; /* 4 */
int16_t x, y; /* 4 screen-space pixel offset */
rtilemapchunk_t chunk; /* 2 handle, RTILEMAPCHUNK_INVALID = no-op */
uint8_t pad[22]; /* 22 */
} roptilemapc_t;
_Static_assert(sizeof(roptilemapc_t) == ROP_SIZE, "roptilemapc_t must be ROP_SIZE bytes");
+31
View File
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "display/render/ropbuffer.h"
#include "util/memory.h"
#include "assert/assert.h"
ropbuffer_t ROPBUFFER;
void ropBufferReset(ropbuffer_t *buf) {
buf->byteCount = 0;
buf->count = 0;
}
void *ropBufferAlloc(ropbuffer_t *buf, ropop_t op) {
uint32_t size = ropOpSize(op);
assertTrue(
buf->byteCount + size <= ROPBUFFER_BYTE_SIZE,
"ROP buffer is full"
);
uint8_t *ptr = buf->data + buf->byteCount;
memoryZero(ptr, size);
((ropheader_t *)ptr)->op = (uint8_t)op;
buf->byteCount += size;
buf->count++;
return ptr;
}
+23
View File
@@ -0,0 +1,23 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "display/render/rop.h"
/* 256 KB pool — enough for ~8192 2D sprites or ~4096 3D quads mixed. */
#define ROPBUFFER_BYTE_SIZE (256 * 1024)
typedef struct {
uint8_t data[ROPBUFFER_BYTE_SIZE];
uint32_t byteCount; /* bytes consumed this frame */
uint32_t count; /* number of commands */
} ropbuffer_t;
extern ropbuffer_t ROPBUFFER;
void ropBufferReset(ropbuffer_t *buf);
void *ropBufferAlloc(ropbuffer_t *buf, ropop_t op);
+13
View File
@@ -0,0 +1,13 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include <stdint.h>
typedef uint16_t rtexture_t;
#define RTEXTURE_NONE ((rtexture_t)0)
+13
View File
@@ -0,0 +1,13 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include <stdint.h>
typedef uint16_t rtilemapchunk_t;
#define RTILEMAPCHUNK_INVALID ((rtilemapchunk_t)0)

Some files were not shown because too many files have changed in this diff Show More