Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42cb84b610 | ||
|
|
f8607d114c | ||
|
|
56230dd340 | ||
|
|
df9fdf26c8 | ||
|
|
8f8fa8f8d1 | ||
|
|
07f98c119a | ||
|
|
d49194fc4d | ||
|
|
e61914bad4 | ||
|
|
015d90519f | ||
|
|
7b4f0abfb8 | ||
|
|
0667a44e14 | ||
|
|
0852b8463b | ||
|
|
1436fda858 | ||
|
|
0826908068 | ||
|
|
7ceb9e571d | ||
|
|
38c2f6b6f9 | ||
|
|
b9f06fef7a | ||
|
|
373f1c1010 | ||
|
|
e80d693d85 | ||
|
|
ef60ddf6a8 | ||
|
|
de0ff2e263 | ||
|
|
13a435e9c1 | ||
|
|
725338cd5a | ||
|
|
acd14f46a8 | ||
|
|
ef78f023ed | ||
|
|
85b6109792 | ||
|
|
6c5738c863 | ||
|
|
1174e471f6 | ||
|
|
a618ff46fe | ||
|
|
1fa5cd316e | ||
|
|
11e5d37563 | ||
|
|
9f86c20129 | ||
|
|
8fb1c9fb42 | ||
|
|
5f08337726 | ||
|
|
0bc80d5df3 | ||
|
|
2432443ea6 | ||
|
|
fa138971e7 | ||
|
|
d7982599d1 | ||
|
|
f16c80aa0f | ||
|
|
ef5adf8274 | ||
|
|
2ffc65b1b1 | ||
|
|
d4a17bd98d | ||
|
|
dcf5f434c5 | ||
|
|
78cd973a33 |
No files matched your search
@@ -0,0 +1,858 @@
|
|||||||
|
# Dusk Code Check
|
||||||
|
|
||||||
|
A working checklist for walking through `src/dusk/` (the core, platform-
|
||||||
|
agnostic engine layer) one subsystem at a time and reviewing how it
|
||||||
|
actually looks today -- not just what it's supposed to do. Pairs with
|
||||||
|
`STATUS.md` (maturity snapshot) and `ROADMAP.md` (forward-looking work);
|
||||||
|
this doc is about auditing what's already there.
|
||||||
|
|
||||||
|
Each section below: **Purpose**, **Key files**, and a **Review status**
|
||||||
|
line to fill in as each system gets walked through (e.g. `Not started` /
|
||||||
|
`In progress` / `Reviewed 2026-08-01: <one-line finding>`).
|
||||||
|
|
||||||
|
First full pass completed 2026-08-01 (all 23 sections below reviewed).
|
||||||
|
See "Top cross-cutting findings" right after the index for the
|
||||||
|
highest-priority items across all of them before diving into any one
|
||||||
|
section -- this doc is long, don't make someone read all 23 to find
|
||||||
|
the load-bearing bugs.
|
||||||
|
|
||||||
|
Game-specific code lives in `src/duskrpg/` (not covered here) and
|
||||||
|
platform-specific implementations live in `src/dusk<platform>/` /
|
||||||
|
`src/duskgl/` / `src/dusksdl2/` (also not covered here) -- see `CLAUDE.md`
|
||||||
|
for the layer structure.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Index
|
||||||
|
|
||||||
|
- [error](#error)
|
||||||
|
- [assert](#assert)
|
||||||
|
- [util](#util)
|
||||||
|
- [event](#event)
|
||||||
|
- [time](#time)
|
||||||
|
- [thread](#thread)
|
||||||
|
- [log](#log)
|
||||||
|
- [system](#system)
|
||||||
|
- [console](#console)
|
||||||
|
- [asset](#asset)
|
||||||
|
- [locale](#locale)
|
||||||
|
- [save](#save)
|
||||||
|
- [network](#network)
|
||||||
|
- [display](#display)
|
||||||
|
- [ui](#ui)
|
||||||
|
- [entity](#entity)
|
||||||
|
- [scene](#scene)
|
||||||
|
- [physics](#physics)
|
||||||
|
- [animation](#animation)
|
||||||
|
- [script](#script)
|
||||||
|
- [input](#input)
|
||||||
|
- [engine](#engine)
|
||||||
|
- [game](#game)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Top cross-cutting findings
|
||||||
|
|
||||||
|
Ranked roughly by real-world impact, not by section order. Each links
|
||||||
|
to its full writeup below.
|
||||||
|
|
||||||
|
1. **Bounds/capacity checks that matter at runtime are `assert*` calls,
|
||||||
|
which compile to no-ops in release (`DUSK_ASSERTIONS_FAKED`, set
|
||||||
|
whenever `NDEBUG` is defined) -- confirmed by reading `assert.h`
|
||||||
|
directly.** This shows up in [entity](#entity) (`entitymanager.c`,
|
||||||
|
`component.c` -- reachable from JerryScript via `moduleentity.c`
|
||||||
|
with no return-value check) and [scene](#scene) (`sceneCreate`'s
|
||||||
|
pool-exhaustion path, reachable from `new Scene()`). Untrusted
|
||||||
|
script input can silently get back an invalid ID that later indexes
|
||||||
|
a fixed array out of bounds in a release build -- the exact
|
||||||
|
"validate untrusted data with errorThrow, not asserts" case
|
||||||
|
CLAUDE.md/project memory already calls out, just not applied here.
|
||||||
|
2. **FIXED 2026-08-01.** `util/ref.c`'s `refUnlock` decremented an
|
||||||
|
unsigned `count` guarded only by a tautological `count >= 0` assert
|
||||||
|
([util](#util)) -- a double-unlock silently underflowed to
|
||||||
|
`UINT32_MAX` instead of tripping an assert. This wasn't just a
|
||||||
|
`util/` nit: it's the lock/unlock primitive `asset/loader/assetentry.c`
|
||||||
|
builds on (see [asset](#asset)), so an over-unlocked asset entry
|
||||||
|
became permanently un-reapable rather than erroring loudly. Now
|
||||||
|
asserts `count > 0` before decrementing; the pointless
|
||||||
|
`count >= 0` check in `refLock` was removed too.
|
||||||
|
3. **`texture.c:42-52`'s `textureInit()` reads `texture->format` to
|
||||||
|
decide which `data` fields to validate *before* the struct is
|
||||||
|
zeroed a few lines later** ([display](#display)) -- it's validating
|
||||||
|
whatever stale value happened to be in the caller's (possibly
|
||||||
|
stack) memory, not the `format` parameter actually being requested.
|
||||||
|
4. **FIXED 2026-08-01 (confirmed real before fixing).** PSP's
|
||||||
|
`timeGetRealTimeZonePSP` returned hours; every other platform
|
||||||
|
(`timeGetRealTimeZoneLinux`/Dolphin) returns seconds, and
|
||||||
|
`timeEpochInit`/`timeEpochGetHours` etc. add the timezone value
|
||||||
|
directly to a Unix-epoch-seconds timestamp -- confirmed by reading
|
||||||
|
all three platform implementations plus `timeepoch.c` directly, not
|
||||||
|
just trusting the review agent's claim. The PSP function's own
|
||||||
|
comment even said "Return timezone offset in hours". Now divides by
|
||||||
|
`1000000.0` only (microseconds -> seconds), matching the other
|
||||||
|
platforms. See [time](#time).
|
||||||
|
5. **Discussed, not changed.** `consolePrint` aborts the process (via
|
||||||
|
`stringFormatVA`'s `assert(ret < destSize)`) instead of truncating
|
||||||
|
when a single debug line exceeds 511 bytes. This is a real, if rare,
|
||||||
|
crash risk (any format producing >511 bytes of runtime-variable
|
||||||
|
content -- a long path, a long error string -- takes the whole
|
||||||
|
process down over a debug print), but changing `stringFormatVA`
|
||||||
|
itself would affect every caller in the codebase, and a
|
||||||
|
console-local truncating rewrite is easy to do wrong (vsnprintf
|
||||||
|
directly, bypassing the project's string-utils convention) without
|
||||||
|
more time to get right. Left as-is pending a decision on which
|
||||||
|
fix shape is wanted. See [console](#console).
|
||||||
|
6. **FIXED 2026-08-01.** `thread.c`'s `threadHandler` signaled
|
||||||
|
`THREAD_STATE_STOPPED` before resetting `threadId = 0`, and
|
||||||
|
`threadStartRequest` wasn't synchronized against that reset -- a
|
||||||
|
real (if rare-window) race, not hypothetical: the test suite was
|
||||||
|
already working around it by re-calling `threadInit()` instead of
|
||||||
|
exercising true stop/start reuse. `threadId` is now reset inside the
|
||||||
|
same mutex-locked section before the STOPPED signal/unlock;
|
||||||
|
`test_thread_restart` now loops 20x on the same `thread_t` without
|
||||||
|
re-initializing, which would have caught the old race. See
|
||||||
|
[thread](#thread).
|
||||||
|
7. **FIXED 2026-08-01.** `tools/color.py` emitted invalid C float
|
||||||
|
literals (`0f`, `1f`, etc.) for any whole-number CSV channel --
|
||||||
|
confirmed by actually running the generator against `color.csv`
|
||||||
|
before and after. Was dormant only because `COLOR_*_3F`/`_4F` were
|
||||||
|
unreferenced anywhere in the repo; the first real use of a float
|
||||||
|
color variant wouldn't have compiled. Now routes channel values
|
||||||
|
through Python `float()` before interpolating (always stringifies
|
||||||
|
with a decimal point, e.g. `0.0`/`1.0`), and `test/display/test_color.c`
|
||||||
|
gained two tests that reference `COLOR_BLACK_3F`/`COLOR_WHITE_4F`/
|
||||||
|
`COLOR_RED_3B`/`COLOR_GRAY_3F` directly -- giving the previously-dead
|
||||||
|
generated macros real compile-time + value coverage instead of
|
||||||
|
silently bit-rotting again. See [display](#display).
|
||||||
|
8. **`assetModelLoaderAsync` is confirmed fully dead** -- model loading
|
||||||
|
is genuinely synchronous end-to-end (verified by tracing the state
|
||||||
|
machine, not just repeating STATUS.md's claim). See [asset](#asset).
|
||||||
|
9. **No cycle guard on prefab `extends` chains** in
|
||||||
|
`scenePrefabResolveAndApply` -- a self-referencing or A->B->A prefab
|
||||||
|
table is a stack-overflow crash from what looks like a harmless
|
||||||
|
typo in hand-authored data. See [scene](#scene).
|
||||||
|
10. **Untested-code hot spots worth prioritizing** if test investment
|
||||||
|
is on the table: `util/ref.c`/`random.c`/`crypt.c`/`endian.c`
|
||||||
|
(zero tests), `animation/easing.c` (13 of 16 functions untested),
|
||||||
|
`event/`, `console/`, `system/`, `log/`, `input/`, `engine/`,
|
||||||
|
`locale/`, `save/`, and most of `display/` (mesh, shader, texture,
|
||||||
|
tileset, text, screen, framebuffer) have no dedicated tests at
|
||||||
|
all.
|
||||||
|
|
||||||
|
Convention-only items (real, but lower stakes than the above): raw
|
||||||
|
stdlib string functions (`strlen`/`strchr`/`strstr`/etc.) show up
|
||||||
|
instead of `util/string.h` wrappers in `network/http/` and
|
||||||
|
`asset/loader/locale/assetlocaleloader.c` ([network](#network),
|
||||||
|
[asset](#asset)); several `display/mesh/` files use `//` header
|
||||||
|
comments and `/* */` inline comments where CLAUDE.md wants the
|
||||||
|
opposite ([display](#display)); `animation/`'s core files all use `//`
|
||||||
|
copyright headers instead of `/** */` ([animation](#animation)).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## error
|
||||||
|
|
||||||
|
**Purpose:** The engine's single error-handling convention. Every
|
||||||
|
fallible function returns `errorret_t`, built with `errorOk()` /
|
||||||
|
`errorThrow(fmt, ...)` / `errorChain(call)` and consumed with
|
||||||
|
`errorIsOk()`/`errorIsNotOk()`/`errorCatch()`. No `errno`, no raw error
|
||||||
|
codes anywhere else in the engine.
|
||||||
|
|
||||||
|
**Key files:** `error.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Solid, and tested unusually well
|
||||||
|
(`test/error/test_error.c` covers thread isolation and concurrent
|
||||||
|
throws, not just happy path). Two issues: `errorChainImpl` (error.c:86-91)
|
||||||
|
hand-rolls `snprintf`/`strlen` instead of `util/string.h`'s
|
||||||
|
`stringFormat`/`stringFormatVA` wrappers that `errorThrowImpl` uses one
|
||||||
|
function above it -- an inconsistency, not just a style nit, since
|
||||||
|
CLAUDE.md requires the wrappers everywhere. `errorThrowWithCode`
|
||||||
|
(error.h:100) is dead code -- zero call sites anywhere in `src/`/`test/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## assert
|
||||||
|
|
||||||
|
**Purpose:** Debug-time invariant checks -- `assertNotNull`, `assertTrue`,
|
||||||
|
`assertFalse`, `assertUnreachable`, `assertIsMainThread`. Distinct from
|
||||||
|
`error/`: asserts are for programmer mistakes/invariants, `errorret_t` is
|
||||||
|
for runtime-recoverable failures (see `CLAUDE.md`'s note on validating
|
||||||
|
untrusted data with `errorThrow` rather than asserting).
|
||||||
|
|
||||||
|
**Key files:** `assert.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Clean, no issues found. Impl
|
||||||
|
functions + macros wrapping `__FILE__`/`__LINE__` and a proper
|
||||||
|
`DUSK_ASSERTIONS_FAKED` no-op path for release builds;
|
||||||
|
`assertNotNullImpl` (assert.c:109-111) does a real "touch" dereference
|
||||||
|
after the null check as a belt-and-braces addition. Test coverage
|
||||||
|
exercises both success and `expect_assert_failure` failure paths for
|
||||||
|
every variant, including `assertDeprecated`/`assertIsMainThread`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## util
|
||||||
|
|
||||||
|
**Purpose:** Small stand-alone helpers with no engine-state dependencies:
|
||||||
|
`array` (dynamic array), `crypt` (hashing/checksum), `endian` (byte-order
|
||||||
|
swap), `math` (clamp/lerp/pow2/etc.), `memory` (`memoryAllocate`/`Free`/
|
||||||
|
`Zero`/`Copy`/`Compare` -- the only allocator the rest of the engine is
|
||||||
|
allowed to call directly), `random`, `ref` (refcounted handle with
|
||||||
|
lock/unlock callbacks), `sort` (bubble sort used for one-time static list
|
||||||
|
ordering), `string` (`stringCopy`/`Compare`/`Format`/etc. -- required in
|
||||||
|
place of libc `str*` functions per `CLAUDE.md`).
|
||||||
|
|
||||||
|
**Key files:** `array.c/h`, `crypt.c/h`, `endian.c/h`, `math.c/h`,
|
||||||
|
`memory.c/h`, `random.c/h`, `ref.c/h`, `sort.c/h`, `string.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Several real issues, worst was
|
||||||
|
in `ref.c`: `refUnlock` (ref.c:37-39) decremented `count` (`uint32_t`)
|
||||||
|
guarded only by `assertTrue(ref->count >= 0, ...)` -- tautologically
|
||||||
|
always true on an unsigned type, so a double-unlock silently underflowed
|
||||||
|
to `UINT32_MAX` and kept invoking `onUnlock` instead of tripping an
|
||||||
|
assert (confirmed by reading ref.c directly). **Fixed 2026-08-01** --
|
||||||
|
`refUnlock` now asserts `count > 0` before decrementing; also fixed
|
||||||
|
`refInit`'s doc comment, which claimed a fresh ref starts at count 1
|
||||||
|
when the code has always started it at 0. Same tautological unsigned
|
||||||
|
`>= 0` assert remains in `memory.c:98` (lower stakes -- `memoryFree`'s
|
||||||
|
own counter, not a shared lock/unlock primitive other subsystems build
|
||||||
|
on -- left as-is). `memory.h:11` declares
|
||||||
|
`static size_t MEMORY_POINTERS_IN_USE = 0;` directly in the header --
|
||||||
|
confirmed present -- meaning every TU including it gets its own private
|
||||||
|
copy (only "works" because the accessors all live in memory.c).
|
||||||
|
`random.c`'s `randomInt` (confirmed, random.c:15-16) does
|
||||||
|
`rand() % (max - min)` with no `max > min` check (UB on `max <= min`),
|
||||||
|
and `srand()` is never called anywhere in the repo -- unseeded,
|
||||||
|
deterministic RNG. `sort.c:1` has `#include <stdlib.h>` before the
|
||||||
|
copyright header (confirmed). Test coverage: array/math/memory/sort/
|
||||||
|
string are thorough; `ref.c`, `random.c`, `crypt.c`, `endian.c` have
|
||||||
|
**zero** tests. `randomInt`/`randomFloat` also appear unused
|
||||||
|
engine-wide (dead code, not just untested).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## event
|
||||||
|
|
||||||
|
**Purpose:** Generic pub/sub primitive -- `event_t` wraps a caller-owned
|
||||||
|
array of `eventcallback_t`/user-pointer pairs; `eventInit`/`eventSubscribe`/
|
||||||
|
`eventInvoke`. Used for things like `uifullbox_t`'s transition-end
|
||||||
|
callback and `uiloading_t`'s show/hide callbacks. Per `STATUS.md`: "Clean,
|
||||||
|
small, finished", built to replace the old input system's callback
|
||||||
|
pattern.
|
||||||
|
|
||||||
|
**Key files:** `event.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Well-formed -- correctly uses
|
||||||
|
swap-with-last for O(1) unsubscribe, asserts on capacity overflow and
|
||||||
|
duplicate-subscribe, no dead code (`eventUnsubscribe` used in 3 other
|
||||||
|
files). No `errorret_t` needed here since these are programmer-error
|
||||||
|
assertions rather than runtime-data validation, consistent with
|
||||||
|
CLAUDE.md's assert-vs-error guidance. One gap: `test/event/` doesn't
|
||||||
|
exist -- zero unit coverage, including the capacity-exceeded and
|
||||||
|
double-subscribe assert paths.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## time
|
||||||
|
|
||||||
|
**Purpose:** Frame delta/elapsed time (`TIME.delta`, exposed to JS via
|
||||||
|
`moduleTime`) plus `timeepoch_t` wall-clock timestamps (used by
|
||||||
|
`uifps.c` for the FPS counter).
|
||||||
|
|
||||||
|
**Key files:** `time.c/h`, `timeepoch.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. `time.c:52-56` unconditionally
|
||||||
|
formats an epoch string into a 256-byte stack buffer every single
|
||||||
|
`timeUpdate()` call purely to feed a commented-out `consolePrint` --
|
||||||
|
burns the leap-year/day-counting loop three times a frame for a
|
||||||
|
discarded value. `timeepoch.c`'s day-counting loops have no
|
||||||
|
handling/guard for negative epoch/timezone values (pre-1970). Test
|
||||||
|
coverage is solid for `time.c` (mocked ticks, boundary/backwards-time
|
||||||
|
cases) but `timeepoch.c`'s date math (leap year, rollover, format
|
||||||
|
specifiers) has no dedicated tests despite being the more bug-prone
|
||||||
|
half. The PSP-specific timezone unit bug flagged in the cross-cutting
|
||||||
|
findings (#4) was confirmed and fixed 2026-08-01 --
|
||||||
|
`timeGetRealTimeZonePSP` was returning hours where `timeepoch.c`
|
||||||
|
expects seconds.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## thread
|
||||||
|
|
||||||
|
**Purpose:** Thin cross-platform thread/mutex/thread-local wrappers.
|
||||||
|
Used by the asset system's background loading and the POSIX console's
|
||||||
|
input-polling thread.
|
||||||
|
|
||||||
|
**Key files:** `thread.c/h`, `threadmutex.c/h`, `threadlocal.h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Conventions followed
|
||||||
|
throughout. Real race condition, **fixed 2026-08-01**: `threadHandler`
|
||||||
|
used to unlock `stateMutex` and signal `THREAD_STATE_STOPPED` *before*
|
||||||
|
resetting `thread->threadId = 0`, but `threadStartRequest` asserts
|
||||||
|
`threadId == 0` with no synchronization against that reset --
|
||||||
|
`threadStop()` immediately followed by `threadStart()` on the same
|
||||||
|
struct could intermittently trip the assert. Telling sign it was real,
|
||||||
|
not theoretical: `test/thread/test_thread.c` already re-called
|
||||||
|
`threadInit()` before restarting specifically "so threadId/state are
|
||||||
|
reset" -- the test suite was working around the bug rather than
|
||||||
|
exercising true reuse. `threadId` is now reset inside the same
|
||||||
|
mutex-locked section, before the signal/unlock; the test now loops
|
||||||
|
stop/start 20x on the same `thread_t` with no `threadInit()` in
|
||||||
|
between. Otherwise test coverage is good (real pthreads, try-lock
|
||||||
|
coordination, a 4-thread x 10k-iteration mutex contention test).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## log
|
||||||
|
|
||||||
|
**Purpose:** `logDebug`/`logError` -- the engine's only print/debug-output
|
||||||
|
path. Header-only declarations; each platform provides the actual
|
||||||
|
implementation (see `src/dusk<platform>/log/`).
|
||||||
|
|
||||||
|
**Key files:** `log.h` (declarations only, no `.c` in core).
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Clean 2-function API; all
|
||||||
|
three platform implementations (`dusklinux`, `duskpsp`, `duskdolphin`)
|
||||||
|
match the declared signatures with correct `va_copy` usage for the
|
||||||
|
dual stdout+file writes. Dolphin's `logError` correctly falls back to
|
||||||
|
raw VIDEO/console init when the framebuffer isn't ready yet and blocks
|
||||||
|
on a START-button dismiss loop; PSP writes to
|
||||||
|
`ms0:/PSP/GAME/Dusk/*.log`. No bugs found. No `test/log/` exists --
|
||||||
|
understandable for I/O/side-effect code, but zero coverage.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## system
|
||||||
|
|
||||||
|
**Purpose:** Very early engine init (`systemInit`), the
|
||||||
|
`systemplatform_t` enum (via the `systemplatformlist.h` X-macro pattern),
|
||||||
|
and native OS dialog boxes (`systemdialogtype_t`: render-blocking vs
|
||||||
|
tick-blocking).
|
||||||
|
|
||||||
|
**Key files:** `system.c/h`, `systemplatformlist.h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. X-macro platform enum and
|
||||||
|
compile-time `#error` guards for missing platform macros used
|
||||||
|
correctly; all three platforms define the required
|
||||||
|
`systemInitPlatform`/`systemGetActiveDialogTypePlatform`/
|
||||||
|
`systemGetCyclesPlatform`. Dead code confirmed: `systemPSPGetLanguage()`
|
||||||
|
(`duskpsp/system/systempsp.c:51`) and `systemGetLanguageDolphin()`
|
||||||
|
(`duskdolphin/system/systemdolphin.c:40`) are defined but never called
|
||||||
|
anywhere -- likely intended for locale wiring that hasn't landed. No
|
||||||
|
`test/system/` exists.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## console
|
||||||
|
|
||||||
|
**Purpose:** In-engine dev console: fixed-size scrollback
|
||||||
|
(`CONSOLE_HISTORY_MAX` lines x `CONSOLE_LINE_MAX` chars), `consolePrint`,
|
||||||
|
a `dirty` flag consumers (namely `ui/debug/uiconsole.c`) watch to know
|
||||||
|
when to rebuild their own cached representation. POSIX builds also poll
|
||||||
|
stdin on a background thread for interactive script execution.
|
||||||
|
|
||||||
|
**Key files:** `console.c/h`, `consoledefs.h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Two real issues. `consolePrint`
|
||||||
|
(console.c:32-44) gets its length from `stringFormatVA(buffer,
|
||||||
|
CONSOLE_LINE_MAX, ...)`, and `stringFormatVA` (util/string.c:100)
|
||||||
|
**asserts** `ret < destSize` rather than truncating -- so any single
|
||||||
|
debug line over 511 bytes aborts the process instead of just getting
|
||||||
|
cut off, a harsh failure mode for a dev console. Separately,
|
||||||
|
`consoleUpdate`'s doc ("Processes pending queued script lines") and
|
||||||
|
`CONSOLE_EXEC_BUFFER_MAX` (consoledefs.h:12) describe a queued-script-
|
||||||
|
execution feature that doesn't exist -- `console_t` has no exec-queue
|
||||||
|
fields, `consoleUpdate` only toggles `visible`, and
|
||||||
|
`CONSOLE_EXEC_BUFFER_MAX` is unreferenced elsewhere (dead constant,
|
||||||
|
stale doc). No `test/console/` exists.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## asset
|
||||||
|
|
||||||
|
**Purpose:** The asset pipeline: `dusk.dsk` zip archive reading
|
||||||
|
(`assetfile.c/h`), lock/ref-counted entries (`asset/loader/assetentry.c/h`,
|
||||||
|
built on `util/ref.h`), batch loading (`assetbatch.c/h`), and the loader
|
||||||
|
registry (`asset/loader/assetloader.c/h`, plus one subfolder per loader
|
||||||
|
type: `dmf/` mesh+model, `display/` texture+tileset, `locale/`, `json/`,
|
||||||
|
`animation/`). See `CLAUDE.md`'s "Adding a new asset loader type" for the
|
||||||
|
extension pattern. Per `STATUS.md`: model loading's "async" path is
|
||||||
|
actually synchronous -- the one known stub in core.
|
||||||
|
|
||||||
|
**Key files:** `asset.c/h`, `assetfile.c/h`, `assetbatch.c/h`,
|
||||||
|
`loader/assetentry.c/h`, `loader/assetloader.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Core is well-structured and the
|
||||||
|
multi-pass reaper correctly handles parent/child dependency chains.
|
||||||
|
Found: `assetFileInit` (assetfile.c:29) has `if(!zip_stat(...) == 0)` --
|
||||||
|
precedence makes this `(!zip_stat(...)) == 0`, which happens to
|
||||||
|
evaluate correctly for zip's 0/nonzero convention but reads as broken
|
||||||
|
and should just be `zip_stat(...) != 0`. More seriously,
|
||||||
|
`assetEntryLock`/`Unlock` sit on top of `util/ref.c`'s confirmed
|
||||||
|
double-unlock underflow bug (see **util** above) -- an over-unlocked
|
||||||
|
asset entry silently becomes un-reapable forever instead of asserting.
|
||||||
|
**Confirmed via code-trace** (not just citing STATUS.md):
|
||||||
|
`assetModelLoaderAsync` (assetmodelloader.c:19-23) is genuinely dead --
|
||||||
|
`assetEntryStartLoading` unconditionally sets
|
||||||
|
`ASSET_ENTRY_STATE_PENDING_SYNC`, and `assetModelLoaderSync`'s state
|
||||||
|
machine never transitions to `PENDING_ASYNC` the way mesh/texture/
|
||||||
|
tileset/locale/json/animation all do, so model loading runs fully
|
||||||
|
synchronously via `assetRequireLoaded`'s busy-loop; grep confirms
|
||||||
|
`assetModelLoaderAsync` has no callers. `assetlocaleloader.c` uses raw
|
||||||
|
stdlib (`strstr`/`strncmp`/`strchr`/`strtol`/`atoi`) instead of
|
||||||
|
`util/string.h` wrappers throughout, and tests line-prefixes via
|
||||||
|
`memoryCompare(lineBuffer, "msgid", 5)` without confirming the reused
|
||||||
|
stack buffer actually holds 5 valid bytes at that point -- a short line
|
||||||
|
could spuriously prefix-match against stale buffer contents. Test
|
||||||
|
coverage: good breadth for entry lifecycle, tileset/JSON/animation
|
||||||
|
loaders, and locale parsing; no dedicated tests for mesh/model/texture
|
||||||
|
loader internals or `assetfile.c`'s line reader.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## locale
|
||||||
|
|
||||||
|
**Purpose:** Active-locale tracking (`LOCALE.locale`/`LOCALE.entry`) over
|
||||||
|
`.po`-derived locale assets loaded through the asset system. See
|
||||||
|
`assets/locale/en_US.po` -- per memory, currently placeholder/test
|
||||||
|
content, not real shipped game text.
|
||||||
|
|
||||||
|
**Key files:** `localemanager.c/h`, `localeinfo.h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Clean, no bugs found --
|
||||||
|
correctly balances `assetEntryLock`/`Unlock` in both `SetLocale` and
|
||||||
|
`Dispose` (unlocks the old entry before adopting the new one). Minor
|
||||||
|
nit: `localeinfo.h` declares `static const localeinfo_t` globals
|
||||||
|
(`LOCALE_EN_US` etc.) directly in the header, so every including TU
|
||||||
|
gets its own duplicate copy -- harmless given how few TUs include it.
|
||||||
|
No `test/locale/` directory; `test/asset/test_assetlocale.c` tests the
|
||||||
|
loader, not `localemanager.c` itself.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## save
|
||||||
|
|
||||||
|
**Purpose:** Slot-based save data (`SAVE_FILE_COUNT_MAX` fixed slots),
|
||||||
|
yyjson documents persisted with size + CRC32 checksum. `saveLoad`/
|
||||||
|
`saveSave` read/write JSON fresh every call; callers own the returned
|
||||||
|
doc and must free it. Actual file I/O goes through platform stream hooks
|
||||||
|
(`saveplatform_t`, one impl per platform) -- core `save.c` must never
|
||||||
|
touch the filesystem directly. `savesettings.c/h` layers engine settings
|
||||||
|
(display/audio/input/general) on top. Per `CLAUDE.md`: "mature, but
|
||||||
|
undocumented" beyond the one paragraph there -- no tests.
|
||||||
|
|
||||||
|
**Key files:** `save.c/h`, `savefile.h`, `savestream.c/h`,
|
||||||
|
`savesettings.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Clean and convention-compliant
|
||||||
|
-- `save.c` genuinely never touches the filesystem directly (every I/O
|
||||||
|
path goes through `saveXxxPlatform` macros, all three platforms define
|
||||||
|
them), yyjson doc ownership is honored at every call site checked, and
|
||||||
|
CRC32 is validated before parsing with every error path freeing `buf`.
|
||||||
|
One real gap: `saveFileLoad`'s `memoryAllocate(file->size)`
|
||||||
|
(savestream.c:122) allocates straight from an on-disk size field with
|
||||||
|
no sanity bound before the allocation -- a corrupted/tampered save
|
||||||
|
could request an oversized allocation, worth a max-size guard given the
|
||||||
|
"never trust incoming data" principle (arguably applies to save files,
|
||||||
|
not just network packets). Confirmed no `test/save/` exists. `saveDelete`/
|
||||||
|
`saveExists`/`saveGet` are public API not yet called anywhere in the
|
||||||
|
repo -- likely just unconsumed so far, not truly dead.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## network
|
||||||
|
|
||||||
|
**Purpose:** Connection-state layer only (`networkstate_t`:
|
||||||
|
`DISCONNECTED`/`CONNECTING`/`CONNECTED`/`DISCONNECTING`) plus a one-off
|
||||||
|
HTTP client (`network/http/`: request/header/URL/thread/process split
|
||||||
|
across files). **Not** a multiplayer/replication protocol yet -- that's
|
||||||
|
`ROADMAP.md` items 8-17. Platform-specific connection polling (PSP's
|
||||||
|
`sceNetApctl`, GameCube/Wii's `if_config()`) lives under
|
||||||
|
`src/dusk<platform>/network/`. Has HTTP tests only (`test/network/http/`).
|
||||||
|
|
||||||
|
**Key files:** `network.c/h`, `networkinfo.c/h`, `http/networkhttp.c/h`,
|
||||||
|
`http/networkhttprequest.c/h`, `http/networkhttpthread.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Genuinely stays a thin
|
||||||
|
connection-state layer (grepped for "packet"/"replicat"/"multiplayer"/
|
||||||
|
"udp" -- no hits, no scope creep). The HTTP client correctly validates
|
||||||
|
untrusted server input with `errorThrow` rather than trusting it
|
||||||
|
(malformed status lines, oversized headers, bad `Content-Length`,
|
||||||
|
early-closed connections all throw) -- exactly what CLAUDE.md calls
|
||||||
|
out. `networkhttpthread.c`'s request handoff is actually correct
|
||||||
|
despite request fields being written outside the mutex: the final
|
||||||
|
`state = PENDING` write happens under the same mutex the worker
|
||||||
|
acquires, giving a valid release/acquire handoff (worth a comment, not
|
||||||
|
a bug). One recurring convention violation:
|
||||||
|
`networkhttpprocess.c`/`networkhttpurl.c` use raw stdlib
|
||||||
|
`strlen`/`strchr`/`strstr`/`strncasecmp`/`strcspn` instead of
|
||||||
|
`util/string.h` wrappers in several places -- `util/string.h` currently
|
||||||
|
has no direct substitute for `strchr`/`strstr`/`strcspn`, so this may
|
||||||
|
be a missing-utility gap rather than pure oversight. No leaks found
|
||||||
|
(request/response bodies freed exactly once via
|
||||||
|
`networkHttpRequestReset`, redirect loop frees the intermediate body).
|
||||||
|
Real test coverage exists: `test/network/http/test_networkhttp.c` runs
|
||||||
|
six tests against a fake loopback server (GET/POST/PUT, query encoding,
|
||||||
|
redirects, connection-refused), each asserting zero leaked allocations.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## display
|
||||||
|
|
||||||
|
**Purpose:** The engine's most mature, most-optimized subsystem --
|
||||||
|
platform-agnostic rendering built on top of `duskgl`/`duskdolphin`.
|
||||||
|
Subfolders: `mesh/` (primitive builders: cube/sphere/capsule/plane/
|
||||||
|
triprism/quad, plus the shared `meshvertex_t`/`mesh_t` API), `shader/`
|
||||||
|
(currently one material type, unlit), `spritebatch/` (the shared
|
||||||
|
`SPRITEBATCH_SPRITES_MAX`-capacity quad batcher everything 2D goes
|
||||||
|
through -- flushes on shader/material change), `texture/` (texture +
|
||||||
|
tileset + palette), `text/` (`font_t`/`FONT_DEFAULT`'s baked-in bitmap
|
||||||
|
glyphs, `textBuildSpriteCache`/`textDrawSpriteCache`'s build-once/
|
||||||
|
translate-per-frame pattern), `screen/` (scan-safe area), `framebuffer/`.
|
||||||
|
`color.csv` + `tools/color/csv/__main__.py` code-generate `color.h` --
|
||||||
|
never hand-edit the generated header.
|
||||||
|
|
||||||
|
**Key files:** `display.c/h`, `mesh/mesh.c/h`, `spritebatch/spritebatch.c/h`,
|
||||||
|
`spritebatch/spritebatchsprite.c/h`, `text/font.c/h`, `text/text.c/h`,
|
||||||
|
`texture/texture.c/h`, `texture/tileset.c/h`, `shader/shader.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. "Most mature" oversold it
|
||||||
|
slightly -- real bugs found, several confirmed by direct read:
|
||||||
|
- **texture.c:42-52 (confirmed)** -- `textureInit()` branches on
|
||||||
|
`texture->format` to validate the incoming `data` union *before*
|
||||||
|
`memoryZero(texture, ...)` runs a few lines later, so it's reading
|
||||||
|
whatever stale/uninitialized value was already in the caller's
|
||||||
|
struct, not the `format` parameter actually being requested.
|
||||||
|
Validation is effectively checking garbage.
|
||||||
|
- `spritebatchsprite.c:20-25` -- `spriteBatchSpriteTilesetPosition`'s
|
||||||
|
zero-width/height early return zeroes `sprite.min`/`max` but leaves
|
||||||
|
`uvMin`/`uvMax` uninitialized (stack garbage); the existing
|
||||||
|
zero-size test doesn't check uv fields, so this isn't caught.
|
||||||
|
- `mesh.c:43` -- `meshFlush`'s offset assert (`vertexOffset <
|
||||||
|
vertCount - 1`) wrongly rejects a valid offset at the very last
|
||||||
|
vertex; off-by-one.
|
||||||
|
- `text.c:34-37` -- bounds assert uses `tileIndex <= tileCount`
|
||||||
|
(should be `<`), currently unreachable in practice since a preceding
|
||||||
|
clamp already guards it, but the assert itself is wrong.
|
||||||
|
- `framebuffer.c:23-28` -- `frameBufferBind(NULL)` recurses into
|
||||||
|
binding the backbuffer without `errorChain`, discarding any failure
|
||||||
|
and unconditionally returning `errorOk()`.
|
||||||
|
- `displayInit()`'s six static "SIMPLE" primitive meshes
|
||||||
|
(quad/cube/sphere/plane/capsule/triprism) are never disposed in
|
||||||
|
`displayDispose()` -- one VBO+VAO leaked per primitive on the
|
||||||
|
non-legacy GL path.
|
||||||
|
- **Confirmed and fixed 2026-08-01.** `tools/color.py` (not the
|
||||||
|
`tools/color/csv/__main__.py` path CLAUDE.md's doc comment names --
|
||||||
|
that's a stale path, only a `__pycache__/` remnant exists there; the
|
||||||
|
live script is `tools/color.py`) emitted invalid C float literals
|
||||||
|
for whole-number CSV channels (`0`, `1` -- every black/white/primary
|
||||||
|
color), e.g. `color3f(0f, 0f, 0f)`. Was harmless *only* because
|
||||||
|
`COLOR_*_3F`/`_4F` were never referenced anywhere in `src/`/`test/`
|
||||||
|
-- confirmed by actually running the generator before and after the
|
||||||
|
fix, not just reading the source. Now routes channel values through
|
||||||
|
Python `float()` first (always stringifies with a decimal point);
|
||||||
|
`test/display/test_color.c` gained tests referencing
|
||||||
|
`COLOR_BLACK_3F`/`COLOR_WHITE_4F`/`COLOR_RED_3B`/`COLOR_GRAY_3F`
|
||||||
|
directly so the previously-dead macros now have real compile-time +
|
||||||
|
value coverage.
|
||||||
|
- Style drift: `mesh.h` uses `//` header comments instead of `/** */`;
|
||||||
|
sphere/capsule/triprism use `/* */` block comments inside function
|
||||||
|
bodies where CLAUDE.md mandates `//`; every primitive builder's
|
||||||
|
JSDoc still documents a `@param color` that no longer exists in the
|
||||||
|
signature (leftover from before color moved out of `meshvertex_t`).
|
||||||
|
- The primitive `*Buffer()` flexible-geometry functions (sphereBuffer,
|
||||||
|
capsuleBuffer, etc.) are confirmed unused outside their own
|
||||||
|
`*Init()` -- only the fixed default mesh instances are actually
|
||||||
|
consumed (via `script/module/display/modulemesh.c`).
|
||||||
|
|
||||||
|
Test coverage: `test/display/` only registers `test_color.c` and
|
||||||
|
`test_spritebatchsprite.c` -- mesh/shader/texture/tileset/palette/text/
|
||||||
|
font/screen/framebuffer all have zero unit tests.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ui
|
||||||
|
|
||||||
|
**Purpose:** Flat, static, singleton-driven widget framework -- no scene
|
||||||
|
graph. Top level is a compile-time X-macro registry
|
||||||
|
(`uielementlist.h`/`uielement.c/h`) of `{init, update, draw, dispose,
|
||||||
|
order}` tuples (screens: frame/confirm/settings/overlays/console/fps),
|
||||||
|
spliced with `duskrpg`'s own list. Composition below that is `uimenu_t`
|
||||||
|
(`widget/uimenu.c/h`) -- a flat tagged-union array of widgets laid out in
|
||||||
|
a simple row/column grid via the `MENU_*` authoring macros; no nesting.
|
||||||
|
Widgets: `uilabel`/`uiwidgetlabel` (cached glyph sprites, the pattern
|
||||||
|
every other widget's text now uses), `uibutton`, `uicheckbox`,
|
||||||
|
`uislider`, `uidropdown`, `uitab`, `uiscrolling` (empty placeholder).
|
||||||
|
`focus/` is the gamepad/keyboard directional-navigation stack (no mouse/
|
||||||
|
pointer hit-testing exists anywhere). `frame/` is the 9-slice box plus
|
||||||
|
the confirm dialog and settings screens. `overlay/` is fullscreen
|
||||||
|
fades/loading/crop bars. `debug/` is the FPS counter and dev console
|
||||||
|
renderer.
|
||||||
|
|
||||||
|
As of 2026-07-31: slider/tab/frame (`uiFrameDrawCached`)/duskrpg's
|
||||||
|
textbox all cache their sprite geometry instead of rebuilding it every
|
||||||
|
frame; console uses a fixed-size vertex buffer instead of alloc/free.
|
||||||
|
Still open: sprite-batch flushes are keyed on material/color, so
|
||||||
|
per-widget highlight-color changes still force a flush per widget (see
|
||||||
|
`ROADMAP.md` item 5 in the debt backlog). No JS bindings exist for UI
|
||||||
|
yet. `test/ui/`/`test/display/test_spritebatchsprite.c` cover the new
|
||||||
|
caching *logic* only -- nothing exercises real `uiXxxDraw()` calls, since
|
||||||
|
those need a live GL context (`FONT_DEFAULT`/`UI_FRAME` textures) this
|
||||||
|
repo's test binaries don't have.
|
||||||
|
|
||||||
|
**Key files:** `ui.c/h`, `uielement.c/h`, `focus/uifocus.c/h`,
|
||||||
|
`widget/uimenu.c/h`, `widget/uilabel.c/h`, `frame/uiframe.c/h`,
|
||||||
|
`debug/uiconsole.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-07-31 (this session's sprite-caching
|
||||||
|
pass) -- see notes above; per-material flush granularity and hit-testing
|
||||||
|
still open.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## entity
|
||||||
|
|
||||||
|
**Purpose:** Fixed-size-array ECS. `entitymanager_t` owns
|
||||||
|
`ENTITY_COUNT_MAX` entities, each with up to `ENTITY_COMPONENT_COUNT_MAX`
|
||||||
|
components stored in a tagged union (`componentdata_t` -- flagged in
|
||||||
|
`PSP_OPTIMIZATION_PLAN.md` as the biggest PSP memory-waste candidate,
|
||||||
|
since every entity reserves space for every component type's largest
|
||||||
|
variant). `componentlist.h`'s `X()` macro auto-generates the component
|
||||||
|
enum/union/dispatch table from `entity/component/**`; engine-level
|
||||||
|
`entityprefablist.h` is an empty sentinel (real prefabs live in
|
||||||
|
`duskrpg/entity/entityprefablist.h`, resolved via
|
||||||
|
`entityPrefabResolveAndApply`). No JSON serialize/deserialize (removed by
|
||||||
|
design in favor of C-coded prefabs or JerryScript `Entity`/`Component`).
|
||||||
|
|
||||||
|
**Key files:** `entitymanager.c/h`, `entity.c/h`, `component.c/h`,
|
||||||
|
`componentlist.h`, `entityprefab.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Structurally sound (sentinel
|
||||||
|
prefab list, X-macro shape both match CLAUDE.md), but there's a real
|
||||||
|
security-relevant gap: **every capacity/bounds guard
|
||||||
|
(`entitymanager.c:35`, `entity.c:56`, `component.c:37-39,58-62,75-76,
|
||||||
|
140-141`) is an `assert*` call**, and `assert.h` compiles these to
|
||||||
|
`((void)0)` under `DUSK_ASSERTIONS_FAKED` (auto-set whenever `NDEBUG`
|
||||||
|
is defined -- confirmed by reading assert.h directly, this is a real
|
||||||
|
release-mode no-op, not a hypothetical). `moduleentity.c:30,67` create
|
||||||
|
entities/components from JerryScript with no return-value check, so a
|
||||||
|
script that exceeds `ENTITY_COUNT_MAX`/the per-entity component cap
|
||||||
|
silently gets back an invalid ID in release builds, which then indexes
|
||||||
|
fixed arrays out-of-bounds later. This directly contradicts the
|
||||||
|
project's own "untrusted-data limits need errorThrow, not asserts"
|
||||||
|
guidance -- and script input is about as untrusted as it gets. Minor:
|
||||||
|
`component.h:100`/`component.c:52` misplace the `*` in `void *
|
||||||
|
componentGetData(`. Dead code: `entityUpdateRemove`/
|
||||||
|
`entityDisposeRemove`/`entityDisposeAdd` have zero call sites.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## scene
|
||||||
|
|
||||||
|
**Purpose:** Same shape as `entity/` one level up -- `SCENE_COUNT_MAX`
|
||||||
|
fixed-count scenes, each an isolated entity-manager pool; engine-level
|
||||||
|
`sceneprefablist.h` is an empty sentinel (real prefabs in
|
||||||
|
`duskrpg/scene/`). As of the `Scene.set()` work (2026-07-31), JerryScript
|
||||||
|
can install a `{init, update, dispose}` module as the active scene via
|
||||||
|
`modulescene.c`'s `moduleSceneSetStatic`/`moduleSceneUpdateCurrent`/
|
||||||
|
`moduleSceneTeardownCurrent` (see `script` below) -- scene IDs are reused
|
||||||
|
from a small pool immediately after `sceneDestroy`, so don't assume a
|
||||||
|
freshly created scene has a "new" ID.
|
||||||
|
|
||||||
|
**Key files:** `scene.c/h`, `scenebase.h`, `sceneprefab.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Shares entity/'s assert-not-
|
||||||
|
errorThrow bounds gap (`sceneCreate` hits `assertUnreachable` then
|
||||||
|
falls through to `SCENE_ID_INVALID` on pool exhaustion in release --
|
||||||
|
reachable from `new Scene()` in JS). Additional finding:
|
||||||
|
`scenePrefabResolveAndApply`/`scenePrefabInit` (sceneprefab.c:31-54)
|
||||||
|
recurse through a prefab's `extends` chain with **no cycle guard** -- a
|
||||||
|
self-referencing or A→B→A prefab table causes unbounded recursion/
|
||||||
|
stack overflow from what's otherwise a one-typo mistake in a
|
||||||
|
hand-authored prefab list. No dead code, no use-after-free. Tests cover
|
||||||
|
create/destroy/isolation/update cadence well but have zero coverage for
|
||||||
|
pool exhaustion, `sceneRender()`, or `sceneprefab.c` (no prefab test
|
||||||
|
file exists at all).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## physics
|
||||||
|
|
||||||
|
**Purpose:** `physicsworld_t` step simulation over `physicsbodytype_t`
|
||||||
|
(static/dynamic/kinematic) and `physicshapetype_t` (cube/sphere/capsule/
|
||||||
|
plane/custom, plus mesh shapes via `physicsshapemesh.c/h`).
|
||||||
|
`triggersystem.c/h` layers trigger-volume enter/exit events on top. Per
|
||||||
|
`STATUS.md`: "mature, recently churned" -- a revert/re-disable of "old
|
||||||
|
ent code" suggests component wiring isn't fully settled yet. Well
|
||||||
|
tested (`test/physics/`).
|
||||||
|
|
||||||
|
**Key files:** `physicsworld.c/h`, `physicsbodytype.h`, `physicsshape.h`,
|
||||||
|
`physicsshapemesh.c/h`, `triggersystem.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. `STATUS.md`'s "component
|
||||||
|
wiring isn't fully settled" caveat looks stale on closer look:
|
||||||
|
`physicsWorldStep`/`triggerSystemStep` are live-wired in `scene.c:89-90`
|
||||||
|
and `duskrpg`'s player prefab actively uses both PHYSICS and TRIGGER --
|
||||||
|
no `#if 0`/TODO/commented-out code found; the disable-then-revert in
|
||||||
|
history reads like a same-day whole-ECS revert, not something
|
||||||
|
physics-specific. Two real bugs found instead:
|
||||||
|
`physicsbodytype.h:23-27` documents kinematic bodies as capable of
|
||||||
|
being a player controller, but `physicsworld.c:124,166-167` only ever
|
||||||
|
writes `onGround` for the dynamic side of a collision pair -- a
|
||||||
|
kinematic controller's `onGround` is permanently false (latent today,
|
||||||
|
since the one existing player prefab uses DYNAMIC, not KINEMATIC).
|
||||||
|
`physicstest.c:213`'s barycentric interior-test branch has no guard
|
||||||
|
against a zero-area triangle (divide-by-zero/NaN risk in mesh-sphere
|
||||||
|
collision). Dead code: `physicsShapeMeshCreate` (mesh-terrain
|
||||||
|
collision) has zero production callers despite being well-tested in
|
||||||
|
isolation; `entityPhysicsGetShape`/`GetCollideMask` are unwired to the
|
||||||
|
JS module. Test depth is genuinely strong for what's implemented
|
||||||
|
(gravity convergence, dynamic-vs-dynamic separation, mask filtering,
|
||||||
|
mesh sphere/capsule resting) -- "well tested" is earned for the
|
||||||
|
features that exist, though the unused mesh-collision path and
|
||||||
|
missing trigger→JS bridge mean the subsystem's *integration* maturity
|
||||||
|
is a bit narrower than its test depth suggests.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## animation
|
||||||
|
|
||||||
|
**Purpose:** Keyframe + easing only -- no blend trees or state machines
|
||||||
|
yet. `keyframe_t`/`keyframeset_t` interpolate values over time via
|
||||||
|
`easing.c/h`'s easing functions; `animation.c/h` ties a keyframe set to
|
||||||
|
playback state. Per `STATUS.md`: terse commit history ("ANIM") suggests
|
||||||
|
still iterating.
|
||||||
|
|
||||||
|
**Key files:** `animation.c/h`, `easing.c/h`, `keyframe.c/h`,
|
||||||
|
`keyframeset.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. All 8 core files use `//`
|
||||||
|
copyright headers instead of the required `/** */` block, inconsistent
|
||||||
|
with the correctly-formatted `entityanimation.{c,h}` next door. Math
|
||||||
|
checks out: all 16 easing functions satisfy f(0)=0/f(1)=1 with no
|
||||||
|
precision issues, and keyframe interpolation clamps (doesn't
|
||||||
|
extrapolate) outside the time range with no reachable divide-by-zero
|
||||||
|
-- though it doesn't validate that keyframe times are ascending. 15 of
|
||||||
|
16 `easing.h` declarations lack Javadoc. Biggest gap: **no
|
||||||
|
`test_easing.c` exists** -- only linear/in-quad get incidental coverage
|
||||||
|
via `test_keyframe.c`, so 13 of 16 easing functions are completely
|
||||||
|
untested. Dead code (test-only, unused by any `duskrpg` game code):
|
||||||
|
`keyframeSetGetValues`, `keyframeSetFireCallback`, `animationSetEvent`,
|
||||||
|
`entityAnimationSetKeyframes`/`GetValue`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## script
|
||||||
|
|
||||||
|
**Purpose:** Embedded JerryScript integration. `scriptmanager.c/h` owns
|
||||||
|
the JerryScript context lifecycle and the exec/call helpers
|
||||||
|
(`scriptManagerExec`/`ExecFile`/`CallGlobal`/`CallValue`, the last two
|
||||||
|
sharing exception + promise-draining logic). `scriptproto.c/h` is the
|
||||||
|
`scriptproto_t` prototype-wrapping helper every module builds on.
|
||||||
|
`module/` holds each registered JS-facing module:
|
||||||
|
- `modulebase.h` -- the shared macro toolkit (`moduleBaseFunction`,
|
||||||
|
`moduleBaseRequireArgs`/`RequireString`/etc., `moduleBaseDefineProp`/
|
||||||
|
`Func`/`StaticFunc`, `moduleBaseSetWrappedPointer`, `moduleBaseThrowError`).
|
||||||
|
- `moduleplatform.h`, `entity/moduleentity.c/h` +
|
||||||
|
`entity/component/*` (generic `Component` plus typed Position/Physics/
|
||||||
|
Renderable wrappers via `modulecomponentlist.c/h`), `scene/modulescene.c/h`
|
||||||
|
(`Scene`, including `Scene.set()`), `display/modulemesh.c/h`,
|
||||||
|
`time/moduletime.c/h`, `require/modulerequire.c/h` (CommonJS-style
|
||||||
|
`require()`/`module.exports`, with a directory stack for relative
|
||||||
|
resolution -- `scriptManagerExecFile` now pushes its own file's
|
||||||
|
directory before exec so a top-level entry script's relative
|
||||||
|
`require()` calls resolve correctly).
|
||||||
|
- `modulelist.c/h` -- registers/disposes every module above in order;
|
||||||
|
`moduleListDispose()` is now actually called from
|
||||||
|
`scriptManagerDispose()` (was a latent bug -- it wasn't, until
|
||||||
|
2026-07-31).
|
||||||
|
|
||||||
|
Entry point convention: `assets/scripts/init.js` does
|
||||||
|
`require('./scenefile.js')` + `Scene.set(module)`. Has unit tests
|
||||||
|
(`test/script/`), including one that reads the real shipped
|
||||||
|
`overworldscene.js` off disk rather than an embedded copy.
|
||||||
|
|
||||||
|
**Key files:** `scriptmanager.c/h`, `scriptproto.c/h`,
|
||||||
|
`module/modulebase.h`, `module/modulelist.c/h`,
|
||||||
|
`module/require/modulerequire.c/h`, `module/scene/modulescene.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-07-31 (this session's Scene.set() +
|
||||||
|
require()-dir-stack work) -- see notes above.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## input
|
||||||
|
|
||||||
|
**Purpose:** Bind-based input (`inputaction.c/h` maps
|
||||||
|
`INPUT_BIND_*` names to raw `inputbutton_t`s per platform), with a
|
||||||
|
configurable analog deadzone. Platform button/axis backends live under
|
||||||
|
`src/dusk<platform>/input/`; capability macros (`DUSK_INPUT_GAMEPAD`/
|
||||||
|
`KEYBOARD`/`POINTER`) gate what's available per target. Pointer axis
|
||||||
|
values are plumbed through (`DUSK_INPUT_POINTER`), but nothing in `ui/`
|
||||||
|
consumes them yet -- no hit-testing exists (see `ui` above).
|
||||||
|
|
||||||
|
**Key files:** `input.c/h`, `inputaction.c/h`, `inputbutton.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Clean and convention-compliant;
|
||||||
|
deadzone math (`inputDeadzone`, input.c:244) is correct and safe. One
|
||||||
|
naming nit: `inputBind`'s param is named `act` in input.h:216 while its
|
||||||
|
own doc comment calls it `action`. **Confirmed, not just cited from
|
||||||
|
STATUS.md**: pointer input is genuinely wired end-to-end, not a
|
||||||
|
dead-end at the platform layer -- SDL2's `inputUpdateSDL2` populates
|
||||||
|
`INPUT.platform.mouseX/Y`/scroll from `SDL_GetMouseState`,
|
||||||
|
`inputButtonGetValueSDL2` handles the pointer-axis cases, and
|
||||||
|
`duskrpg/input/inputbindmap.h` binds `mouse_x`/`mouse_y` to
|
||||||
|
`INPUT_BIND_POINTERX/Y`. The dead end is specifically at the
|
||||||
|
*consumption* layer: grepping `src/dusk/ui/` for those binds or any
|
||||||
|
pointer-axis read turns up nothing -- exactly as STATUS.md says, just
|
||||||
|
now confirmed rather than assumed. No tests exist for `input/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## engine
|
||||||
|
|
||||||
|
**Purpose:** Top-level init/update/dispose orchestration
|
||||||
|
(`engineInit`/`engineUpdate`/`engineDispose`) -- the thing `main.c` calls,
|
||||||
|
which in turn calls into every subsystem above plus `game/gameInit` etc.
|
||||||
|
`ENGINE.running`/`ENGINE.version` are the only bits of global state
|
||||||
|
outside the per-subsystem structs.
|
||||||
|
|
||||||
|
**Key files:** `engine.c/h`.
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01, confirmed by direct read of
|
||||||
|
`engineInit`/`engineDispose`. Init order is safe (time -> console ->
|
||||||
|
system -> input -> asset -> scriptManager -> save/saveSettings ->
|
||||||
|
locale -> display -> ui -> network -> scene -> game), with display
|
||||||
|
before UI and scriptManager before scene/game so JS `Entity`/`Scene`
|
||||||
|
wrappers exist before any script runs. `engineDispose` is **not** a
|
||||||
|
clean reverse of that order, though: `localeManagerDispose()` runs
|
||||||
|
*before* `uiDispose()`/`displayDispose()`, even though locale was
|
||||||
|
initialized *before* both -- correct reverse order would tear down
|
||||||
|
UI/display first, and as written there's a real risk of UI/display
|
||||||
|
teardown code touching already-freed locale data (e.g. any localized
|
||||||
|
string still held/logged during dispose). Separately, `void
|
||||||
|
engineExit(void)` (engine.c:95) is defined but **not declared in
|
||||||
|
engine.h**, and a repo-wide grep finds no caller anywhere -- dead,
|
||||||
|
unreachable, and in violation of the "every public function must be
|
||||||
|
declared in its header" rule. No tests exist for `engine/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## game
|
||||||
|
|
||||||
|
**Purpose:** Intentionally header-only in core -- just declares
|
||||||
|
`gameInit`/`gameUpdate`/`gameDispose`. The real implementation is
|
||||||
|
`src/duskrpg/game/game.c` (currently: runs `scripts/init.js` on init).
|
||||||
|
|
||||||
|
**Key files:** `game.h` (no `.c` in core).
|
||||||
|
|
||||||
|
**Review status:** Reviewed 2026-08-01. Confirmed: no `.c` file exists
|
||||||
|
in `src/dusk/game/` (only `game.h` + `CMakeLists.txt`) -- a pure
|
||||||
|
interface, as intended. The real `src/duskrpg/game/game.c`
|
||||||
|
implementation is a thin JS-bootstrap shim: `gameInit` just does
|
||||||
|
`errorChain(scriptManagerExecFile("scripts/init.js", NULL))`, while
|
||||||
|
`gameUpdate`/`gameDispose` are both empty (`errorOk()` only). Not a
|
||||||
|
bug -- consistent with the ongoing migration of game logic into JS --
|
||||||
|
but worth flagging as "not yet fleshed out" rather than broken if
|
||||||
|
anything is expected to happen there per-frame at the C layer. No
|
||||||
|
tests exist for this layer.
|
||||||
@@ -33,3 +33,74 @@ jobs:
|
|||||||
libssl-dev
|
libssl-dev
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: ./scripts/test-linux.sh
|
run: ./scripts/test-linux.sh
|
||||||
|
|
||||||
|
# Emulator smoke tests: boot the built disc/EBOOT for a fixed window and
|
||||||
|
# confirm the emulator doesn't crash. Not yet verified against a real
|
||||||
|
# runner (no CI run has exercised these) -- continue-on-error so a
|
||||||
|
# flaky/broken emulator step doesn't block the required Linux test job.
|
||||||
|
run-tests-gamecube-dolphin:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
continue-on-error: true
|
||||||
|
container:
|
||||||
|
image: ghcr.io/extremscorner/libogc2:latest
|
||||||
|
steps:
|
||||||
|
- name: Install Node.js
|
||||||
|
run: apt-get update && apt-get install -y nodejs
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Install additional dependencies
|
||||||
|
run: |
|
||||||
|
apt-get install -y \
|
||||||
|
python3-pip python3-polib python3-pil \
|
||||||
|
python3-dotenv python3-pyqt5 python3-opengl xorriso \
|
||||||
|
dolphin-emu xvfb
|
||||||
|
dkp-pacman -Syu --noconfirm
|
||||||
|
dkp-pacman -S --needed --noconfirm \
|
||||||
|
gamecube-sdl2 ppc-liblzma ppc-libzip \
|
||||||
|
gamecube-tools ppc-libmad ppc-zlib-ng ppc-bzip2 ppc-zstd
|
||||||
|
- name: Build GameCube ISO and boot it in Dolphin
|
||||||
|
run: ./scripts/test-gamecube-dolphin.sh
|
||||||
|
|
||||||
|
run-tests-wii-dolphin:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
continue-on-error: true
|
||||||
|
container:
|
||||||
|
image: ghcr.io/extremscorner/libogc2:latest
|
||||||
|
steps:
|
||||||
|
- name: Install Node.js
|
||||||
|
run: apt-get update && apt-get install -y nodejs
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Install additional dependencies
|
||||||
|
run: |
|
||||||
|
apt-get install -y \
|
||||||
|
python3-pip python3-polib python3-pil \
|
||||||
|
python3-dotenv python3-pyqt5 python3-opengl xorriso \
|
||||||
|
dolphin-emu xvfb
|
||||||
|
dkp-pacman -Syu --noconfirm
|
||||||
|
dkp-pacman -S --needed --noconfirm \
|
||||||
|
gamecube-sdl2 ppc-liblzma ppc-libzip \
|
||||||
|
gamecube-tools ppc-libmad ppc-zlib-ng ppc-bzip2 ppc-zstd
|
||||||
|
- name: Build Wii ISO and boot it in Dolphin
|
||||||
|
run: ./scripts/test-wii-dolphin.sh
|
||||||
|
|
||||||
|
run-tests-psp-ppsspp:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
continue-on-error: true
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Setup pspdev
|
||||||
|
uses: ./.github/actions/setup-pspdev
|
||||||
|
- name: Install PPSSPPHeadless build dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y git cmake ninja-build libsdl2-dev zlib1g-dev
|
||||||
|
- name: Build PPSSPPHeadless
|
||||||
|
run: |
|
||||||
|
git clone --recursive --depth 1 https://github.com/hrydgard/ppsspp.git /tmp/ppsspp
|
||||||
|
cmake -S /tmp/ppsspp -B /tmp/ppsspp/build -DCMAKE_BUILD_TYPE=Release
|
||||||
|
cmake --build /tmp/ppsspp/build --target PPSSPPHeadless -- -j$(nproc)
|
||||||
|
echo "PPSSPP_HEADLESS_BIN=/tmp/ppsspp/build/PPSSPPHeadless" >> "$GITHUB_ENV"
|
||||||
|
- name: Build PSP EBOOT and boot it in PPSSPPHeadless
|
||||||
|
run: ./scripts/test-psp-ppsspp.sh
|
||||||
@@ -107,4 +107,3 @@ yarn.lock
|
|||||||
/assets/test
|
/assets/test
|
||||||
/tools_old
|
/tools_old
|
||||||
/assets/test.png
|
/assets/test.png
|
||||||
/assets/audio/boa.mp3
|
|
||||||
@@ -0,0 +1,549 @@
|
|||||||
|
# Dusk — Claude Code rules
|
||||||
|
|
||||||
|
See `STATUS.md` for a periodically-refreshed inventory of subsystem
|
||||||
|
maturity, test coverage gaps, and known open issues — check it before
|
||||||
|
assuming a subsystem is fully wired up or before picking a next task.
|
||||||
|
|
||||||
|
## File headers
|
||||||
|
Every C, H, and JS file starts with:
|
||||||
|
|
||||||
|
```c
|
||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
```
|
||||||
|
|
||||||
|
JS files use `//` comment style instead.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
### Memory
|
||||||
|
Use the project allocator — never raw `malloc`/`free`:
|
||||||
|
|
||||||
|
```c
|
||||||
|
memoryAllocate(size) // allocate
|
||||||
|
memoryFree(ptr) // free
|
||||||
|
memoryZero(dest, size) // zero a block
|
||||||
|
memoryCopy(dest, src, size) // copy
|
||||||
|
```
|
||||||
|
|
||||||
|
### Asserts
|
||||||
|
Prefer specific assert macros over bare `assert()`:
|
||||||
|
|
||||||
|
```c
|
||||||
|
assertNotNull(ptr, "msg");
|
||||||
|
assertTrue(cond, "msg");
|
||||||
|
assertFalse(cond, "msg");
|
||||||
|
assertUnreachable("msg");
|
||||||
|
assertIsMainThread("msg");
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Build system
|
||||||
|
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 |
|
||||||
|
| `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)
|
||||||
|
src/dusksdl2/ SDL2 window + input (Linux, Knulli, PSP)
|
||||||
|
src/dusklinux/ Linux + Knulli platform impl
|
||||||
|
src/duskpsp/ PSP 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()`, `entityMyCompRender()`.
|
||||||
|
2. Add the include to `src/dusk/entity/componentlist.h` header block
|
||||||
|
(or `src/duskrpg/entity/gamecomponentlist.h` for a game-specific
|
||||||
|
component, appended after the engine's inbuilt ones).
|
||||||
|
3. Add a row:
|
||||||
|
```c
|
||||||
|
X(MYCOMP, entityMyComp_t, myComp, entityMyCompInit, NULL, NULL)
|
||||||
|
```
|
||||||
|
Params are `(enumName, type, field, init, dispose, render)` — pass
|
||||||
|
`NULL` for any callback the component doesn't need. This
|
||||||
|
auto-generates the enum, union field, and definition entry.
|
||||||
|
4. If JS-facing, create the script module and `.d.ts` (see below).
|
||||||
|
|
||||||
|
Entities/components/scenes have no JSON serialize/deserialize path —
|
||||||
|
that was removed in favor of building scenes from C-coded prefabs
|
||||||
|
(below) or from JerryScript (`Entity`/`Component`/`Scene`, see
|
||||||
|
"Adding a new script (JS) module").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding a new entity/scene prefab
|
||||||
|
Entity prefabs (`src/dusk/entity/entityprefab.h`) and scene prefabs
|
||||||
|
(`src/dusk/scene/sceneprefab.h`) follow the same pattern:
|
||||||
|
1. Write an apply function: `errorret_t entityPrefabXxxApply(mgr,
|
||||||
|
entityId)` (or `errorret_t scenePrefabXxxApply(sceneId)`), building
|
||||||
|
up the entity/scene with the normal component/entity APIs.
|
||||||
|
2. Add an entry to the sentinel-terminated `ENTITY_PREFABS[]` (in
|
||||||
|
`src/dusk/entity/entityprefablist.h`, or a game-specific list it
|
||||||
|
includes) or `SCENE_PREFABS[]`:
|
||||||
|
```c
|
||||||
|
{ .name = "MY_PREFAB", .extends = "", .apply = entityPrefabXxxApply }
|
||||||
|
```
|
||||||
|
`extends` names another prefab to apply first (recurses through
|
||||||
|
`entityPrefabResolveAndApply`/`scenePrefabResolveAndApply`), or `""`
|
||||||
|
for none. Do not add an enum or count field — the array is iterated
|
||||||
|
until `.name[0] == '\0'`.
|
||||||
|
3. `entityPrefabResolveAndApply`/`scenePrefabResolveAndApply` only
|
||||||
|
resolve names against the C-coded registry above — there is no JSON
|
||||||
|
asset fallback. Throws if no prefab with that name is registered.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding a new cutscene item type
|
||||||
|
1. Create `src/duskrpg/cutscene/item/<category>/cutsceneMyItem.h/.c`
|
||||||
|
with a data struct (e.g. `cutscenemyitem_t`) and
|
||||||
|
`cutsceneMyItemStart(item, data)` / `cutsceneMyItemUpdate(item,
|
||||||
|
data)` (the latter returns `true` once the item has completed). Add
|
||||||
|
a matching `cutscenemyitemdata_t` runtime-data struct only if the
|
||||||
|
item needs per-run state across ticks (most don't).
|
||||||
|
2. Add `CUTSCENE_ITEM_TYPE_MY_ITEM` to the enum and a union member to
|
||||||
|
`cutsceneitem_t` (and `cutsceneitemdata_t` if it has runtime data) in
|
||||||
|
`src/duskrpg/cutscene/item/cutsceneitem.h`.
|
||||||
|
3. Register the `{ start, update }` pair in `CUTSCENE_ITEM_CALLBACKS[]`
|
||||||
|
in `cutsceneitem.c`.
|
||||||
|
4. Add an authoring macro to `src/duskrpg/cutscene/cutscene.h`:
|
||||||
|
```c
|
||||||
|
#define CUTSCENE_MY_ITEM(ARGS...) \
|
||||||
|
{ .type = CUTSCENE_ITEM_TYPE_MY_ITEM, .myItem = { ARGS } }
|
||||||
|
```
|
||||||
|
used inside a `CUTSCENE(NAME, SIZE, PAUSE_TYPE, ...)` block.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Save system
|
||||||
|
Save data lives under `src/dusk/save/` (`save.h`/`savefile.h`/
|
||||||
|
`saveplatform.h`). Slots are fixed-count (`SAVE_FILE_COUNT_MAX`), each
|
||||||
|
holding a yyjson document persisted with its byte size and a CRC32
|
||||||
|
checksum. `saveLoad`/`saveSave` read/write the JSON fresh every call —
|
||||||
|
callers own the returned/passed `yyjson_doc`/`yyjson_mut_doc` and must
|
||||||
|
free it themselves. Actual file I/O goes through platform-specific
|
||||||
|
`saveplatform_t`/stream hooks (one implementation per platform under
|
||||||
|
`src/dusk<platform>/save/`) — do not add direct filesystem calls to the
|
||||||
|
core `save.c`, extend the platform stream hooks instead.
|
||||||
|
|
||||||
|
## Network system
|
||||||
|
`src/dusk/network/` (`network.h`) is a connection-state layer only — a
|
||||||
|
`networkstate_t` state machine (`DISCONNECTED`/`CONNECTING`/`CONNECTED`/
|
||||||
|
`DISCONNECTING`) plus an HTTP client (`network/http/`) used for one-off
|
||||||
|
requests. It is not a multiplayer/replication protocol — that layer
|
||||||
|
doesn't exist yet (see `ROADMAP.md` items on the socket server/client
|
||||||
|
and packet handlers). Platform-specific connection logic (e.g. PSP's
|
||||||
|
`sceNetApctl` polling, GameCube/Wii's `if_config()`) lives under
|
||||||
|
`src/dusk<platform>/network/`, wired through `networkplatform.h` macros
|
||||||
|
the same way display/input are. Whenever this eventually grows a
|
||||||
|
multiplayer protocol, apply `ROADMAP.md`'s principle: never trust
|
||||||
|
incoming packet data — validate defensively with `errorret_t`/
|
||||||
|
`errorThrow()`, not asserts.
|
||||||
|
|
||||||
|
## Adding a new script (JS) module
|
||||||
|
Dusk embeds JerryScript (`src/dusk/script/`, fetched via
|
||||||
|
`cmake/modules/Findjerryscript.cmake`). Today only `Entity`, the
|
||||||
|
generic `Component` wrapper, and `Scene` are registered (see
|
||||||
|
`src/dusk/script/module/modulelist.c`) — no per-component-type typed
|
||||||
|
wrappers exist yet (e.g. no `.position` on a `POSITION` component);
|
||||||
|
`entity.add(TYPE)`/`entity.getComponent(TYPE)` always return the
|
||||||
|
generic `Component`.
|
||||||
|
|
||||||
|
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 —
|
||||||
|
these are the one exception to "no `static` in `.c` files": the
|
||||||
|
macro itself expands to a `static jerry_value_t name(...)`
|
||||||
|
JerryScript external-handler trampoline, never called by name
|
||||||
|
from other C files, so it isn't declared in the `.h`.
|
||||||
|
- 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 a component module that adds a *typed* wrapper for a specific
|
||||||
|
component type, create
|
||||||
|
`src/dusk/script/module/entity/component/modulecomponentlist.c` (it
|
||||||
|
doesn't exist yet — the first such module creates it) so
|
||||||
|
`entity.add()` can return the typed wrapper instead of the generic
|
||||||
|
`Component`.
|
||||||
|
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
|
||||||
|
|
||||||
|
### ASCII only
|
||||||
|
Source files (`.c`, `.h`, `.js`) must contain only ASCII characters (U+0000–U+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.
|
||||||
|
|
||||||
|
### Indentation
|
||||||
|
2 spaces. No tabs.
|
||||||
|
|
||||||
|
### Keyword and operator spacing
|
||||||
|
No space between a keyword or function name and its opening parenthesis:
|
||||||
|
|
||||||
|
```c
|
||||||
|
if(!ptr) return;
|
||||||
|
for(uint8_t i = 0; i < count; i++) {
|
||||||
|
while(entry->state != DONE) {
|
||||||
|
switch(type) {
|
||||||
|
sizeof(assetbatch_t)
|
||||||
|
memoryZero(ptr, size)
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Color system
|
||||||
|
|
||||||
|
Colors are defined in `src/dusk/display/color.csv` and code-generated
|
||||||
|
into a `color.h` header by `tools/color/csv/__main__.py`.
|
||||||
|
|
||||||
|
Each row in the CSV has `name,r,g,b,a` with channel values in `[0.0, 1.0]`.
|
||||||
|
The script emits four `#define` variants per color plus a bare alias:
|
||||||
|
|
||||||
|
```
|
||||||
|
COLOR_<NAME>_4B color4b(r8, g8, b8, a8) // default alias target
|
||||||
|
COLOR_<NAME>_3B color3b(r8, g8, b8)
|
||||||
|
COLOR_<NAME>_3F color3f(rf, gf, bf)
|
||||||
|
COLOR_<NAME>_4F color4f(rf, gf, bf, af)
|
||||||
|
COLOR_<NAME> COLOR_<NAME>_4B
|
||||||
|
```
|
||||||
|
|
||||||
|
`color_t` is `color4b_t` (four `uint8_t` channels).
|
||||||
|
|
||||||
|
To add a new color, append a row to `color.csv` and rebuild — do not
|
||||||
|
hand-edit the generated header.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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`.
|
||||||
+15
-40
@@ -8,22 +8,16 @@ cmake_minimum_required(VERSION 3.13)
|
|||||||
|
|
||||||
set(CMAKE_C_STANDARD 11)
|
set(CMAKE_C_STANDARD 11)
|
||||||
set(CMAKE_C_STANDARD_REQUIRED ON)
|
set(CMAKE_C_STANDARD_REQUIRED ON)
|
||||||
set(CMAKE_MODULE_PATH
|
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
|
||||||
${CMAKE_MODULE_PATH}
|
|
||||||
${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules
|
|
||||||
)
|
|
||||||
cmake_policy(SET CMP0079 NEW)
|
cmake_policy(SET CMP0079 NEW)
|
||||||
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
|
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
|
||||||
|
|
||||||
option(DUSK_BUILD_TESTS "Enable tests" OFF)
|
option(DUSK_BUILD_TESTS "Enable tests" OFF)
|
||||||
option(DUSK_NETWORK "Enable network support" ON)
|
|
||||||
|
|
||||||
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
|
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
|
||||||
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
|
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
|
||||||
set(DUSK_GAME_SHORT_DESCRIPTION "Dusk game" CACHE STRING "One-line description")
|
set(DUSK_GAME_SHORT_DESCRIPTION "Dusk game" CACHE STRING "One-line description")
|
||||||
set(DUSK_GAME_LONG_DESCRIPTION
|
set(DUSK_GAME_LONG_DESCRIPTION "No description yet." CACHE STRING "Full description")
|
||||||
"No description yet." CACHE STRING "Full description"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Prep cache
|
# Prep cache
|
||||||
set(DUSK_CACHE_TARGET "dusk-target")
|
set(DUSK_CACHE_TARGET "dusk-target")
|
||||||
@@ -37,19 +31,13 @@ set(DUSK_TEMP_DIR "${DUSK_BUILD_DIR}/temp")
|
|||||||
set(DUSK_TOOLS_DIR "${DUSK_ROOT_DIR}/tools")
|
set(DUSK_TOOLS_DIR "${DUSK_ROOT_DIR}/tools")
|
||||||
set(DUSK_DATA_DIR "${DUSK_ROOT_DIR}/data")
|
set(DUSK_DATA_DIR "${DUSK_ROOT_DIR}/data")
|
||||||
set(DUSK_ASSETS_DIR "${DUSK_ROOT_DIR}/assets")
|
set(DUSK_ASSETS_DIR "${DUSK_ROOT_DIR}/assets")
|
||||||
set(DUSK_BUILT_ASSETS_DIR "${DUSK_BUILD_DIR}/built_assets"
|
set(DUSK_BUILT_ASSETS_DIR "${DUSK_BUILD_DIR}/built_assets" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
|
||||||
)
|
|
||||||
set(DUSK_GENERATED_HEADERS_DIR "${DUSK_BUILD_DIR}/generated")
|
set(DUSK_GENERATED_HEADERS_DIR "${DUSK_BUILD_DIR}/generated")
|
||||||
set(DUSK_BUILD_BINARY ${DUSK_BUILD_DIR}/Dusk
|
set(DUSK_BUILD_BINARY ${DUSK_BUILD_DIR}/Dusk CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
|
||||||
)
|
|
||||||
set(DUSK_ASSETS "" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_ASSETS "" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
set(DUSK_LIBRARY_TARGET_NAME "DuskCore" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_LIBRARY_TARGET_NAME "DuskCore" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
set(DUSK_BINARY_TARGET_NAME "Dusk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_BINARY_TARGET_NAME "Dusk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
set(DUSK_ASSETS_ZIP "${DUSK_BUILD_DIR}/dusk.dsk"
|
set(DUSK_ASSETS_ZIP "${DUSK_BUILD_DIR}/dusk.dsk" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
|
||||||
)
|
|
||||||
|
|
||||||
if(NOT DEFINED DUSK_TARGET_SYSTEM)
|
if(NOT DEFINED DUSK_TARGET_SYSTEM)
|
||||||
set(DUSK_TARGET_SYSTEM "linux")
|
set(DUSK_TARGET_SYSTEM "linux")
|
||||||
@@ -84,9 +72,7 @@ if(DUSK_BUILD_TESTS)
|
|||||||
${DUSK_LIBRARY_TARGET_NAME}
|
${DUSK_LIBRARY_TARGET_NAME}
|
||||||
)
|
)
|
||||||
else()
|
else()
|
||||||
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}"
|
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
CACHE INTERNAL ${DUSK_CACHE_TARGET}
|
|
||||||
)
|
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(NOT DEFINED DUSK_VERSION)
|
if(NOT DEFINED DUSK_VERSION)
|
||||||
@@ -104,12 +90,6 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
|
|||||||
DUSK_VERSION="${DUSK_VERSION}"
|
DUSK_VERSION="${DUSK_VERSION}"
|
||||||
)
|
)
|
||||||
|
|
||||||
if(DUSK_NETWORK)
|
|
||||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|
||||||
DUSK_NETWORK
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# Toolchains
|
# Toolchains
|
||||||
include(cmake/targets/${DUSK_TARGET_SYSTEM}.cmake)
|
include(cmake/targets/${DUSK_TARGET_SYSTEM}.cmake)
|
||||||
|
|
||||||
@@ -135,21 +115,16 @@ if(DUSK_BUILD_TESTS)
|
|||||||
add_subdirectory(test)
|
add_subdirectory(test)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# Build assets. Runs unconditionally on every build (rather than being
|
# Build assets
|
||||||
# gated behind a custom_command's file-level DEPENDS list) because
|
file(GLOB_RECURSE DUSK_ASSET_FILES CONFIGURE_DEPENDS "${DUSK_ASSETS_DIR}/*")
|
||||||
# CONFIGURE_DEPENDS globs only pick up added/removed files on the next
|
add_custom_command(
|
||||||
# CMake configure, so that approach could miss/lag a rebuild behind an
|
OUTPUT "${DUSK_ASSETS_ZIP}"
|
||||||
# asset edit. tools.asset.pack itself decides whether anything actually
|
|
||||||
# changed (see its manifest check) and no-ops quickly when nothing did,
|
|
||||||
# so this stays cheap on a build where assets are untouched.
|
|
||||||
add_custom_target(DUSK_ASSETS_BUILT ALL
|
|
||||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_ASSETS_DIR}"
|
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_ASSETS_DIR}"
|
||||||
COMMAND ${Python3_EXECUTABLE} -m tools.asset.pack
|
COMMAND ${CMAKE_COMMAND} -E rm -f "${DUSK_ASSETS_ZIP}"
|
||||||
--input "${DUSK_ASSETS_DIR}"
|
COMMAND ${CMAKE_COMMAND} -E tar "cf" "${DUSK_ASSETS_ZIP}" --format=zip -- .
|
||||||
--output "${DUSK_ASSETS_ZIP}"
|
WORKING_DIRECTORY "${DUSK_ASSETS_DIR}"
|
||||||
WORKING_DIRECTORY "${DUSK_ROOT_DIR}"
|
DEPENDS ${DUSK_ASSET_FILES}
|
||||||
BYPRODUCTS "${DUSK_ASSETS_ZIP}"
|
|
||||||
COMMENT "Packing assets into dusk.dsk"
|
|
||||||
VERBATIM
|
VERBATIM
|
||||||
)
|
)
|
||||||
|
add_custom_target(DUSK_ASSETS_BUILT DEPENDS "${DUSK_ASSETS_ZIP}")
|
||||||
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} DUSK_ASSETS_BUILT)
|
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} DUSK_ASSETS_BUILT)
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
# PSP Optimization Plan
|
||||||
|
|
||||||
|
A survey of concrete memory and CPU (especially floating-point) optimization
|
||||||
|
opportunities for the PSP target, done 2026-07-31 on branch `ac2` at commit
|
||||||
|
`e61914ba` + this session's scripting work. Point-in-time findings, not a
|
||||||
|
substitute for reading the referenced source before acting on it.
|
||||||
|
|
||||||
|
## Why this exists
|
||||||
|
|
||||||
|
The PSP (Allegrex MIPS CPU, 222-333MHz, single core, 32-64MB main RAM, 2MB
|
||||||
|
eDRAM, 16KB I-cache / 16KB D-cache, no virtual memory or memory protection)
|
||||||
|
is the tightest-constrained target this engine ships to. Two rules guide
|
||||||
|
everything below, both already correctly applied in one place in this
|
||||||
|
codebase (`entityposition_t` caching its transform matrices instead of
|
||||||
|
recomputing them from position/rotation/scale every read — see "Already
|
||||||
|
correct" below):
|
||||||
|
|
||||||
|
- **Memory is finite and cannot be compacted.** No VM means a fragmented
|
||||||
|
heap after a few minutes of play can fail an allocation even with
|
||||||
|
"enough" total free bytes. Prefer static/pool allocation over
|
||||||
|
malloc/free churn; prefer trading memory for CPU only when the memory
|
||||||
|
cost is bounded and paid once.
|
||||||
|
- **CPU is finite and floating-point math is not free**, especially
|
||||||
|
trig/sqrt on the plain scalar FPU. Prefer caching a computed result
|
||||||
|
behind a dirty flag over recomputing it unconditionally; prefer
|
||||||
|
avoiding a sqrt via squared-distance comparison wherever only a
|
||||||
|
yes/no or ordering result is needed.
|
||||||
|
|
||||||
|
## Priority 1 — Entity/component memory: a union tax paid on every slot, times 4 scenes
|
||||||
|
|
||||||
|
**The single biggest finding.** `entitymanager_t` (`src/dusk/entity/entitymanager.h:11-15`)
|
||||||
|
is a flat, statically-sized struct:
|
||||||
|
|
||||||
|
```c
|
||||||
|
typedef struct entitymanager_t {
|
||||||
|
entity_t entities[ENTITY_COUNT_MAX]; // 64
|
||||||
|
component_t components[ENTITY_COUNT_MAX * ENTITY_COMPONENT_COUNT_MAX]; // 64*16 = 1024
|
||||||
|
componentid_t entitiesWithComponent[COMPONENT_TYPE_COUNT * ENTITY_COUNT_MAX];
|
||||||
|
} entitymanager_t;
|
||||||
|
```
|
||||||
|
|
||||||
|
`component_t` (`src/dusk/entity/component.h:69-72`) holds a **tagged union**
|
||||||
|
(`componentdata_t`) sized to its largest variant. That variant is
|
||||||
|
`entityrenderable_t`'s spritebatch payload (`entityrenderable.h:25-66`):
|
||||||
|
`spritebatchsprite_t sprites[64]` at 40 bytes each (`vec3 min + vec3 max +
|
||||||
|
vec2 uvMin + vec2 uvMax`) = **2560 bytes**, versus ~28-300 bytes for every
|
||||||
|
other component type (camera, physics, animation, position, trigger).
|
||||||
|
|
||||||
|
Because the union is embedded by value in a flat array — not behind a
|
||||||
|
pointer, not sparse — **every one of the 1024 component slots in every
|
||||||
|
entity manager costs ~2580 bytes, whether it holds a 28-byte camera or
|
||||||
|
nothing at all.** `1024 * 2580 ≈ 2.52MB` per `entitymanager_t`, confirmed
|
||||||
|
by the engine's own startup log every run: `Entity manager size: 2684992
|
||||||
|
bytes (2622.06 KB)`.
|
||||||
|
|
||||||
|
`scene_t` (`src/dusk/scene/scene.h:14-18`) embeds `entitymanager_t` by
|
||||||
|
value too, and `SCENE_COUNT_MAX = 4` (`scene/scenebase.h:11`) with
|
||||||
|
`SCENE_MANAGER` declared as a plain global (`scene/scene.c:20`) — so this
|
||||||
|
~2.52MB exists as static BSS from process start for **all 4 scene slots**,
|
||||||
|
used or not. **Total: ~10.1MB reserved permanently for entity storage
|
||||||
|
alone** — 16-31% of PSP main RAM — before a single texture, mesh, or audio
|
||||||
|
asset is loaded.
|
||||||
|
|
||||||
|
**Options to fix (roughly increasing effort/risk):**
|
||||||
|
1. Pull `entityrenderablespritebatch_t` out of the component union entirely
|
||||||
|
— store spritebatch entities via a pointer/handle into a separate,
|
||||||
|
smaller fixed pool sized to how many spritebatch-renderable entities
|
||||||
|
actually coexist (almost certainly far fewer than 64 per entity, and
|
||||||
|
far fewer entities need spritebatch at all vs. mesh/material
|
||||||
|
rendering). This alone would shrink the union's dominant variant from
|
||||||
|
~2560 bytes to whatever the next-largest variant is (~300 bytes,
|
||||||
|
`entitytrigger_t`) — an ~88% reduction, dropping the ~10.1MB down to
|
||||||
|
roughly ~1.2MB.
|
||||||
|
2. Reduce `SCENE_COUNT_MAX` from 4 if 4 concurrent scenes were never a
|
||||||
|
deliberate requirement (check with the project owner — this may just
|
||||||
|
be a round-number default nobody revisited), or make scene storage
|
||||||
|
pointer-based/lazily allocated so unused scene slots cost ~0 instead
|
||||||
|
of a full `entitymanager_t`.
|
||||||
|
3. Reduce `ENTITY_COMPONENT_COUNT_MAX` (16) if entities realistically use
|
||||||
|
far fewer distinct component types simultaneously — check actual
|
||||||
|
usage across `entityprefablist.h`/`gameprefablist.h` prefabs.
|
||||||
|
|
||||||
|
Do (1) first — it's the highest-leverage, most contained change (touches
|
||||||
|
`entityrenderable.h`'s data layout and its render/dispose paths, not the
|
||||||
|
general entity/component system), and re-measure via the same startup
|
||||||
|
log line before deciding whether (2)/(3) are still worth doing.
|
||||||
|
|
||||||
|
## Priority 2 — VFPU is completely unused; all vec/mat math is scalar
|
||||||
|
|
||||||
|
The PSP's Allegrex CPU has a **VFPU** (vector floating-point unit) capable
|
||||||
|
of fast SIMD-style 4-wide float ops and hardware-accelerated matrix
|
||||||
|
operations, exposed by pspsdk's `pspvfpu`/GU "Geometry Utility" (`gum_*`)
|
||||||
|
helpers. This engine links `pspvfpu` (`cmake/targets/psp.cmake`) but
|
||||||
|
**never calls into it** — confirmed via a zero-hit grep for
|
||||||
|
`vfpu|pspmath|gum_|vcst|gu_matrix` across `src/duskpsp/` and `src/duskgl/`.
|
||||||
|
|
||||||
|
All vector/matrix math instead goes through cglm (`glm_vec3_*`,
|
||||||
|
`glm_mat4_*`), which auto-detects SIMD only for x86 (`CGLM_SSE2`/`AVX`) or
|
||||||
|
ARM (`CGLM_NEON`) — neither applies to MIPS, and no `CGLM_*` macros are
|
||||||
|
set anywhere in this repo (confirmed zero hits). **Every `glm_mat4_mul`,
|
||||||
|
every position/rotation rebuild, every physics vector op runs on the
|
||||||
|
plain scalar MIPS FPU with the VFPU sitting idle.**
|
||||||
|
|
||||||
|
This is the single largest *available* CPU win identified in this survey
|
||||||
|
— larger than any specific hot-path fix below, because it's a multiplier
|
||||||
|
on all of them. Concretely: route `entityposition.c`'s matrix
|
||||||
|
rebuild/multiply path and `physicsworld.c`'s per-body vector math through
|
||||||
|
`pspvfpu`/`gum_*` on the PSP build specifically (behind `#ifdef DUSK_PSP`,
|
||||||
|
matching the project's existing platform-guard convention), while keeping
|
||||||
|
cglm as the portable fallback for Linux/Knulli/GameCube/Wii. This is a
|
||||||
|
genuinely large effort (new platform-specific math backend, careful
|
||||||
|
correctness verification since VFPU has its own quirks around
|
||||||
|
pipelining/hazards) — scope it as its own project, not a quick pass.
|
||||||
|
|
||||||
|
## Priority 3 — UI/spritebatch rebuilds and redraws every vertex, every frame
|
||||||
|
|
||||||
|
Already flagged in `STATUS.md`/`ROADMAP.md` (item 4/5) as a known open
|
||||||
|
issue; this session's research adds concrete numbers. `meshvertex_t`
|
||||||
|
(`display/mesh/meshvertex.h:14-17`) is `{ float uv[2]; float pos[3]; }` =
|
||||||
|
**20 bytes/vertex**, no packing. `SPRITEBATCH_SPRITES_MAX = 512`,
|
||||||
|
`SPRITEBATCH_FLUSH_COUNT = 16` → 32 sprites/flush = 192 vertices = **3,840
|
||||||
|
bytes rebuilt and redrawn per flush**, with a flush forced on every
|
||||||
|
shader/material change (`spritebatch.c:38-50`) and used unconditionally
|
||||||
|
by every widget except `uiconsole.c` (`uitab.c:56`, `uislider.c:183/199/231`,
|
||||||
|
final flush in `ui.c:51`). A UI screen with ~50-100 sprites and 2-3
|
||||||
|
material changes costs an estimated **8-15KB of vertex rebuild + GU
|
||||||
|
submission every single frame**, regardless of whether the UI changed
|
||||||
|
since the last frame.
|
||||||
|
|
||||||
|
Confirmed on the PSP legacy-GL path specifically: there's no GPU buffer
|
||||||
|
re-upload cost (`meshFlushGL` is a literal no-op comment: "we use the
|
||||||
|
glClientState stuff" — `meshgl.c:91-93`; `meshDrawGL` just points
|
||||||
|
`glVertexPointer` at the CPU-side array each call), so the real cost is
|
||||||
|
(a) the CPU-side per-sprite vertex rewrite every frame and (b) GU
|
||||||
|
re-transforming the full vertex stream from RAM on every draw with no
|
||||||
|
skip for unchanged geometry.
|
||||||
|
|
||||||
|
**Fix direction** (already captured in `ROADMAP.md`'s debt backlog item 5):
|
||||||
|
extend `uiconsole.c`'s cached-mesh, dirty-flag-gated rebuild pattern to
|
||||||
|
the rest of the widget tree. This plan adds one refinement: also consider
|
||||||
|
packing `meshvertex_t` down (next item) since it multiplies this cost.
|
||||||
|
|
||||||
|
## Priority 4 — All-float vertex format wastes bandwidth and T&L cost
|
||||||
|
|
||||||
|
`meshvertex_t` uses two `float` fields (20 bytes) for every mesh and
|
||||||
|
sprite vertex, mesh-wide, with no normal or per-vertex color (color is
|
||||||
|
already handled at the material level, so that part is already optimal).
|
||||||
|
GU natively supports fixed-point 16-bit positions/UVs
|
||||||
|
(`GU_VERTEX_16BIT`/`GU_TEXTURE_16BIT`), which would roughly halve
|
||||||
|
per-vertex size and the corresponding vertex-fetch/transform cost, at the
|
||||||
|
cost of position precision (fine for UI/sprite work and most world
|
||||||
|
geometry at this engine's scale; worth checking against the largest
|
||||||
|
world coordinates actually used before committing). Pair with Priority 3
|
||||||
|
so the packing benefit compounds with the dirty-tracking benefit instead
|
||||||
|
of just reducing the cost of a rebuild that still happens every frame.
|
||||||
|
|
||||||
|
## Priority 5 — Running gameplay logic in JerryScript has a real per-frame cost on PSP
|
||||||
|
|
||||||
|
This is new since last session's work, not a pre-existing issue: `assets/
|
||||||
|
scripts/overworldscene.js`'s `update()` is now called every frame via
|
||||||
|
`scriptManagerCallGlobal("update")` (wired into `engine.c`'s
|
||||||
|
`engineUpdate()`), replacing what used to be a direct `cosf`/`sinf` C
|
||||||
|
callback (`entityUpdateAdd`). Per call, `scriptManagerCallGlobal`
|
||||||
|
(`scriptmanager.c:91-144`) does: a global-object property lookup (key is
|
||||||
|
cached, but the `jerry_object_get` dispatch still runs), full JS
|
||||||
|
interpreter call dispatch (frame setup, argument marshaling) for what's a
|
||||||
|
two-line function, and an unconditional `jerry_value_is_promise` check
|
||||||
|
every call even though `update()` is synchronous. Inside, `Math.cos`/
|
||||||
|
`Math.sin` run as JS builtin calls rather than direct libm calls.
|
||||||
|
|
||||||
|
Additionally: this project's JerryScript fork is already patched to use
|
||||||
|
32-bit float internally (`JERRY_NUMBER_TYPE_FLOAT64=0`,
|
||||||
|
`Findjerryscript.cmake`) — a deliberate, already-correct optimization for
|
||||||
|
this exact concern — but the *public* engine API (`jerry_value_as_number()`)
|
||||||
|
still returns `double`, so every native↔JS boundary crossing (every
|
||||||
|
`moduleBaseArgFloat`, every `moduleBaseVec3ToObject`) still pays a
|
||||||
|
float→double→float round trip. Also note `JERRY_MATH` is off, so
|
||||||
|
`Math.sin`/`cos` fall through to whatever generic libm the platform
|
||||||
|
provides rather than JerryScript's own fdlibm implementation — worth
|
||||||
|
checking whether turning it on changes anything measurable on PSP.
|
||||||
|
|
||||||
|
**This is one `update()` call for one scene-level script today — cheap in
|
||||||
|
absolute terms.** It becomes a real problem only if the pattern scales:
|
||||||
|
giving many individual entities their own per-frame JS update callback
|
||||||
|
would multiply all of the above per entity. **Recommendation: keep
|
||||||
|
high-frequency, hot per-entity logic (movement, camera math, physics
|
||||||
|
response) in native C update callbacks (`entityUpdateAdd`, the existing
|
||||||
|
mechanism), and reserve JS for one-time setup, infrequent/event-driven
|
||||||
|
logic, and coarse-grained per-scene orchestration** — which is exactly
|
||||||
|
what `require()` and the typed component wrappers built this session are
|
||||||
|
suited for, not a per-entity-per-frame hot path. This is a design
|
||||||
|
guideline to apply going forward, not a regression to fix in the current
|
||||||
|
`overworldscene.js` (one scene-level `update()` call per frame is fine).
|
||||||
|
|
||||||
|
## Priority 6 — No pooling/arena allocator; plain malloc/free everywhere
|
||||||
|
|
||||||
|
`memoryAllocate`/`memoryFree` (`util/memory.c`) are direct `malloc`/`free`
|
||||||
|
passthroughs (`memoryAlign`→`memalign`, `memoryReallocate`/`memoryResize`→
|
||||||
|
`realloc`), with the only extra behavior being a global allocation-count
|
||||||
|
tracker used solely for test leak detection. No pool, arena, free-list,
|
||||||
|
or size-class allocator exists anywhere.
|
||||||
|
|
||||||
|
This survey found **no rogue per-frame heap allocations** in the hot
|
||||||
|
paths checked (render dispatch in `entityrenderable.c`, all of
|
||||||
|
`physics/*.c`) — so this is not an active bug today. But it's a
|
||||||
|
structural risk for a no-VM platform over a long play session: any future
|
||||||
|
code that does frequent small alloc/free (dynamic lists, string
|
||||||
|
building, temp buffers) will fragment the 32-64MB heap with no OS-level
|
||||||
|
recovery mechanism. **Recommendation: before adding any new subsystem
|
||||||
|
that allocates/frees frequently at runtime (not just at load time),
|
||||||
|
default to a fixed-size pool or arena for it**, following the same
|
||||||
|
"static, bounded" philosophy already used for `ENTITY_COUNT_MAX`/
|
||||||
|
`SCENE_COUNT_MAX`/`ASSET_ENTRY_COUNT_MAX` elsewhere in the engine, rather
|
||||||
|
than reaching for `memoryAllocate` per-instance.
|
||||||
|
|
||||||
|
## Already correct — don't touch without new evidence
|
||||||
|
|
||||||
|
- **`entityposition_t`'s matrix caching** (the pattern the project owner
|
||||||
|
called out as the reason for writing this plan). Verified: a full
|
||||||
|
"dirty" recompute chain (decompose + rebuild local + rebuild world) is
|
||||||
|
~10 trig calls (`asinf`/`cosf`/`atan2f`) plus at most one 4x4 matrix
|
||||||
|
multiply, and `entityPositionEnsurePRS`/`EnsureLocal`/`EnsureWorld`
|
||||||
|
(`entityposition.c:596-669`) all early-return on a flag check, only
|
||||||
|
doing that work when something actually changed. The cache is correct
|
||||||
|
and clearly worth its ~128-byte-per-entity matrix storage cost.
|
||||||
|
- **Physics narrow-phase sqrt avoidance.** All three `sqrtf` call sites
|
||||||
|
in `physicstest.c`/`physicsshapemesh.c` already sit behind a
|
||||||
|
squared-distance early-reject and only compute the real (linear)
|
||||||
|
distance once, when actually needed for penetration depth — no further
|
||||||
|
"use squared distance instead" opportunity was found here.
|
||||||
|
- **No allocations in the render/physics hot loop** (Priority 6) — this
|
||||||
|
is good and worth preserving as new code is added to those files.
|
||||||
|
- **Asset decompression already runs off the main thread.** Assets are
|
||||||
|
DEFLATE-compressed (not stored) in `dusk.dsk`, so loading pays a real
|
||||||
|
CPU cost for decompression — but every `*LoaderAsync` function
|
||||||
|
(`asset/loader/*/*.c`) runs via `ASSET.loadThread`
|
||||||
|
(`assertNotMainThread` in `asset.c:365`), so this cost is already kept
|
||||||
|
off the main thread. Low priority to change; if load-time CPU cost
|
||||||
|
becomes a measured problem later, revisit stored-vs-compressed as a
|
||||||
|
build-time flag rather than assuming compression is free.
|
||||||
|
|
||||||
|
## Suggested approach
|
||||||
|
|
||||||
|
1. **Measure before changing.** None of the above have been profiled on
|
||||||
|
real PSP hardware in this pass — this is a source-level survey, not a
|
||||||
|
profile. Before investing in Priority 1 or 2 especially, confirm with
|
||||||
|
an actual PSP build/run (or at minimum the existing "Entity manager
|
||||||
|
size" startup log plus a frame-time counter) that these are the real
|
||||||
|
bottlenecks, not just the largest numbers on paper.
|
||||||
|
2. **Priority 1 first** — it's the most contained (one component's data
|
||||||
|
layout), has the clearest before/after metric (the startup log line),
|
||||||
|
and doesn't require new platform-specific code.
|
||||||
|
3. **Priority 3 next** (extend the console's dirty-tracking pattern to
|
||||||
|
the rest of the UI) — already scoped in `ROADMAP.md`, no new design
|
||||||
|
needed, just implementation.
|
||||||
|
4. **Priority 2 (VFPU) as a dedicated project**, not a quick pass — it's
|
||||||
|
the largest potential win but touches core math plumbing and needs
|
||||||
|
careful correctness verification on real hardware.
|
||||||
|
5. Treat Priority 5 as a standing design guideline for all future
|
||||||
|
scripting work, not a one-time fix.
|
||||||
@@ -9,18 +9,15 @@ following packages, depending on your system;
|
|||||||
|
|
||||||
Fedora;
|
Fedora;
|
||||||
```
|
```
|
||||||
sudo dnf install git make gcc cmake python python-polib python3-pillow python3-dotenv python3-numpy python-qt5 python3-pyopengl SDL2-devel zlib-devel libzip-devel bzip2-devel openssl-devel lzma-sdk-devel xz xz-devel lua-devel libmad-devel
|
sudo dnf install git make gcc cmake python python-polib python3-pillow python3-dotenv python3-numpy python-qt5 python3-pyopengl SDL2-devel zlib-devel libzip-devel bzip2-devel openssl-devel lzma-sdk-devel xz xz-devel lua-devel
|
||||||
```
|
```
|
||||||
`libmad-devel` (used for MP3 decoding) is GPL-licensed and ships in the
|
|
||||||
[RPM Fusion](https://rpmfusion.org/) free repository rather than Fedora's
|
|
||||||
base repos - make sure RPM Fusion is enabled first.
|
|
||||||
|
|
||||||
Ubuntu;
|
Ubuntu;
|
||||||
```
|
```
|
||||||
sudo apt-get install git build-essential gcc python python-polib python3-pillow python3-dotenv python3-numpy python3-pyqt5 python3-opengl libmad0-dev
|
sudo apt-get install git build-essential gcc python python-polib python3-pillow python3-dotenv python3-numpy python3-pyqt5 python3-opengl
|
||||||
```
|
```
|
||||||
|
|
||||||
Arch Linux;
|
Arch Linux;
|
||||||
```
|
```
|
||||||
sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl libmad
|
sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl
|
||||||
```
|
```
|
||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
# Dusk Roadmap
|
||||||
|
|
||||||
|
Tracking upcoming milestones for the engine. See `PSP_OPTIMIZATION_PLAN.md`
|
||||||
|
for a memory/CPU optimization survey specifically targeting the PSP build
|
||||||
|
(milestone 4 below is its Priority 3).
|
||||||
|
|
||||||
|
## Upcoming milestones
|
||||||
|
|
||||||
|
1. Add a very basic physics engine, moving away from the current
|
||||||
|
tile-based movement.
|
||||||
|
2. Give entities full freedom of movement (no longer locked to tile
|
||||||
|
grid positions).
|
||||||
|
3. Update entity interaction, triggers, chunk management, and other
|
||||||
|
systems that currently assume tile-based positioning so they work
|
||||||
|
with the new 3D positioning/movement code.
|
||||||
|
4. Investigate and fix poor UI rendering performance. First pass done
|
||||||
|
(2026-07-31): slider/tab/frame/textbox now cache their sprite
|
||||||
|
geometry instead of rebuilding it every frame, and the console's
|
||||||
|
vertex buffer is fixed-size instead of alloc/free churn (see
|
||||||
|
`STATUS.md`'s "UI rendering performance" note for detail). Still
|
||||||
|
open: per-widget material/color changes still force a sprite-batch
|
||||||
|
flush each time (color is per-material, not per-vertex), so a row of
|
||||||
|
alternating highlighted widgets still costs one draw call per
|
||||||
|
widget.
|
||||||
|
5. Create UI elements for displaying status indicators, e.g. network
|
||||||
|
connection state and save-in-progress.
|
||||||
|
6. Fully test saving end-to-end on all supported platforms.
|
||||||
|
7. Remove the tile system from chunks in favor of meshes, with
|
||||||
|
dynamic hitboxes per chunk loaded in from the chunk file data.
|
||||||
|
8. Create UI elements for network status: a connecting modal, an
|
||||||
|
error state, and a connected flag. Retire the test HTTP request
|
||||||
|
once these are in place.
|
||||||
|
9. Build the socket server and client implementation, including
|
||||||
|
handlers for the different packet types.
|
||||||
|
10. Add a dedicated multiplayer entity type, `clientplayer`, alongside
|
||||||
|
the existing `npc` and `player` types. Limit to 16 (defined
|
||||||
|
constant, see SERVER_CLIENT_COUNT_MAX/CLIENT_COUNT_MAX in
|
||||||
|
src/dusk/network/socket/) for now.
|
||||||
|
11. Send and receive `clientplayer` position over the network.
|
||||||
|
12. Create a UI menu for creating a server and joining a server. For
|
||||||
|
now, join IPs are hard-coded (testing against a fixed IP of
|
||||||
|
10.0.0.94).
|
||||||
|
13. Create "handshake" packets. For now, just send the username,
|
||||||
|
enforced to be under 10 characters long.
|
||||||
|
14. Server tracks all players' positions and broadcasts them to all
|
||||||
|
connected clients.
|
||||||
|
15. Server sends disconnect packets for users who leave.
|
||||||
|
16. Server assigns each client a UUID; all clients know every other
|
||||||
|
client's UUID (used to reference them across position updates,
|
||||||
|
disconnect packets, etc).
|
||||||
|
17. Server notifies all clients (by UUID) when a user joins, leaves,
|
||||||
|
or is disconnected, so clients can spawn or remove the
|
||||||
|
corresponding `clientplayer` entity in the world.
|
||||||
|
|
||||||
|
## Infrastructure / debt backlog
|
||||||
|
|
||||||
|
Found during a full-codebase inventory pass (2026-07-30, see `STATUS.md`
|
||||||
|
for the full survey). These aren't new feature milestones so much as
|
||||||
|
loose ends worth closing, roughly in order of how cheap/safe they are to
|
||||||
|
fix:
|
||||||
|
|
||||||
|
1. Re-enable `test/item` (currently commented out in
|
||||||
|
`test/CMakeLists.txt`) -- confirm it still passes and turn it back on.
|
||||||
|
2. Restore `itemgive.c/h` in `src/duskrpg/item/CMakeLists.txt` -- the
|
||||||
|
textbox UI dependency it was waiting on (`ui/textbox/`) is already
|
||||||
|
back.
|
||||||
|
3. Decide the fate of the `vita` target: `scripts/build-vita.sh` and
|
||||||
|
`docker/vita/` reference `-DDUSK_TARGET_SYSTEM=vita`, but no
|
||||||
|
`cmake/targets/vita.cmake` exists, so the build is currently broken.
|
||||||
|
Either implement it or remove the dangling scripts/Dockerfile.
|
||||||
|
4. Per-PR CI build coverage for non-Linux targets: first pass added
|
||||||
|
2026-07-31 as `run-tests-gamecube-dolphin`/`run-tests-wii-dolphin`
|
||||||
|
(build the ISO, boot it in Dolphin under Xvfb) and
|
||||||
|
`run-tests-psp-ppsspp` (build the EBOOT, boot it in PPSSPPHeadless)
|
||||||
|
in `.github/workflows/test.yml`, plus matching
|
||||||
|
`scripts/test-*-dolphin.sh`/`scripts/test-psp-ppsspp.sh` (+ `-docker`
|
||||||
|
variants). Marked `continue-on-error: true` since none of these have
|
||||||
|
actually been exercised on a real runner yet -- verify they pass
|
||||||
|
before relying on them, and drop the flag once they do. Knulli still
|
||||||
|
has no per-PR coverage at all.
|
||||||
|
5. Milestone 4 above (poor UI rendering performance) has a first pass
|
||||||
|
in (2026-07-31, see `STATUS.md`) -- remaining concrete lead: sprite
|
||||||
|
batch flushes are keyed on shader+material (including tint color),
|
||||||
|
so per-widget color changes (e.g. focus highlight) still force a
|
||||||
|
flush per widget; moving tint to per-vertex color would let a whole
|
||||||
|
row of widgets batch into one draw call regardless of highlight
|
||||||
|
state.
|
||||||
|
6. Revisit the GameCube/Wii networking static-IP workaround in
|
||||||
|
`networkdolphin.c` -- it's standing in for an unresolved suspected
|
||||||
|
memory-corruption bug in `if_config()`'s DHCP path.
|
||||||
|
7. Decide whether the PSP dialog-based network connect UI needs to come
|
||||||
|
back -- it was removed entirely (not fixed) when the original
|
||||||
|
dialog-tearing bug proved hard to resolve.
|
||||||
|
8. Backfill unit tests for the biggest untested surfaces: `ui/` (whole
|
||||||
|
widget framework), `save/`, `script/` (JerryScript bindings), `event/`.
|
||||||
|
|
||||||
|
## Principles
|
||||||
|
|
||||||
|
- Never trust the network implicitly. Neither side (server or client)
|
||||||
|
should assume the other's packets are well-formed or benign --
|
||||||
|
validate all incoming packet data defensively, since either side
|
||||||
|
may send garbage or malicious data. Use `errorret_t` /
|
||||||
|
`errorThrow()` for these runtime checks, not assert macros --
|
||||||
|
asserts are debug-only and won't guard release builds against
|
||||||
|
malformed or malicious packet data.
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
# Dusk Engine - Status Snapshot
|
||||||
|
|
||||||
|
This is a point-in-time inventory of the codebase's maturity, test coverage,
|
||||||
|
and known gaps. It is not auto-maintained -- re-survey periodically (or
|
||||||
|
whenever picking a new roadmap milestone) rather than trusting it blindly.
|
||||||
|
See `ROADMAP.md` for the ordered feature milestones this status feeds into,
|
||||||
|
and `CLAUDE.md` for coding conventions.
|
||||||
|
|
||||||
|
Last surveyed: 2026-07-31, at commit `8f8fa8f8`.
|
||||||
|
|
||||||
|
## Core engine (`src/dusk/`)
|
||||||
|
|
||||||
|
| Subsystem | Maturity | Notes |
|
||||||
|
|------------|------------------------------------|-------|
|
||||||
|
| asset | Mature, fully wired | Model loading's "async" path is actually synchronous (`assetmodelloader.h`) -- only real stub found in core. |
|
||||||
|
| script | Mature for its current scope | Registered modules: `modulePlatform`, `moduleComponent`/`moduleComponentList` (typed Position/Physics/Renderable wrappers), `moduleEntity`, `moduleScene` (with `Scene.set()` module lifecycle), `moduleMesh`, `moduleTime`, `moduleRequire` (CommonJS-style `require()`/`module.exports`). Entry point is `scripts/init.js`, which does `require('./overworldscene.js')` + `Scene.set()`. Has unit tests (`test/script/`). |
|
||||||
|
| entity | Mature | Engine-level prefab lists are empty sentinels; all real prefabs live in `duskrpg`. |
|
||||||
|
| scene | Mature | Same prefab-delegation pattern as entity. No JSON serialize/deserialize (removed by design). |
|
||||||
|
| save | Mature, but undocumented | Slot-based, yyjson + CRC32, platform stream hooks. Not covered in `CLAUDE.md`, no tests. |
|
||||||
|
| network | Connection-state layer only | HTTP client + connection state machine; no multiplayer/replication protocol (expected -- that's roadmap items 8-17). Not covered in `CLAUDE.md`, has HTTP tests only. |
|
||||||
|
| physics | Mature, recently churned | Recent revert/re-disable of "old ent code" suggests component wiring around physics isn't fully settled. Well tested. |
|
||||||
|
| animation | Early/mid-stage | Keyframes + easing only, no blend trees or state machines. Terse commit history ("ANIM") suggests still iterating. |
|
||||||
|
| display | Most mature/battle-tested | Backbone of the engine; dominated by platform optimization commits. |
|
||||||
|
| ui | Actively churning, perf pass done | Widget framework has had features added and ripped out repeatedly (story/battle UI added then removed). No JS bindings yet (from-scratch surface if that's picked up). Sprite-cache pass landed for slider/tab/frame/textbox (see roadmap item 4 below); still no scripted pointer/hit-testing. Has unit tests for the new caching logic (`test/ui/`), but nothing exercises actual draw calls -- see below. |
|
||||||
|
| console | Small, finished for its scope | Fixed-size cached mesh (no more alloc/free churn), same pattern the rest of `ui/` now follows. |
|
||||||
|
| event | Clean, small, finished | Pub/sub, rebuilt to replace the old input system. |
|
||||||
|
| game | Intentionally header-only | Real implementation lives in `duskrpg/game/game.c`. |
|
||||||
|
|
||||||
|
### UI rendering performance (roadmap item 4)
|
||||||
|
First pass landed 2026-07-31: `uislider`/`uitab` now cache their non-text
|
||||||
|
quads (track/fill/markers, tab background) relative to origin and only
|
||||||
|
rebuild on state change, translating into position at draw time.
|
||||||
|
`uiframe.c` grew `uiFrameDrawCached()`, which skips rebuilding its 9-slice
|
||||||
|
sprites when x/y/width/height match the last call; wired into the
|
||||||
|
confirm dialog, settings panel, and textbox (each owns its own
|
||||||
|
`uiframecache_t`). `uitextbox` no longer does one `spriteBatchBuffer` call
|
||||||
|
per visible glyph -- it builds a per-page glyph cache once and slices a
|
||||||
|
prefix by scroll each frame. `uiconsole` dropped its alloc/free vertex
|
||||||
|
buffer for a fixed 512-glyph array. `uifps` skips its label rebuild when
|
||||||
|
the formatted FPS string hasn't changed.
|
||||||
|
|
||||||
|
Still open: every widget still issues its own `spriteBatchBuffer` call
|
||||||
|
per material/color, so a row of alternating highlighted/plain widgets
|
||||||
|
still forces a GPU flush per widget (color is applied via material, not
|
||||||
|
per-vertex) -- that's the next real win if PSP framerate is still an
|
||||||
|
issue. No scripted pointer/hit-testing exists either; input is still
|
||||||
|
100% gamepad/keyboard directional-focus (`ui/focus/`).
|
||||||
|
|
||||||
|
Test coverage caveat: `test/ui/` and `test/display/test_spritebatchsprite.c`
|
||||||
|
cover the new caching *logic* (geometry math, exercised by constructing
|
||||||
|
widget structs directly) but cannot exercise `uiXxxDraw()`/`uiFrameDraw()`
|
||||||
|
themselves -- those need `FONT_DEFAULT`/`UI_FRAME`'s GL texture, which
|
||||||
|
needs a live GL context this test binary doesn't have (confirmed: calling
|
||||||
|
`fontInitDefault()` in a test asserts in `texturegl.c`). This is true of
|
||||||
|
the whole rendering layer, not something newly introduced -- there's no
|
||||||
|
GL-backed test harness anywhere in the repo yet.
|
||||||
|
|
||||||
|
## Game layer (`src/duskrpg/`)
|
||||||
|
|
||||||
|
Actively maintained, not orphaned (despite an old "remove rpg" commit deep
|
||||||
|
in history) -- last touched the same day as this survey.
|
||||||
|
|
||||||
|
- **cutscene/** -- actively developed, matches `CLAUDE.md`'s documented
|
||||||
|
recipe exactly. 16 registered item types.
|
||||||
|
- **entity/, scene/** -- overworld player/camera/interactable components
|
||||||
|
and prefabs, active.
|
||||||
|
- **item/** -- `item.c`/`inventory.c`/`backpack.c` built via a working
|
||||||
|
`item.json` -> `itemdef.h` codegen pipeline. `itemgive.c/h` exist on
|
||||||
|
disk but are explicitly excluded from the CMake build pending textbox
|
||||||
|
UI restoration -- **that UI (`ui/textbox/`) is already restored**, so
|
||||||
|
this looks like an overdue follow-up, not a real blocker.
|
||||||
|
- **input/** -- headers only, no implementation. Contains the one
|
||||||
|
genuine TODO found in the whole `duskrpg` tree: `// TODO: Wiimote, USB
|
||||||
|
Keyboard, probably more.`
|
||||||
|
- **ui/** -- textbox restored and built; `uitestlabel.c/h` is an
|
||||||
|
intentional smoke-test scaffold, not dead code.
|
||||||
|
|
||||||
|
## Platform layers
|
||||||
|
|
||||||
|
| Platform | Status |
|
||||||
|
|--------------|--------|
|
||||||
|
| duskgl / dusksdl2 | Complete, shared by Linux/Knulli/PSP, no gaps found. |
|
||||||
|
| dusklinux | Complete, well-trodden. |
|
||||||
|
| duskpsp | Complete for current design. The historical dialog/tearing bug (see memory `project_psp_dialog_tearing` etc.) was **not fixed -- the dialog-based connect UI was removed entirely** (commit `d7982599`, "Simplified PSP network") in favor of a silent profile-based connect. Revisit if the dialog UX is still wanted. |
|
||||||
|
| duskdolphin (GameCube/Wii) | Functional, not a stub -- real GX-based display/mesh/shader/texture. Wii input uses only the GameCube `PAD_*` library; no WPAD/Wiimote support (`inputdolphin.h` has `#error "Wii not implemented"` gated behind macros that are never defined, so currently dormant, not a live build break). `networkdolphin.c` hardcodes a static IP as an explicit temporary workaround for a suspected DHCP-related memory-corruption bug in `if_config()` -- root cause still open. |
|
||||||
|
| vita | **Referenced by `scripts/build-vita.sh` and `docker/vita/` but no `cmake/targets/vita.cmake` exists** -- the build target is broken/unfinished at the CMake level. |
|
||||||
|
|
||||||
|
### CI coverage gap
|
||||||
|
`.github/workflows/test.yml` only builds+tests Linux, on PRs to `main`.
|
||||||
|
`build.yml` builds all other platforms (PSP, Knulli, GameCube, Wii +
|
||||||
|
ISO variants) but **only on tag push** (release time). Vita and Dolphin
|
||||||
|
aren't in CI at all. Net effect: regressions on 4+ platforms can land
|
||||||
|
silently until a release tag is cut.
|
||||||
|
|
||||||
|
## Test coverage gaps
|
||||||
|
|
||||||
|
Core `src/dusk/` subsystems with **zero** unit tests: `console`,
|
||||||
|
`engine`, `event`, `game`, `input`, `log`, `save`, `script` (+ all JS
|
||||||
|
module bindings), `system`, `ui` (entire widget framework).
|
||||||
|
|
||||||
|
`src/duskrpg/` has almost no test coverage: `test/item/test_inventory.c`
|
||||||
|
exists but **`add_subdirectory(item)` is commented out in
|
||||||
|
`test/CMakeLists.txt`**, so even that one test never runs. `cutscene`,
|
||||||
|
`entity`, `game`, `input`, `scene`, `ui` under `duskrpg` have no tests at
|
||||||
|
all.
|
||||||
|
|
||||||
|
No stale tests were found referencing deleted systems (old JSON
|
||||||
|
serialize/deserialize, old event/cutscene modules) -- the test suite is
|
||||||
|
internally consistent with current code, just incomplete in coverage.
|
||||||
|
|
||||||
|
## Build/tooling gaps worth knowing about
|
||||||
|
|
||||||
|
- `assetsraw/` -> `assets/` (chunk JSON -> `.dcf`) is a manual/editor-only
|
||||||
|
step (`tools.asset.chunk`), not part of the CMake build -- committed
|
||||||
|
`.dcf` files can silently drift from their raw source.
|
||||||
|
- Several Python tool packages exist but aren't wired into any build:
|
||||||
|
`tools/color/csv/`, `tools/asset/chunk_json/`, `tools/asset/dmf/`,
|
||||||
|
`tools/asset/tiles/`, `tools/input/csv/`. Some may be superseded by
|
||||||
|
`tools/color.py`/`tools/item.py`; worth a pass to confirm which are
|
||||||
|
live vs leftover.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,68 +0,0 @@
|
|||||||
{
|
|
||||||
"items": [
|
|
||||||
// First thing, try and find a save device, used for settings and what not.
|
|
||||||
{
|
|
||||||
"type": "MODAL",
|
|
||||||
"title": "initial.checking_save.title",
|
|
||||||
"message": "initial.checking_save.message"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "WAIT",
|
|
||||||
"seconds": 0.2
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "SAVE_DEVICE_CHECK",
|
|
||||||
"successMarker": "CONTINUE",
|
|
||||||
"failureMarker": "SAVE_DEVICE_NOT_FOUND"
|
|
||||||
},
|
|
||||||
|
|
||||||
// No save device found
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "SAVE_DEVICE_NOT_FOUND"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_CLOSE"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_OPTIONS_MARKERS",
|
|
||||||
"title": "initial.no_device.title",
|
|
||||||
"message": "initial.no_device.message",
|
|
||||||
"options": [
|
|
||||||
{
|
|
||||||
"text": "initial.no_device.retry",
|
|
||||||
"marker": "SAVE_DEVICE_RETRY"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"text": "initial.no_device.continue",
|
|
||||||
"marker": "CONTINUE"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
|
|
||||||
// Save device not found, user to retry, just close modal and loop
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "SAVE_DEVICE_RETRY"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_CLOSE"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "RESTART"
|
|
||||||
},
|
|
||||||
|
|
||||||
// Save device found (or continuing without one)
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "CONTINUE"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_CLOSE"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "CUTSCENE",
|
|
||||||
"name": "main_menu"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
{
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "MAIN_MENU_IDLE"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "UI_SHOW",
|
|
||||||
"name": "main_menu"
|
|
||||||
},
|
|
||||||
|
|
||||||
// Options button goes here - no options screen yet, so this is just
|
|
||||||
// an alias landing right back on the idle loop below.
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "OPTIONS"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "IDLE"
|
|
||||||
},
|
|
||||||
|
|
||||||
// New Game button goes here.
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "NEW_GAME"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL",
|
|
||||||
"title": "main_menu.checking_save.title",
|
|
||||||
"message": "main_menu.checking_save.message"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "WAIT",
|
|
||||||
"seconds": 0.2
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "SAVE_DEVICE_CHECK",
|
|
||||||
"successMarker": "SAVE_DEVICE_FOUND",
|
|
||||||
"failureMarker": "SAVE_DEVICE_NOT_FOUND"
|
|
||||||
},
|
|
||||||
|
|
||||||
// Save device not found
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "SAVE_DEVICE_NOT_FOUND"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_CLOSE"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_OPTIONS_MARKERS",
|
|
||||||
"title": "main_menu.no_device.title",
|
|
||||||
"message": "main_menu.no_device.message",
|
|
||||||
"options": [
|
|
||||||
{
|
|
||||||
"text": "main_menu.no_device.retry",
|
|
||||||
"marker": "NEW_GAME"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"text": "main_menu.no_device.continue",
|
|
||||||
"marker": "SAVE_DEVICE_FOUND"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
|
|
||||||
// Save data failed to load (e.g. corrupt/unreadable) - only option is
|
|
||||||
// to retry, no "continue without saving" here since we already know a
|
|
||||||
// device is present.
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "LOAD_ERROR"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_OPTIONS_MARKERS",
|
|
||||||
"title": "main_menu.save_load_error.title",
|
|
||||||
"message": "main_menu.save_load_error.message",
|
|
||||||
"options": [
|
|
||||||
{
|
|
||||||
"text": "main_menu.save_load_error.retry",
|
|
||||||
"marker": "NEW_GAME"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
|
|
||||||
// Quit Game button goes here. Cancelling jumps back to
|
|
||||||
// MAIN_MENU_IDLE; confirming falls through to QUIT_GAME, which
|
|
||||||
// ends the process directly.
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "QUIT"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_OPTIONS_MARKERS",
|
|
||||||
"title": "main_menu.quit_confirm",
|
|
||||||
"options": [
|
|
||||||
{
|
|
||||||
"text": "ui.confirm.confirm",
|
|
||||||
"marker": "QUIT_CONFIRMED"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"text": "ui.confirm.cancel",
|
|
||||||
"marker": "MAIN_MENU_IDLE"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "QUIT_CONFIRMED"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "QUIT_GAME"
|
|
||||||
},
|
|
||||||
|
|
||||||
// main menu just listens for cutscene ending to show the select save modal
|
|
||||||
// so we have that here.
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "SAVE_DEVICE_FOUND"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "MODAL_CLOSE"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "SAVE_LOAD_ALL_SLOTS",
|
|
||||||
"successMarker": "LOADED",
|
|
||||||
"failureMarker": "LOAD_ERROR"
|
|
||||||
},
|
|
||||||
|
|
||||||
// Must be the very last item - falling off the end here is what
|
|
||||||
// completes the cutscene and fires uiMainMenuOpenSelectSave (see
|
|
||||||
// cutsceneSystemSetOnComplete in ui/screen/mainmenu/uimainmenu.c).
|
|
||||||
// Placing this anywhere earlier would fall through into whatever
|
|
||||||
// comes next instead (e.g. the QUIT block, if placed just before it).
|
|
||||||
{
|
|
||||||
"type": "MARKER",
|
|
||||||
"name": "LOADED"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -5,107 +5,11 @@ msgstr ""
|
|||||||
"Content-Type: text/plain; charset=UTF-8\n"
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
|
"Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
|
||||||
|
|
||||||
# Initial Scene
|
|
||||||
msgid "initial.checking_save.title"
|
|
||||||
msgstr "Checking for save data"
|
|
||||||
|
|
||||||
msgid "initial.checking_save.message"
|
|
||||||
msgstr "Please wait..."
|
|
||||||
|
|
||||||
msgid "initial.no_device.title"
|
|
||||||
msgstr "No Save Device Found"
|
|
||||||
|
|
||||||
msgid "initial.no_device.message"
|
|
||||||
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
|
|
||||||
|
|
||||||
msgid "initial.no_device.retry"
|
|
||||||
msgstr "Try again"
|
|
||||||
|
|
||||||
msgid "initial.no_device.continue"
|
|
||||||
msgstr "Continue without saving"
|
|
||||||
|
|
||||||
|
|
||||||
# Main Menu Scene
|
|
||||||
msgid "main_menu.start_game"
|
|
||||||
msgstr "Start Game"
|
|
||||||
|
|
||||||
msgid "main_menu.options"
|
|
||||||
msgstr "Options"
|
|
||||||
|
|
||||||
msgid "main_menu.quit"
|
|
||||||
msgstr "Quit Game"
|
|
||||||
|
|
||||||
msgid "main_menu.quit_confirm"
|
|
||||||
msgstr "Are you sure you want to quit?"
|
|
||||||
|
|
||||||
msgid "main_menu.checking_save.title"
|
|
||||||
msgstr "Checking for save data"
|
|
||||||
|
|
||||||
msgid "main_menu.checking_save.message"
|
|
||||||
msgstr "Please wait..."
|
|
||||||
|
|
||||||
msgid "main_menu.no_device.title"
|
|
||||||
msgstr "No Save Device Found"
|
|
||||||
|
|
||||||
msgid "main_menu.no_device.message"
|
|
||||||
msgstr "Could not find a save device, ensure it is connected and try again. You can continue, but progress will not be saved."
|
|
||||||
|
|
||||||
msgid "main_menu.no_device.retry"
|
|
||||||
msgstr "Try again"
|
|
||||||
|
|
||||||
msgid "main_menu.no_device.continue"
|
|
||||||
msgstr "Continue without saving"
|
|
||||||
|
|
||||||
msgid "main_menu.save_load_error.title"
|
|
||||||
msgstr "Error"
|
|
||||||
|
|
||||||
msgid "main_menu.save_load_error.message"
|
|
||||||
msgstr "Failed to load save data. Please try again."
|
|
||||||
|
|
||||||
msgid "main_menu.save_load_error.retry"
|
|
||||||
msgstr "Try Again"
|
|
||||||
|
|
||||||
|
|
||||||
# Select Save Screen
|
|
||||||
msgid "ui.select_save.title"
|
|
||||||
msgstr "Select Save"
|
|
||||||
|
|
||||||
msgid "ui.select_save.empty"
|
|
||||||
msgstr "Empty Slot"
|
|
||||||
|
|
||||||
msgid "ui.select_save.slot_format"
|
|
||||||
msgstr "%s Lv.%d %s"
|
|
||||||
|
|
||||||
msgid "ui.select_save.delete_mode"
|
|
||||||
msgstr "Delete a Save"
|
|
||||||
|
|
||||||
msgid "ui.select_save.delete_confirm"
|
|
||||||
msgstr "Are you sure you want to delete this save?"
|
|
||||||
|
|
||||||
msgid "ui.select_save.name_title"
|
|
||||||
msgstr "Enter game save file name"
|
|
||||||
|
|
||||||
msgid "ui.save_slot.number_format"
|
|
||||||
msgstr "Slot %d"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#: ui/menu.c:10
|
#: ui/menu.c:10
|
||||||
msgid "ui.title"
|
msgid "ui.title"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
"Welcome"
|
"Welcome"
|
||||||
|
|
||||||
msgid "save.linux.mkdirp_failed"
|
|
||||||
msgstr "Failed to create save directory, check the disk is not full or write-protected."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettings.c
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
msgid "ui.settings.tabs.general"
|
msgid "ui.settings.tabs.general"
|
||||||
msgstr "General"
|
msgstr "General"
|
||||||
@@ -152,114 +56,6 @@ msgstr "Items"
|
|||||||
msgid "ui.game_menu.settings"
|
msgid "ui.game_menu.settings"
|
||||||
msgstr "Settings"
|
msgstr "Settings"
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save"
|
|
||||||
msgstr "Save"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_success"
|
|
||||||
msgstr "Game saved."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_cancelled"
|
|
||||||
msgstr "Save cancelled."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_unavailable"
|
|
||||||
msgstr "Can't save - no save device found."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_temporary"
|
|
||||||
msgstr "This session is temporary - no save device was found, so saving is disabled."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_create_confirm"
|
|
||||||
msgstr "No save data found. Create a new save?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_failed_format"
|
|
||||||
msgstr "Save failed: %s"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/game/uigamemenu.c
|
|
||||||
msgid "ui.game_menu.save_check_failed_format"
|
|
||||||
msgstr "Can't save: %s"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.message"
|
|
||||||
msgstr "No save device found. You can continue, but\nprogress will not be saved."
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.retry"
|
|
||||||
msgstr "Retry"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialnocard.c
|
|
||||||
msgid "ui.initial.no_card.continue"
|
|
||||||
msgstr "Continue Anyway"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.message"
|
|
||||||
msgstr "No save data found. Create a new save?"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.yes"
|
|
||||||
msgstr "Yes"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/initial/uiinitialcreatesave.c
|
|
||||||
msgid "ui.initial.create_save.no"
|
|
||||||
msgstr "No"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/uiconfirm.c
|
|
||||||
msgid "ui.confirm.confirm"
|
|
||||||
msgstr "Confirm"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/uiconfirm.c
|
|
||||||
msgid "ui.confirm.cancel"
|
|
||||||
msgstr "Cancel"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/battle/uibattlemenu.c
|
|
||||||
msgid "ui.battle.menu.attack"
|
|
||||||
msgstr "Attack"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/battle/uibattlemenu.c
|
|
||||||
msgid "ui.battle.menu.flee"
|
|
||||||
msgstr "Flee"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/battle/uibattlemenu.c
|
|
||||||
msgid "ui.battle.menu.target_format"
|
|
||||||
msgstr "Enemy %u (%u/%u HP)"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/battle/uibattlehud.c
|
|
||||||
msgid "ui.battle.hud.hp_format"
|
|
||||||
msgstr "HP %u/%u"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/battle/uibattlehud.c
|
|
||||||
msgid "ui.battle.hud.mp_format"
|
|
||||||
msgstr "MP %u/%u"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettingsaudio.c
|
|
||||||
msgid "ui.settings.audio.placeholder"
|
|
||||||
msgstr "No audio settings yet"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettingsdisplay.c
|
|
||||||
msgid "ui.settings.display.placeholder"
|
|
||||||
msgstr "No display settings yet"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/settings/uisettingsinput.c
|
|
||||||
msgid "ui.settings.input.placeholder"
|
|
||||||
msgstr "No input settings yet"
|
|
||||||
|
|
||||||
#: src/dusk/ui/frame/backpack/uibackpack.c
|
|
||||||
msgid "ui.backpack.category_format"
|
|
||||||
msgstr "Category %u"
|
|
||||||
|
|
||||||
#: src/dusk/ui/overlay/uiloading.c
|
|
||||||
msgid "ui.loading.text"
|
|
||||||
msgstr "loading"
|
|
||||||
|
|
||||||
#: src/dusk/ui/overlay/uiautosave.c
|
|
||||||
msgid "ui.autosave.saving"
|
|
||||||
msgstr "SAVING"
|
|
||||||
|
|
||||||
msgid "item.potion.name"
|
msgid "item.potion.name"
|
||||||
msgstr "Potion"
|
msgstr "Potion"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
msgid ""
|
||||||
|
msgstr ""
|
||||||
|
"Project-Id-Version: ExampleApp 1.0\n"
|
||||||
|
"Language: es\n"
|
||||||
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
|
"Plural-Forms: nplurals=2; plural=(n==1 ? 0 : 1);\n"
|
||||||
|
|
||||||
|
#: ui/menu.c:10
|
||||||
|
msgid "ui.title"
|
||||||
|
msgstr ""
|
||||||
|
"Bienvenido"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.general"
|
||||||
|
msgstr "General"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.input"
|
||||||
|
msgstr "Entrada"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.display"
|
||||||
|
msgstr "Pantalla"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.audio"
|
||||||
|
msgstr "Audio"
|
||||||
|
|
||||||
|
msgid "ui.settings.input.deadzone"
|
||||||
|
msgstr "Deadzone"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
||||||
|
msgid "ui.settings.general.language"
|
||||||
|
msgstr "Idioma"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
||||||
|
msgid "ui.settings.general.language_detail"
|
||||||
|
msgstr "Se aplica después de reiniciar la aplicación."
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.apply"
|
||||||
|
msgstr "Aplicar"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/uiconfirm.c
|
||||||
|
msgid "ui.confirm.discard_changes"
|
||||||
|
msgstr "¿Descartar los cambios no guardados?"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/game/uigamemenu.c
|
||||||
|
msgid "ui.game_menu.characters"
|
||||||
|
msgstr "Personajes"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/game/uigamemenu.c
|
||||||
|
msgid "ui.game_menu.items"
|
||||||
|
msgstr "Objetos"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/game/uigamemenu.c
|
||||||
|
msgid "ui.game_menu.settings"
|
||||||
|
msgstr "Configuración"
|
||||||
|
|
||||||
|
#: src/dusk/rpg/item/item.json
|
||||||
|
msgid "item.potion.name"
|
||||||
|
msgstr "Poción"
|
||||||
|
|
||||||
|
#: src/dusk/rpg/item/item.json
|
||||||
|
msgid "item.potato.name"
|
||||||
|
msgstr "Papa"
|
||||||
|
|
||||||
|
#: src/dusk/rpg/item/item.json
|
||||||
|
msgid "item.apple.name"
|
||||||
|
msgstr "Manzana"
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
msgid ""
|
||||||
|
msgstr ""
|
||||||
|
"Project-Id-Version: ExampleApp 1.0\n"
|
||||||
|
"Language: ja\n"
|
||||||
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
|
"Plural-Forms: nplurals=1; plural=(0);\n"
|
||||||
|
|
||||||
|
#: ui/menu.c:10
|
||||||
|
msgid "ui.title"
|
||||||
|
msgstr ""
|
||||||
|
"歓迎"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.general"
|
||||||
|
msgstr "一般"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.input"
|
||||||
|
msgstr "入力"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.display"
|
||||||
|
msgstr "表示"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.tabs.audio"
|
||||||
|
msgstr "オーディオ"
|
||||||
|
|
||||||
|
msgid "ui.settings.input.deadzone"
|
||||||
|
msgstr "デッドゾーン"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
||||||
|
msgid "ui.settings.general.language"
|
||||||
|
msgstr "言語"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
|
||||||
|
msgid "ui.settings.general.language_detail"
|
||||||
|
msgstr "アプリケーションを再起動すると適用されます。"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/settings/uisettings.c
|
||||||
|
msgid "ui.settings.apply"
|
||||||
|
msgstr "適用"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/uiconfirm.c
|
||||||
|
msgid "ui.confirm.discard_changes"
|
||||||
|
msgstr "未保存の変更を破棄しますか?"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/game/uigamemenu.c
|
||||||
|
msgid "ui.game_menu.characters"
|
||||||
|
msgstr "キャラクター"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/game/uigamemenu.c
|
||||||
|
msgid "ui.game_menu.items"
|
||||||
|
msgstr "アイテム"
|
||||||
|
|
||||||
|
#: src/dusk/ui/frame/game/uigamemenu.c
|
||||||
|
msgid "ui.game_menu.settings"
|
||||||
|
msgstr "設定"
|
||||||
|
|
||||||
|
#: src/dusk/rpg/item/item.json
|
||||||
|
msgid "item.potion.name"
|
||||||
|
msgstr "ポーション"
|
||||||
|
|
||||||
|
#: src/dusk/rpg/item/item.json
|
||||||
|
msgid "item.potato.name"
|
||||||
|
msgstr "ジャガイモ"
|
||||||
|
|
||||||
|
#: src/dusk/rpg/item/item.json
|
||||||
|
msgid "item.apple.name"
|
||||||
|
msgstr "リンゴ"
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// Copyright (c) 2026 Dominic Masters
|
||||||
|
//
|
||||||
|
// This software is released under the MIT License.
|
||||||
|
// https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
// Player: dynamic capsule body, moved relative to the camera by PLAYER's
|
||||||
|
// own update callback (see entityplayer.c).
|
||||||
|
class Player {
|
||||||
|
constructor() {
|
||||||
|
this.entity = new Entity();
|
||||||
|
|
||||||
|
this.position = this.entity.add(POSITION);
|
||||||
|
this.position.setLocalPosition(0.0, 2.0, 0.0);
|
||||||
|
|
||||||
|
this.physics = this.entity.add(PHYSICS);
|
||||||
|
this.physics.setShape(PHYSICS_SHAPE_CAPSULE, 0.5, 0.5);
|
||||||
|
|
||||||
|
this.renderable = this.entity.add(RENDERABLE);
|
||||||
|
this.renderable.setMesh(0, MESH_CAPSULE);
|
||||||
|
this.renderable.setColor(0, 0, 255, 255);
|
||||||
|
|
||||||
|
this.entity.add(PLAYER);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = Player;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// Copyright (c) 2026 Dominic Masters
|
||||||
|
//
|
||||||
|
// This software is released under the MIT License.
|
||||||
|
// https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
// Entry point run once at startup (see game.c). Swap which scene module
|
||||||
|
// gets passed to Scene.set() here to change what the game boots into.
|
||||||
|
var overworldScene = require('./overworldscene.js');
|
||||||
|
Scene.set(overworldScene);
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// Copyright (c) 2026 Dominic Masters
|
||||||
|
//
|
||||||
|
// This software is released under the MIT License.
|
||||||
|
// https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
// Radius must stay well outside the floor's footprint (a 20x20 plane has a
|
||||||
|
// corner-to-center distance of 10*sqrt(2) =~ 14.1) -- orbiting inside that
|
||||||
|
// puts parts of the floor's own geometry near/behind the camera's view
|
||||||
|
// direction, which the PSP's legacy GU pipeline can't clip properly and
|
||||||
|
// drops the whole triangle instead of clipping it.
|
||||||
|
var CAMERA_ORBIT_RADIUS = 18.0;
|
||||||
|
var CAMERA_ORBIT_HEIGHT = 10.0;
|
||||||
|
var CAMERA_ORBIT_SPEED = 0.5;
|
||||||
|
|
||||||
|
var Player = require('./Player.js');
|
||||||
|
|
||||||
|
var cameraOrbitAngle = 0.0;
|
||||||
|
var cameraPosition = null;
|
||||||
|
|
||||||
|
// Orbits the camera around the world origin at a fixed radius/height/
|
||||||
|
// speed, always looking back at the origin. Called once up front (so the
|
||||||
|
// very first rendered frame is already positioned correctly) and then
|
||||||
|
// once per frame via update() below.
|
||||||
|
function updateCameraOrbit() {
|
||||||
|
cameraOrbitAngle += Time.delta * CAMERA_ORBIT_SPEED;
|
||||||
|
|
||||||
|
var eyeX = Math.cos(cameraOrbitAngle) * CAMERA_ORBIT_RADIUS;
|
||||||
|
var eyeY = CAMERA_ORBIT_HEIGHT;
|
||||||
|
var eyeZ = Math.sin(cameraOrbitAngle) * CAMERA_ORBIT_RADIUS;
|
||||||
|
|
||||||
|
cameraPosition.lookAt(eyeX, eyeY, eyeZ, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
// Called once by Scene.set(), right after it creates and activates the
|
||||||
|
// scene this module owns.
|
||||||
|
init: function() {
|
||||||
|
// Camera, orbiting the origin (see updateCameraOrbit above).
|
||||||
|
var camera = new Entity();
|
||||||
|
cameraPosition = camera.add(POSITION);
|
||||||
|
camera.add(CAMERA);
|
||||||
|
updateCameraOrbit();
|
||||||
|
|
||||||
|
// Static ground plane. Physics ignores the entity's position
|
||||||
|
// component -- the shape's own normal/distance fully define the
|
||||||
|
// plane in world space.
|
||||||
|
var plane = new Entity();
|
||||||
|
var planePosition = plane.add(POSITION);
|
||||||
|
planePosition.setLocalPosition(-10.0, 0.0, -10.0);
|
||||||
|
planePosition.setLocalScale(20.0, 1.0, 20.0);
|
||||||
|
|
||||||
|
var planePhysics = plane.add(PHYSICS);
|
||||||
|
planePhysics.setBodyType(PHYSICS_BODY_STATIC);
|
||||||
|
planePhysics.setShape(PHYSICS_SHAPE_PLANE, 0.0, 1.0, 0.0, 0.0);
|
||||||
|
|
||||||
|
var planeRenderable = plane.add(RENDERABLE);
|
||||||
|
planeRenderable.setMesh(0, MESH_PLANE);
|
||||||
|
planeRenderable.setColor(128, 128, 128, 255);
|
||||||
|
|
||||||
|
new Player();
|
||||||
|
},
|
||||||
|
|
||||||
|
// Called once per engine frame while this module is the active scene
|
||||||
|
// (see Scene.set(), engineUpdate() -> moduleSceneUpdateCurrent()).
|
||||||
|
update: function() {
|
||||||
|
if(cameraPosition) updateCameraOrbit();
|
||||||
|
},
|
||||||
|
|
||||||
|
// Called once by Scene.set() when this module is replaced by another,
|
||||||
|
// right before the scene it owns is destroyed.
|
||||||
|
dispose: function() {
|
||||||
|
cameraPosition = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 1.2 KiB |
@@ -2179,27 +2179,5 @@
|
|||||||
0
|
0
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
|
||||||
"entities": [
|
|
||||||
{
|
|
||||||
"type": "global",
|
|
||||||
"globalId": 3,
|
|
||||||
"pos": [8, 8, 1]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "item",
|
|
||||||
"itemId": 1,
|
|
||||||
"quantity": 1,
|
|
||||||
"pos": [12, 2, 0]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"areas": [
|
|
||||||
{
|
|
||||||
"min": [11, 3, 0],
|
|
||||||
"max": [16, 9, 10],
|
|
||||||
"callbackId": 1,
|
|
||||||
"notify": 3,
|
|
||||||
"trigger": 6
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# Copyright (c) 2026 Dominic Masters
|
||||||
|
#
|
||||||
|
# This software is released under the MIT License.
|
||||||
|
# https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
# Turn things off we don't need
|
||||||
|
set(JERRY_CMDLINE OFF CACHE BOOL "" FORCE)
|
||||||
|
set(JERRY_EXT ON CACHE BOOL "" FORCE)
|
||||||
|
set(JERRY_DEBUGGER OFF CACHE BOOL "" FORCE)
|
||||||
|
set(JERRY_BUILTIN_DATE OFF CACHE BOOL "" FORCE)
|
||||||
|
set(ENABLE_LTO OFF CACHE BOOL "" FORCE)
|
||||||
|
|
||||||
|
# Fetch Jerry
|
||||||
|
include(FetchContent)
|
||||||
|
FetchContent_Declare(
|
||||||
|
jerryscript
|
||||||
|
GIT_REPOSITORY https://git.wish.moe/YourWishes/jerryscript
|
||||||
|
GIT_TAG float32-fix
|
||||||
|
)
|
||||||
|
FetchContent_MakeAvailable(jerryscript)
|
||||||
|
|
||||||
|
# Mark found
|
||||||
|
set(jerryscript_FOUND ON)
|
||||||
|
|
||||||
|
# Define targets
|
||||||
|
if(TARGET jerryscript-core)
|
||||||
|
set(JERRY_CORE_TARGET jerryscript-core)
|
||||||
|
elseif(TARGET jerry-core)
|
||||||
|
set(JERRY_CORE_TARGET jerry-core)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(TARGET jerryscript-ext)
|
||||||
|
set(JERRY_EXT_TARGET jerryscript-ext)
|
||||||
|
elseif(TARGET jerry-ext)
|
||||||
|
set(JERRY_EXT_TARGET jerry-ext)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(TARGET jerryscript-port-default)
|
||||||
|
set(JERRY_PORT_TARGET jerryscript-port-default)
|
||||||
|
elseif(TARGET jerry-port-default)
|
||||||
|
set(JERRY_PORT_TARGET jerry-port-default)
|
||||||
|
elseif(TARGET jerryscript-port)
|
||||||
|
set(JERRY_PORT_TARGET jerryscript-port)
|
||||||
|
elseif(TARGET jerry-port)
|
||||||
|
set(JERRY_PORT_TARGET jerry-port)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT JERRY_CORE_TARGET)
|
||||||
|
message(FATAL_ERROR "JerryScript core target not found")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT JERRY_EXT_TARGET)
|
||||||
|
message(FATAL_ERROR "JerryScript ext target not found")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT JERRY_PORT_TARGET)
|
||||||
|
message(FATAL_ERROR "JerryScript port target not found")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
foreach(tgt IN ITEMS
|
||||||
|
${JERRY_CORE_TARGET}
|
||||||
|
${JERRY_EXT_TARGET}
|
||||||
|
${JERRY_PORT_TARGET}
|
||||||
|
)
|
||||||
|
if(TARGET ${tgt})
|
||||||
|
set_property(TARGET ${tgt} PROPERTY INTERPROCEDURAL_OPTIMIZATION OFF)
|
||||||
|
target_compile_definitions(${JERRY_CORE_TARGET} PRIVATE
|
||||||
|
JERRY_NUMBER_TYPE_FLOAT64=0
|
||||||
|
JERRY_BUILTIN_DATE=0
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
# Export include dirs through the targets
|
||||||
|
target_include_directories(${JERRY_CORE_TARGET} INTERFACE
|
||||||
|
${jerryscript_SOURCE_DIR}/jerry-core/include
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(${JERRY_EXT_TARGET} INTERFACE
|
||||||
|
${jerryscript_SOURCE_DIR}/jerry-ext/include
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(${JERRY_PORT_TARGET} INTERFACE
|
||||||
|
${jerryscript_SOURCE_DIR}/jerry-port/default/include
|
||||||
|
)
|
||||||
|
|
||||||
|
# Suppress JerryScript-only warning
|
||||||
|
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
|
||||||
|
target_compile_options(${JERRY_CORE_TARGET} PRIVATE
|
||||||
|
-Wno-error
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
add_library(jerryscript::core ALIAS ${JERRY_CORE_TARGET})
|
||||||
|
add_library(jerryscript::ext ALIAS ${JERRY_EXT_TARGET})
|
||||||
|
add_library(jerryscript::port ALIAS ${JERRY_PORT_TARGET})
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
# Copyright (c) 2026 Dominic Masters
|
|
||||||
#
|
|
||||||
# This software is released under the MIT License.
|
|
||||||
# https://opensource.org/licenses/MIT
|
|
||||||
|
|
||||||
# NOTE: libmad itself is GPL-licensed (see https://www.underbit.com/products/mad/),
|
|
||||||
# not MIT like the rest of this project. Any binary linking it must comply
|
|
||||||
# with the GPL - a deliberate tradeoff accepted for MP3 decode correctness
|
|
||||||
# (see audiostreammp3decodersw.c's own comment on why minimp3 wasn't enough).
|
|
||||||
|
|
||||||
find_path(LIBMAD_INCLUDE_DIR NAMES mad.h)
|
|
||||||
mark_as_advanced(LIBMAD_INCLUDE_DIR)
|
|
||||||
|
|
||||||
find_library(LIBMAD_LIBRARY NAMES mad)
|
|
||||||
mark_as_advanced(LIBMAD_LIBRARY)
|
|
||||||
|
|
||||||
include(FindPackageHandleStandardArgs)
|
|
||||||
find_package_handle_standard_args(
|
|
||||||
libmad
|
|
||||||
REQUIRED_VARS
|
|
||||||
LIBMAD_LIBRARY
|
|
||||||
LIBMAD_INCLUDE_DIR
|
|
||||||
)
|
|
||||||
|
|
||||||
if(libmad_FOUND AND NOT TARGET libmad::mad)
|
|
||||||
add_library(libmad::mad UNKNOWN IMPORTED)
|
|
||||||
set_target_properties(libmad::mad
|
|
||||||
PROPERTIES
|
|
||||||
INTERFACE_INCLUDE_DIRECTORIES ${LIBMAD_INCLUDE_DIR}
|
|
||||||
IMPORTED_LOCATION ${LIBMAD_LIBRARY}
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
@@ -61,8 +61,6 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
|
|||||||
zstd
|
zstd
|
||||||
z
|
z
|
||||||
lzma
|
lzma
|
||||||
asnd
|
|
||||||
mad
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
|
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|||||||
|
|
||||||
# Link libraries
|
# Link libraries
|
||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
|
||||||
# bba
|
bba
|
||||||
)
|
)
|
||||||
|
|
||||||
# ISO post-build: produce NTSC-J, NTSC-U and PAL disc images
|
# ISO post-build: produce NTSC-J, NTSC-U and PAL disc images
|
||||||
|
|||||||
+4
-54
@@ -1,3 +1,7 @@
|
|||||||
|
if(NOT CMAKE_BUILD_TYPE)
|
||||||
|
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
|
||||||
|
endif()
|
||||||
|
|
||||||
set(CMAKE_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
set(CMAKE_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
||||||
set(CMAKE_RANLIB "$ENV{PSPDEV}/bin/psp-ranlib" CACHE FILEPATH "" FORCE)
|
set(CMAKE_RANLIB "$ENV{PSPDEV}/bin/psp-ranlib" CACHE FILEPATH "" FORCE)
|
||||||
set(CMAKE_C_COMPILER_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
set(CMAKE_C_COMPILER_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
||||||
@@ -30,7 +34,6 @@ target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
|||||||
pspgu
|
pspgu
|
||||||
pspaudio
|
pspaudio
|
||||||
pspaudiolib
|
pspaudiolib
|
||||||
pspmp3
|
|
||||||
psputility
|
psputility
|
||||||
pspvfpu
|
pspvfpu
|
||||||
pspvram
|
pspvram
|
||||||
@@ -56,33 +59,9 @@ target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
|||||||
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
|
|
||||||
DUSK_DISPLAY_OVERSCAN=6
|
DUSK_DISPLAY_OVERSCAN=6
|
||||||
)
|
)
|
||||||
|
|
||||||
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
|
|
||||||
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
|
||||||
DUSK_ASSERTIONS_FAKED
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# Generate PARAM.SFO as a normal tracked build output (instead of letting
|
|
||||||
# create_pbp_file() auto-generate + delete it) so it can be reused below by
|
|
||||||
# a properly dependency-tracked EBOOT.PBP repack step.
|
|
||||||
set(DUSK_PSP_PARAM_SFO "${DUSK_BUILD_DIR}/PARAM.SFO")
|
|
||||||
add_custom_command(
|
|
||||||
OUTPUT "${DUSK_PSP_PARAM_SFO}"
|
|
||||||
COMMAND "$ENV{PSPDEV}/bin/mksfoex" "-d" "MEMSIZE=1" "-s" "APP_VER=01.00"
|
|
||||||
"${DUSK_BINARY_TARGET_NAME}" "${DUSK_PSP_PARAM_SFO}"
|
|
||||||
COMMENT "Generating PARAM.SFO for ${DUSK_BINARY_TARGET_NAME}"
|
|
||||||
VERBATIM
|
|
||||||
)
|
|
||||||
add_custom_target(DuskPspParamSfo DEPENDS "${DUSK_PSP_PARAM_SFO}")
|
|
||||||
|
|
||||||
# create_pbp_file()'s own POST_BUILD chain (below) also consumes
|
|
||||||
# DUSK_PSP_PARAM_SFO, so make sure it exists before that chain runs.
|
|
||||||
add_dependencies(${DUSK_BINARY_TARGET_NAME} DuskPspParamSfo)
|
|
||||||
|
|
||||||
# Postbuild, create .pbp file for PSP.
|
# Postbuild, create .pbp file for PSP.
|
||||||
create_pbp_file(
|
create_pbp_file(
|
||||||
TARGET "${DUSK_BINARY_TARGET_NAME}"
|
TARGET "${DUSK_BINARY_TARGET_NAME}"
|
||||||
@@ -92,33 +71,4 @@ create_pbp_file(
|
|||||||
TITLE "${DUSK_BINARY_TARGET_NAME}"
|
TITLE "${DUSK_BINARY_TARGET_NAME}"
|
||||||
PSAR_PATH ${DUSK_ASSETS_ZIP}
|
PSAR_PATH ${DUSK_ASSETS_ZIP}
|
||||||
VERSION 01.00
|
VERSION 01.00
|
||||||
SFO_PATH "${DUSK_PSP_PARAM_SFO}"
|
|
||||||
OUTPUT_DIR "${DUSK_BUILD_DIR}"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# CreatePBP.cmake's pack-pbp step is a POST_BUILD command tied to the
|
|
||||||
# executable target, so it only reruns when the ELF itself relinks. That
|
|
||||||
# means regenerating dusk.dsk (assets) alone, without touching any C
|
|
||||||
# source, silently leaves EBOOT.PBP embedding a stale asset pak. Repack it
|
|
||||||
# here as a normal file-tracked custom command depending on both the
|
|
||||||
# executable and the asset zip, so EBOOT.PBP always reflects the current
|
|
||||||
# assets even when nothing else about the build changed.
|
|
||||||
set(DUSK_PSP_EBOOT "${DUSK_BUILD_DIR}/EBOOT.PBP")
|
|
||||||
if(BUILD_PRX)
|
|
||||||
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>.prx")
|
|
||||||
else()
|
|
||||||
set(DUSK_PSP_EXECUTABLE "$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>")
|
|
||||||
endif()
|
|
||||||
add_custom_command(
|
|
||||||
OUTPUT "${DUSK_PSP_EBOOT}"
|
|
||||||
COMMAND "$ENV{PSPDEV}/bin/pack-pbp" "${DUSK_PSP_EBOOT}" "${DUSK_PSP_PARAM_SFO}"
|
|
||||||
"NULL" "NULL" "NULL" "NULL" "NULL"
|
|
||||||
"${DUSK_PSP_EXECUTABLE}" "${DUSK_ASSETS_ZIP}"
|
|
||||||
DEPENDS
|
|
||||||
"$<TARGET_FILE:${DUSK_BINARY_TARGET_NAME}>"
|
|
||||||
"${DUSK_PSP_PARAM_SFO}"
|
|
||||||
"${DUSK_ASSETS_ZIP}"
|
|
||||||
COMMENT "Repacking EBOOT.PBP (tracks executable + asset pak freshness)"
|
|
||||||
VERBATIM
|
|
||||||
)
|
|
||||||
add_custom_target(DuskPspEbootRepack ALL DEPENDS "${DUSK_PSP_EBOOT}")
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
# Copyright (c) 2026 Dominic Masters
|
|
||||||
#
|
|
||||||
# This software is released under the MIT License.
|
|
||||||
# https://opensource.org/licenses/MIT
|
|
||||||
|
|
||||||
if(NOT DEFINED ENV{VITASDK})
|
|
||||||
message(FATAL_ERROR "VITASDK environment variable is not set.")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
include("$ENV{VITASDK}/share/vita.cmake" REQUIRED)
|
|
||||||
|
|
||||||
set(VITA_APP_NAME "Dusk")
|
|
||||||
set(VITA_TITLEID "DUSK00001")
|
|
||||||
set(VITA_VERSION "01.00")
|
|
||||||
|
|
||||||
find_package(SDL2 REQUIRED)
|
|
||||||
|
|
||||||
# Custom flags for cglm
|
|
||||||
set(CGLM_SHARED OFF CACHE BOOL "Build cglm shared" FORCE)
|
|
||||||
set(CGLM_STATIC ON CACHE BOOL "Build cglm static" FORCE)
|
|
||||||
find_package(cglm REQUIRED)
|
|
||||||
|
|
||||||
# Link libraries
|
|
||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|
||||||
${SDL2_LIBRARIES}
|
|
||||||
cglm
|
|
||||||
SDL2
|
|
||||||
SDL2main
|
|
||||||
zip
|
|
||||||
bz2
|
|
||||||
z
|
|
||||||
zstd
|
|
||||||
crypto
|
|
||||||
lzma
|
|
||||||
m
|
|
||||||
pthread
|
|
||||||
stdc++
|
|
||||||
vitaGL
|
|
||||||
mathneon
|
|
||||||
vitashark
|
|
||||||
kubridge_stub
|
|
||||||
SceAppMgr_stub
|
|
||||||
SceAudio_stub
|
|
||||||
SceCtrl_stub
|
|
||||||
SceCommonDialog_stub
|
|
||||||
SceDisplay_stub
|
|
||||||
SceKernelDmacMgr_stub
|
|
||||||
SceGxm_stub
|
|
||||||
SceShaccCg_stub
|
|
||||||
SceSysmodule_stub
|
|
||||||
ScePower_stub
|
|
||||||
SceTouch_stub
|
|
||||||
SceVshBridge_stub
|
|
||||||
SceIofilemgr_stub
|
|
||||||
SceShaccCgExt
|
|
||||||
libtaihen_stub.a
|
|
||||||
|
|
||||||
|
|
||||||
# SceKernel_stub
|
|
||||||
SceAppUtil_stub
|
|
||||||
SceHid_stub
|
|
||||||
SceRtc_stub
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
|
|
||||||
${SDL2_INCLUDE_DIRS}
|
|
||||||
)
|
|
||||||
|
|
||||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|
||||||
DUSK_SDL2
|
|
||||||
DUSK_OPENGL
|
|
||||||
DUSK_VITA
|
|
||||||
DUSK_INPUT_GAMEPAD
|
|
||||||
DUSK_PLATFORM_ENDIAN_LITTLE
|
|
||||||
DUSK_OPENGL_LEGACY
|
|
||||||
DUSK_DISPLAY_WIDTH=960
|
|
||||||
DUSK_DISPLAY_HEIGHT=544
|
|
||||||
)
|
|
||||||
|
|
||||||
# Post-build: create SELF from the ELF binary (UNSAFE = homebrew, no signing)
|
|
||||||
vita_create_self(${DUSK_BINARY_TARGET_NAME}.self ${DUSK_BINARY_TARGET_NAME} UNSAFE)
|
|
||||||
|
|
||||||
# Post-build: package SELF + assets into a .vpk installable on the Vita
|
|
||||||
vita_create_vpk(${DUSK_BINARY_TARGET_NAME}.vpk ${VITA_TITLEID} ${DUSK_BINARY_TARGET_NAME}.self
|
|
||||||
VERSION ${VITA_VERSION}
|
|
||||||
NAME ${VITA_APP_NAME}
|
|
||||||
FILE ${DUSK_ASSETS_ZIP} dusk.dsk
|
|
||||||
)
|
|
||||||
@@ -4,17 +4,6 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|||||||
DUSK_WII
|
DUSK_WII
|
||||||
)
|
)
|
||||||
|
|
||||||
# Wii save storage method - see src/duskdolphin/save/savedeviceplatform.h.
|
|
||||||
set(DUSK_SAVE_WII_METHOD "SD" CACHE STRING
|
|
||||||
"Wii save storage: NAND (internal storage via ISFS), CARD (GameCube-\
|
|
||||||
compatible memory card emulation), or SD (SD card via libfat)"
|
|
||||||
)
|
|
||||||
set_property(CACHE DUSK_SAVE_WII_METHOD PROPERTY STRINGS "NAND" "CARD" "SD")
|
|
||||||
|
|
||||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|
||||||
DUSK_SAVE_WII_METHOD_${DUSK_SAVE_WII_METHOD}
|
|
||||||
)
|
|
||||||
|
|
||||||
# Generate Homebrew Channel meta.xml from project identity variables
|
# Generate Homebrew Channel meta.xml from project identity variables
|
||||||
string(TIMESTAMP DUSK_BUILD_DATE "%Y%m%d000000" UTC)
|
string(TIMESTAMP DUSK_BUILD_DATE "%Y%m%d000000" UTC)
|
||||||
configure_file(
|
configure_file(
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
FROM ghcr.io/extremscorner/libogc2
|
||||||
|
WORKDIR /workdir
|
||||||
|
RUN apt update && \
|
||||||
|
dkp-pacman -Syu --noconfirm && \
|
||||||
|
apt install -y python3 python3-pip python3-polib python3-pil python3-dotenv python3-pyqt5 python3-opengl xorriso dolphin-emu xvfb && \
|
||||||
|
dkp-pacman -S --needed --noconfirm gamecube-sdl2 ppc-liblzma ppc-libzip libogc2 gamecube-tools ppc-libmad ppc-zlib-ng ppc-liblzma ppc-bzip2 ppc-zstd
|
||||||
|
VOLUME ["/workdir"]
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
FROM pspdev/pspdev:latest
|
||||||
|
WORKDIR /workdir
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
python3 \
|
||||||
|
py3-pip \
|
||||||
|
py3-dotenv \
|
||||||
|
git \
|
||||||
|
cmake \
|
||||||
|
make \
|
||||||
|
g++ \
|
||||||
|
sdl2-dev \
|
||||||
|
zlib-dev \
|
||||||
|
linux-headers
|
||||||
|
|
||||||
|
# PPSSPP has no Alpine/Linux distro package -- build the "PPSSPPHeadless"
|
||||||
|
# target (the CLI/no-window build PPSSPP's own CI uses for automated runs)
|
||||||
|
# from source instead. The target name and exact CMake options have moved
|
||||||
|
# around across PPSSPP versions -- if this breaks, check
|
||||||
|
# https://github.com/hrydgard/ppsspp's CMakeLists.txt for the current name.
|
||||||
|
RUN git clone --recursive --depth 1 \
|
||||||
|
https://github.com/hrydgard/ppsspp.git /opt/ppsspp && \
|
||||||
|
cd /opt/ppsspp && \
|
||||||
|
cmake -B build -DCMAKE_BUILD_TYPE=Release && \
|
||||||
|
cmake --build build --target PPSSPPHeadless -- -j$(nproc) && \
|
||||||
|
cp build/PPSSPPHeadless /usr/local/bin/PPSSPPHeadless && \
|
||||||
|
rm -rf /opt/ppsspp
|
||||||
|
|
||||||
|
VOLUME ["/workdir"]
|
||||||
Executable
+3
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
docker build -t dusk-dolphin-test -f docker/dolphin-test/Dockerfile .
|
||||||
|
docker run --rm -v "$(pwd):/workdir" dusk-dolphin-test /bin/bash -c "./scripts/test-gamecube-dolphin.sh"
|
||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if [ -z "$DEVKITPRO" ]; then
|
||||||
|
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
DOLPHIN_BIN="${DOLPHIN_BIN:-dolphin-emu}"
|
||||||
|
if ! command -v "$DOLPHIN_BIN" >/dev/null 2>&1; then
|
||||||
|
echo "$DOLPHIN_BIN not found. Install Dolphin Emulator (e.g. 'apt install dolphin-emu')"
|
||||||
|
echo "or set DOLPHIN_BIN to its path."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! command -v xvfb-run >/dev/null 2>&1; then
|
||||||
|
echo "xvfb-run not found. Install it (e.g. 'apt install xvfb') -- Dolphin's"
|
||||||
|
echo "Qt frontend needs a display even in batch mode."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
./scripts/build-gamecube-iso.sh
|
||||||
|
|
||||||
|
DUSK_TEST_DOLPHIN_SECONDS="${DUSK_TEST_DOLPHIN_SECONDS:-20}"
|
||||||
|
ISO="build-gamecube-iso/Dusk-NTSC-U.iso"
|
||||||
|
|
||||||
|
echo "Booting $ISO in Dolphin for up to ${DUSK_TEST_DOLPHIN_SECONDS}s (batch mode, headless via Xvfb)..."
|
||||||
|
|
||||||
|
# Dolphin's batch mode (-b -e) runs the disc until told to stop -- there's
|
||||||
|
# no "the game exited cleanly" signal to wait for, so we bound it with
|
||||||
|
# timeout and treat "still running when the clock ran out" as success.
|
||||||
|
set +e
|
||||||
|
xvfb-run -a timeout "${DUSK_TEST_DOLPHIN_SECONDS}" "$DOLPHIN_BIN" -b -e "$ISO"
|
||||||
|
status=$?
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# timeout returns 124 when it had to kill Dolphin after the duration
|
||||||
|
# elapsed -- that means the disc booted and kept running, the expected
|
||||||
|
# smoke-test-passed outcome, not a failure. Any other non-zero status
|
||||||
|
# means Dolphin crashed or refused to boot the disc.
|
||||||
|
if [ "$status" -ne 0 ] && [ "$status" -ne 124 ]; then
|
||||||
|
echo "Dolphin exited with unexpected status $status -- treating as a failure."
|
||||||
|
exit "$status"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "GameCube smoke test passed (Dolphin ran $ISO for ${DUSK_TEST_DOLPHIN_SECONDS}s without crashing)."
|
||||||
Executable
+3
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
docker build -t dusk-psp-test -f docker/psp-test/Dockerfile .
|
||||||
|
docker run --rm -v "$(pwd):/workdir" dusk-psp-test /bin/bash -c "./scripts/test-psp-ppsspp.sh"
|
||||||
Executable
+42
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if [ -z "$PSPDEV" ]; then
|
||||||
|
echo "PSPDEV environment variable is not set. Please set it to the path of your PSP development environment."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# PPSSPP doesn't ship a standard Linux package -- build its "PPSSPPHeadless"
|
||||||
|
# target from source (https://github.com/hrydgard/ppsspp) and either put it
|
||||||
|
# on PATH or point PPSSPP_HEADLESS_BIN at it. See docker/psp-test/Dockerfile
|
||||||
|
# for a from-scratch build.
|
||||||
|
PPSSPP_HEADLESS_BIN="${PPSSPP_HEADLESS_BIN:-PPSSPPHeadless}"
|
||||||
|
if ! command -v "$PPSSPP_HEADLESS_BIN" >/dev/null 2>&1; then
|
||||||
|
echo "$PPSSPP_HEADLESS_BIN not found. Build PPSSPP's 'PPSSPPHeadless' target"
|
||||||
|
echo "from source or set PPSSPP_HEADLESS_BIN to its path."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
./scripts/build-psp.sh
|
||||||
|
|
||||||
|
DUSK_TEST_PPSSPP_SECONDS="${DUSK_TEST_PPSSPP_SECONDS:-20}"
|
||||||
|
EBOOT="build-psp/EBOOT.PBP"
|
||||||
|
|
||||||
|
echo "Booting $EBOOT in PPSSPPHeadless (timeout ${DUSK_TEST_PPSSPP_SECONDS}s)..."
|
||||||
|
|
||||||
|
# PPSSPPHeadless is purpose-built for automated/CI runs -- it renders
|
||||||
|
# without a window and is expected to exit on its own once --timeout
|
||||||
|
# elapses, unlike Dolphin's batch mode which has to be killed externally.
|
||||||
|
# Check `"$PPSSPP_HEADLESS_BIN" --help` if these flags don't match your
|
||||||
|
# PPSSPP checkout -- the headless CLI has changed across versions.
|
||||||
|
set +e
|
||||||
|
"$PPSSPP_HEADLESS_BIN" --timeout="${DUSK_TEST_PPSSPP_SECONDS}" "$EBOOT"
|
||||||
|
status=$?
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if [ "$status" -ne 0 ]; then
|
||||||
|
echo "PPSSPPHeadless exited with status $status"
|
||||||
|
exit "$status"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "PSP smoke test passed (PPSSPPHeadless ran EBOOT.PBP for ${DUSK_TEST_PPSSPP_SECONDS}s without crashing)."
|
||||||
Executable
+3
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
docker build -t dusk-dolphin-test -f docker/dolphin-test/Dockerfile .
|
||||||
|
docker run --rm -v "$(pwd):/workdir" dusk-dolphin-test /bin/bash -c "./scripts/test-wii-dolphin.sh"
|
||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if [ -z "$DEVKITPRO" ]; then
|
||||||
|
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
DOLPHIN_BIN="${DOLPHIN_BIN:-dolphin-emu}"
|
||||||
|
if ! command -v "$DOLPHIN_BIN" >/dev/null 2>&1; then
|
||||||
|
echo "$DOLPHIN_BIN not found. Install Dolphin Emulator (e.g. 'apt install dolphin-emu')"
|
||||||
|
echo "or set DOLPHIN_BIN to its path."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! command -v xvfb-run >/dev/null 2>&1; then
|
||||||
|
echo "xvfb-run not found. Install it (e.g. 'apt install xvfb') -- Dolphin's"
|
||||||
|
echo "Qt frontend needs a display even in batch mode."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
./scripts/build-wii-iso.sh
|
||||||
|
|
||||||
|
DUSK_TEST_DOLPHIN_SECONDS="${DUSK_TEST_DOLPHIN_SECONDS:-20}"
|
||||||
|
ISO="build-wii-iso/Dusk-NTSC-U.iso"
|
||||||
|
|
||||||
|
echo "Booting $ISO in Dolphin for up to ${DUSK_TEST_DOLPHIN_SECONDS}s (batch mode, headless via Xvfb)..."
|
||||||
|
|
||||||
|
# Dolphin's batch mode (-b -e) runs the disc until told to stop -- there's
|
||||||
|
# no "the game exited cleanly" signal to wait for, so we bound it with
|
||||||
|
# timeout and treat "still running when the clock ran out" as success.
|
||||||
|
set +e
|
||||||
|
xvfb-run -a timeout "${DUSK_TEST_DOLPHIN_SECONDS}" "$DOLPHIN_BIN" -b -e "$ISO"
|
||||||
|
status=$?
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# timeout returns 124 when it had to kill Dolphin after the duration
|
||||||
|
# elapsed -- that means the disc booted and kept running, the expected
|
||||||
|
# smoke-test-passed outcome, not a failure. Any other non-zero status
|
||||||
|
# means Dolphin crashed or refused to boot the disc.
|
||||||
|
if [ "$status" -ne 0 ] && [ "$status" -ne 124 ]; then
|
||||||
|
echo "Dolphin exited with unexpected status $status -- treating as a failure."
|
||||||
|
exit "$status"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Wii smoke test passed (Dolphin ran $ISO for ${DUSK_TEST_DOLPHIN_SECONDS}s without crashing)."
|
||||||
+2
-15
@@ -4,32 +4,19 @@
|
|||||||
# https://opensource.org/licenses/MIT
|
# https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
add_subdirectory(dusk)
|
add_subdirectory(dusk)
|
||||||
|
add_subdirectory(duskrpg)
|
||||||
if(DUSK_NETWORK)
|
|
||||||
add_subdirectory(dusknetwork)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
|
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
|
||||||
add_subdirectory(dusklinux)
|
add_subdirectory(dusklinux)
|
||||||
add_subdirectory(dusksdl2)
|
add_subdirectory(dusksdl2)
|
||||||
add_subdirectory(duskgl)
|
add_subdirectory(duskgl)
|
||||||
add_subdirectory(duskmad)
|
|
||||||
|
|
||||||
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)
|
add_subdirectory(duskgl)
|
||||||
|
|
||||||
elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
|
elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube")
|
||||||
add_subdirectory(duskvita)
|
|
||||||
add_subdirectory(dusksdl2)
|
|
||||||
add_subdirectory(duskgl)
|
|
||||||
|
|
||||||
elseif(
|
|
||||||
DUSK_TARGET_SYSTEM STREQUAL "wii" OR
|
|
||||||
DUSK_TARGET_SYSTEM STREQUAL "gamecube"
|
|
||||||
)
|
|
||||||
add_subdirectory(duskdolphin)
|
add_subdirectory(duskdolphin)
|
||||||
add_subdirectory(duskmad)
|
|
||||||
|
|
||||||
endif()
|
endif()
|
||||||
+17
-15
@@ -14,21 +14,12 @@ if(NOT libzip_FOUND)
|
|||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC zip)
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC zip)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# assetdsk.c calls crc32() directly (to verify dusk.dsk archive checksums).
|
|
||||||
# find_package(libzip) above already resolves ZLIB as a side effect, so
|
|
||||||
# ZLIB_FOUND may already be true without ZLIB::ZLIB having been linked to
|
|
||||||
# our target - link it unconditionally rather than guarding on ZLIB_FOUND.
|
|
||||||
find_package(ZLIB REQUIRED)
|
|
||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC ZLIB::ZLIB)
|
|
||||||
|
|
||||||
if(NOT stb_image_FOUND)
|
if(NOT stb_image_FOUND)
|
||||||
find_package(stb REQUIRED)
|
find_package(stb REQUIRED)
|
||||||
if(STB_IMAGE_FOUND)
|
if(STB_IMAGE_FOUND)
|
||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC stb_image)
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC stb_image)
|
||||||
else()
|
else()
|
||||||
message(FATAL_ERROR
|
message(FATAL_ERROR "stb_image not found. Please ensure stb is correctly fetched.")
|
||||||
"stb_image not found. Please ensure stb is correctly fetched."
|
|
||||||
)
|
|
||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
@@ -37,12 +28,19 @@ if(NOT yyjson_FOUND)
|
|||||||
if(yyjson_FOUND)
|
if(yyjson_FOUND)
|
||||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC yyjson::yyjson)
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC yyjson::yyjson)
|
||||||
else()
|
else()
|
||||||
message(FATAL_ERROR
|
message(FATAL_ERROR "yyjson not found. Please ensure yyjson is correctly fetched.")
|
||||||
"yyjson not found. Please ensure yyjson is correctly fetched."
|
|
||||||
)
|
|
||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
if(NOT jerryscript_FOUND)
|
||||||
|
find_package(jerryscript REQUIRED)
|
||||||
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||||
|
jerryscript::core
|
||||||
|
jerryscript::ext
|
||||||
|
jerryscript::port
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
if(DUSK_BACKTRACE)
|
if(DUSK_BACKTRACE)
|
||||||
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
|
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
|
||||||
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
||||||
@@ -64,21 +62,25 @@ target_sources(${DUSK_BINARY_TARGET_NAME}
|
|||||||
|
|
||||||
# Subdirs
|
# Subdirs
|
||||||
add_subdirectory(animation)
|
add_subdirectory(animation)
|
||||||
|
add_subdirectory(event)
|
||||||
add_subdirectory(assert)
|
add_subdirectory(assert)
|
||||||
add_subdirectory(asset)
|
add_subdirectory(asset)
|
||||||
add_subdirectory(audio)
|
|
||||||
add_subdirectory(console)
|
add_subdirectory(console)
|
||||||
add_subdirectory(display)
|
add_subdirectory(display)
|
||||||
|
add_subdirectory(entity)
|
||||||
add_subdirectory(log)
|
add_subdirectory(log)
|
||||||
add_subdirectory(engine)
|
add_subdirectory(engine)
|
||||||
add_subdirectory(error)
|
add_subdirectory(error)
|
||||||
|
add_subdirectory(game)
|
||||||
add_subdirectory(input)
|
add_subdirectory(input)
|
||||||
add_subdirectory(locale)
|
add_subdirectory(locale)
|
||||||
add_subdirectory(rpg)
|
|
||||||
add_subdirectory(scene)
|
add_subdirectory(scene)
|
||||||
add_subdirectory(system)
|
add_subdirectory(system)
|
||||||
add_subdirectory(time)
|
add_subdirectory(time)
|
||||||
add_subdirectory(ui)
|
add_subdirectory(ui)
|
||||||
|
add_subdirectory(network)
|
||||||
|
add_subdirectory(physics)
|
||||||
add_subdirectory(save)
|
add_subdirectory(save)
|
||||||
|
add_subdirectory(script)
|
||||||
add_subdirectory(util)
|
add_subdirectory(util)
|
||||||
add_subdirectory(thread)
|
add_subdirectory(thread)
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
easing.c
|
easing.c
|
||||||
animation.c
|
|
||||||
keyframe.c
|
keyframe.c
|
||||||
|
keyframeset.c
|
||||||
|
animation.c
|
||||||
)
|
)
|
||||||
+56
-116
@@ -1,134 +1,74 @@
|
|||||||
/**
|
// Copyright (c) 2026 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
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "animation.h"
|
#include "animation.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/math.h"
|
#include "util/math.h"
|
||||||
|
#include "time/time.h"
|
||||||
|
|
||||||
void animationInit(
|
void animationInit(
|
||||||
animation_t *anim,
|
animation_t *anim,
|
||||||
keyframe_t *keyframes,
|
keyframe_t **tracks,
|
||||||
uint16_t *keyframeCounts,
|
uint16_t *trackCounts,
|
||||||
const uint16_t layerCount
|
uint16_t trackCount
|
||||||
) {
|
) {
|
||||||
assertNotNull(anim, "Animation pointer cannot be NULL.");
|
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||||
assertNotNull(keyframes, "Keyframes pointer cannot be NULL.");
|
|
||||||
assertNotNull(keyframeCounts, "Keyframe counts pointer cannot be NULL.");
|
|
||||||
assertTrue(layerCount > 0, "Layer count must be greater than zero.");
|
|
||||||
|
|
||||||
memoryZero(anim, sizeof(animation_t));
|
keyframeSetInit(
|
||||||
anim->keyframes = keyframes;
|
&anim->keyframes, tracks, trackCounts, NULL, NULL, trackCount, NULL
|
||||||
anim->keyframeCounts = keyframeCounts;
|
);
|
||||||
anim->layerCount = layerCount;
|
anim->time = 0.0f;
|
||||||
|
anim->speed = 1.0f;
|
||||||
|
anim->loop = false;
|
||||||
|
anim->playing = false;
|
||||||
|
anim->eventTime = 0.0f;
|
||||||
|
anim->eventCallback = NULL;
|
||||||
|
anim->eventUser = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
// Determine duration
|
void animationUpdate(animation_t *anim) {
|
||||||
float_t duration = 0.0f;
|
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||||
for(uint16_t layer = 0; layer < layerCount; layer++) {
|
if(!anim->playing) return;
|
||||||
uint16_t keyframeCount = keyframeCounts[layer];
|
|
||||||
assertTrue(keyframeCount > 0, "Keyframe count invalid.");
|
|
||||||
keyframe_t *layerKeyframes = keyframes + layer * keyframeCount;
|
|
||||||
|
|
||||||
#ifdef DUSK_ASSERTIONS
|
float_t duration = keyframeSetGetDuration(&anim->keyframes);
|
||||||
// Check that the keyframes are sorted by time.
|
float_t prevTime = anim->time;
|
||||||
for(uint16_t i = 1; i < keyframeCount; i++) {
|
anim->time += TIME.delta * anim->speed;
|
||||||
assertTrue(
|
|
||||||
layerKeyframes[i].time >= layerKeyframes[i - 1].time,
|
|
||||||
"Keyframes must be sorted by time."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
keyframe_t *lastKeyframe = layerKeyframes + keyframeCount - 1;
|
// Loops that overshoot duration wrap back into [0, duration) -- an event
|
||||||
duration = mathMax(duration, lastKeyframe->time);
|
// near the end must still be checked across that wrap, as two segments:
|
||||||
|
// (prevTime, duration] then [0, newTime].
|
||||||
|
bool_t wrapped = anim->loop && duration > 0.0f && anim->time >= duration;
|
||||||
|
|
||||||
|
if(anim->loop) {
|
||||||
|
if(duration > 0.0f) anim->time = mathModFloat(anim->time, duration);
|
||||||
|
} else if(anim->time >= duration) {
|
||||||
|
anim->time = duration;
|
||||||
|
anim->playing = false;
|
||||||
}
|
}
|
||||||
assertTrue(duration > 0, "Animation duration must be greater than 0.");
|
|
||||||
anim->duration = duration;
|
if(!anim->eventCallback) return;
|
||||||
|
|
||||||
|
bool_t crossed = wrapped
|
||||||
|
? (prevTime < anim->eventTime || anim->time >= anim->eventTime)
|
||||||
|
: (prevTime < anim->eventTime && anim->time >= anim->eventTime);
|
||||||
|
if(crossed) anim->eventCallback(anim, anim->eventUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer) {
|
void animationSetEvent(
|
||||||
assertNotNull(anim, "Animation pointer cannot be NULL.");
|
|
||||||
assertTrue(layer < anim->layerCount, "Layer index out of bounds.");
|
|
||||||
|
|
||||||
uint16_t keyframeCount = anim->keyframeCounts[layer];
|
|
||||||
keyframe_t *layerKeyframes = anim->keyframes + layer * keyframeCount;
|
|
||||||
return keyframeGetValue(layerKeyframes, keyframeCount, anim->time);
|
|
||||||
}
|
|
||||||
|
|
||||||
void animationUpdate(
|
|
||||||
animation_t *anim,
|
animation_t *anim,
|
||||||
const float_t deltaTime
|
const float_t time,
|
||||||
|
const animationeventcallback_t callback,
|
||||||
|
void *user
|
||||||
) {
|
) {
|
||||||
assertNotNull(anim, "Animation pointer cannot be NULL.");
|
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||||
assertTrue(deltaTime >= 0, "Delta time must be non-negative.");
|
anim->eventTime = time;
|
||||||
|
anim->eventCallback = callback;
|
||||||
bool_t justCompleted = false;
|
anim->eventUser = user;
|
||||||
|
}
|
||||||
if(!(anim->flags & ANIMATION_FLAG_INTERNAL_COMPLETED)) {
|
|
||||||
bool_t loop = (anim->flags & ANIMATION_FLAG_LOOP) != 0;
|
float_t animationGetValue(animation_t *anim, const uint16_t trackIndex) {
|
||||||
bool_t pingpong = (anim->flags & ANIMATION_FLAG_PINGPONG) != 0;
|
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||||
assertFalse(
|
return keyframeSetGetValue(&anim->keyframes, trackIndex, anim->time);
|
||||||
loop && pingpong,
|
|
||||||
"Cannot set both ANIMATION_FLAG_LOOP and ANIMATION_FLAG_PINGPONG."
|
|
||||||
);
|
|
||||||
|
|
||||||
bool_t backward;
|
|
||||||
if(pingpong) {
|
|
||||||
backward = (anim->flags & ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD) != 0;
|
|
||||||
} else {
|
|
||||||
backward = (anim->flags & ANIMATION_FLAG_REVERSE) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resolve boundary crossings one at a time, so a single large deltaTime
|
|
||||||
// can correctly loop/pingpong across multiple boundaries in one call.
|
|
||||||
float_t remaining = deltaTime;
|
|
||||||
while(remaining > 0.0f) {
|
|
||||||
float_t toBoundary = (
|
|
||||||
backward ? anim->time : (anim->duration - anim->time)
|
|
||||||
);
|
|
||||||
if(remaining < toBoundary) {
|
|
||||||
anim->time += backward ? -remaining : remaining;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
remaining -= toBoundary;
|
|
||||||
anim->time = backward ? 0.0f : anim->duration;
|
|
||||||
|
|
||||||
bool_t stopHere;
|
|
||||||
if(backward) {
|
|
||||||
stopHere = (anim->flags & ANIMATION_FLAG_STOP_BEGINNING) != 0;
|
|
||||||
} else {
|
|
||||||
stopHere = (anim->flags & ANIMATION_FLAG_STOP_END) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(stopHere) {
|
|
||||||
justCompleted = true;
|
|
||||||
break;
|
|
||||||
} else if(pingpong) {
|
|
||||||
backward = !backward;
|
|
||||||
if(backward) anim->flags |= ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD;
|
|
||||||
else anim->flags &= ~ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD;
|
|
||||||
} else if(loop) {
|
|
||||||
anim->time = backward ? anim->duration : 0.0f;
|
|
||||||
if(anim->onLoop) anim->onLoop(anim->user);
|
|
||||||
} else {
|
|
||||||
justCompleted = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if(justCompleted) anim->flags |= ANIMATION_FLAG_INTERNAL_COMPLETED;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call onUpdate for each layer.
|
|
||||||
for(uint16_t layer = 0; layer < anim->layerCount; layer++) {
|
|
||||||
float_t value = animationGetLayerValue(anim, layer);
|
|
||||||
if(anim->onUpdate) anim->onUpdate(layer, value, anim->user);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(justCompleted && anim->onComplete) anim->onComplete(anim->user);
|
|
||||||
}
|
}
|
||||||
@@ -1,96 +1,102 @@
|
|||||||
/**
|
// Copyright (c) 2026 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
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "keyframe.h"
|
#include "keyframeset.h"
|
||||||
|
|
||||||
#define ANIMATION_FLAG_LOOP (1 << 0)
|
typedef struct animation_t animation_t;
|
||||||
#define ANIMATION_FLAG_REVERSE (1 << 1)
|
|
||||||
#define ANIMATION_FLAG_PINGPONG (1 << 2)
|
|
||||||
#define ANIMATION_FLAG_STOP_BEGINNING (1 << 3)
|
|
||||||
#define ANIMATION_FLAG_STOP_END (1 << 4)
|
|
||||||
|
|
||||||
// Internal - tracks which direction a pingponging animation is currently
|
/**
|
||||||
// travelling. Do not set this manually, it is managed by animationUpdate().
|
* Callback fired once when animationUpdate() advances time past
|
||||||
#define ANIMATION_FLAG_INTERNAL_PINGPONG_BACKWARD (1 << 7)
|
* eventTime (see animationSetEvent()).
|
||||||
|
*
|
||||||
|
* @param anim The animation whose event fired.
|
||||||
|
* @param user The user pointer passed to animationSetEvent().
|
||||||
|
*/
|
||||||
|
typedef void (*animationeventcallback_t)(animation_t *anim, void *user);
|
||||||
|
|
||||||
// Internal - set once the animation has stopped advancing (see
|
typedef struct animation_t {
|
||||||
// animationUpdate()). Do not set this manually. There is currently no way to
|
/** The animation's tracks/channels and their raw keyframe data. */
|
||||||
// restart a completed animation short of clearing this bit and resetting
|
keyframeset_t keyframes;
|
||||||
// anim->time by hand.
|
|
||||||
#define ANIMATION_FLAG_INTERNAL_COMPLETED (1 << 6)
|
|
||||||
|
|
||||||
typedef struct {
|
/** Current playback position, in seconds. */
|
||||||
keyframe_t *keyframes;
|
|
||||||
uint16_t *keyframeCounts;
|
|
||||||
uint16_t layerCount;
|
|
||||||
float_t time;
|
float_t time;
|
||||||
float_t duration;
|
|
||||||
uint8_t flags;
|
|
||||||
|
|
||||||
void *user;
|
/** Playback rate multiplier; 1.0 = normal speed. */
|
||||||
void (*onUpdate)(const uint16_t layer, const float_t value, void *user);
|
float_t speed;
|
||||||
void (*onComplete)(void *user);
|
|
||||||
void (*onLoop)(void *user);
|
/** True if animationUpdate() should wrap time back to 0 on reaching the
|
||||||
|
* final keyframe, rather than holding there and clearing playing. */
|
||||||
|
bool_t loop;
|
||||||
|
|
||||||
|
/** True while animationUpdate() should advance time each call. */
|
||||||
|
bool_t playing;
|
||||||
|
|
||||||
|
/** Time (seconds) at which eventCallback fires; see animationSetEvent(). */
|
||||||
|
float_t eventTime;
|
||||||
|
/** Callback fired once when time advances past eventTime, or NULL. */
|
||||||
|
animationeventcallback_t eventCallback;
|
||||||
|
/** User pointer passed to eventCallback unchanged. */
|
||||||
|
void *eventUser;
|
||||||
} animation_t;
|
} animation_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes an animation with the given keyframes and layer count.
|
* Initializes an animation: time 0, speed 1.0, not looping, not playing.
|
||||||
|
* See keyframeSetInit() -- tracks/trackCounts and the keyframe_t arrays
|
||||||
|
* they point to are not copied, and must outlive this animation.
|
||||||
*
|
*
|
||||||
* @param anim Pointer to the animation to initialize.
|
* @param anim The animation to initialize.
|
||||||
* @param keyframes Pointer to the array of keyframes for each layer.
|
* @param tracks Array of trackCount keyframe_t arrays.
|
||||||
* @param keyframeCount Number of keyframes in each layer.
|
* @param trackCounts Array of trackCount keyframe counts, matching tracks.
|
||||||
* @param layerCount Number of layers in the animation.
|
* @param trackCount The number of tracks/channels in this animation.
|
||||||
*/
|
*/
|
||||||
void animationInit(
|
void animationInit(
|
||||||
animation_t *anim,
|
animation_t *anim,
|
||||||
keyframe_t *keyframes,
|
keyframe_t **tracks,
|
||||||
uint16_t *keyframeCounts,
|
uint16_t *trackCounts,
|
||||||
const uint16_t layerCount
|
uint16_t trackCount
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the current time of the animation, clamping it to the valid range.
|
* Advances an animation's time by TIME.delta * speed. No-op if not
|
||||||
* This will call the onUpdate callback but none of the other callbacks.
|
* playing. Duration is the latest of every track's final keyframe time
|
||||||
|
* (see keyframeSetGetDuration()). If loop is set, time wraps back into
|
||||||
|
* [0, duration) on reaching it; otherwise time is clamped there and
|
||||||
|
* playing is cleared.
|
||||||
*
|
*
|
||||||
* @param anim Pointer to the animation to set the time for.
|
* If eventCallback is set, it fires once when this call advances time
|
||||||
* @param time The new time to set for the animation.
|
* from at or before eventTime to after it (checked across the loop wrap
|
||||||
|
* point too, so an event near the end of a looping animation still fires
|
||||||
|
* every loop).
|
||||||
|
*
|
||||||
|
* @param anim The animation to update.
|
||||||
*/
|
*/
|
||||||
void animationSetTime(animation_t *anim, const float_t time);
|
void animationUpdate(animation_t *anim);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the current value of a specific layer in the animation based on the
|
* Sets (or clears, with callback NULL) the single time-triggered event
|
||||||
* current animation time.
|
* fired by animationUpdate().
|
||||||
|
*
|
||||||
|
* @param anim The animation to set the event on.
|
||||||
|
* @param time The time, in seconds, at which callback fires.
|
||||||
|
* @param callback The callback to invoke, or NULL to clear any event.
|
||||||
|
* @param user Arbitrary pointer forwarded to callback unchanged.
|
||||||
*/
|
*/
|
||||||
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer);
|
void animationSetEvent(
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the animation state based on the elapsed time. Advances anim->time
|
|
||||||
* by deltaTime (or against it, if ANIMATION_FLAG_REVERSE is set), then
|
|
||||||
* resolves whatever happens when it reaches the 0 or duration boundary:
|
|
||||||
*
|
|
||||||
* - ANIMATION_FLAG_PINGPONG: reflects off the boundary and continues playing
|
|
||||||
* in the opposite direction, forever, unless stopped (see below).
|
|
||||||
* - ANIMATION_FLAG_LOOP: wraps back around to the other boundary and keeps
|
|
||||||
* playing in the same direction, forever, unless stopped (see below).
|
|
||||||
* - ANIMATION_FLAG_STOP_BEGINNING / ANIMATION_FLAG_STOP_END: when the
|
|
||||||
* animation reaches that specific boundary, it clamps there and stops
|
|
||||||
* (firing onComplete) instead of looping/pingponging past it.
|
|
||||||
* - If none of the above apply at a boundary, the animation clamps there and
|
|
||||||
* stops, firing onComplete.
|
|
||||||
*
|
|
||||||
* onUpdate is called for every layer on every call. onLoop is called each
|
|
||||||
* time a loop wraps around. onComplete is called at most once, the moment
|
|
||||||
* the animation stops advancing.
|
|
||||||
*
|
|
||||||
* @param anim Pointer to the animation to update.
|
|
||||||
* @param deltaTime Time elapsed since the last update (in seconds).
|
|
||||||
*/
|
|
||||||
void animationUpdate(
|
|
||||||
animation_t *anim,
|
animation_t *anim,
|
||||||
const float_t deltaTime
|
const float_t time,
|
||||||
|
const animationeventcallback_t callback,
|
||||||
|
void *user
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the value of one of the animation's tracks at its current
|
||||||
|
* playback time.
|
||||||
|
*
|
||||||
|
* @param anim The animation to get the value from.
|
||||||
|
* @param trackIndex The track to evaluate, in [0, trackCount).
|
||||||
|
* @return The interpolated value of that track at the current time.
|
||||||
|
*/
|
||||||
|
float_t animationGetValue(animation_t *anim, const uint16_t trackIndex);
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
/**
|
// Copyright (c) 2026 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
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "easing.h"
|
#include "easing.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
|
|||||||
+4
-123
@@ -1,9 +1,7 @@
|
|||||||
/**
|
// Copyright (c) 2026 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
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "dusk.h"
|
#include "dusk.h"
|
||||||
@@ -47,136 +45,19 @@ extern const easingfn_t EASING_FUNCTIONS[EASING_COUNT];
|
|||||||
*/
|
*/
|
||||||
float_t easingApply(const easingtype_t type, const float_t t);
|
float_t easingApply(const easingtype_t type, const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* No easing - returns t unchanged.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, equal to t.
|
|
||||||
*/
|
|
||||||
float_t easingLinear(const float_t t);
|
float_t easingLinear(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Sinusoidal easing in: starts slow, accelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInSine(const float_t t);
|
float_t easingInSine(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Sinusoidal easing out: starts fast, decelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingOutSine(const float_t t);
|
float_t easingOutSine(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Sinusoidal easing in and out: slow at both ends, fastest in
|
|
||||||
* the middle.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInOutSine(const float_t t);
|
float_t easingInOutSine(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Quadratic easing in: starts slow, accelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInQuad(const float_t t);
|
float_t easingInQuad(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Quadratic easing out: starts fast, decelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingOutQuad(const float_t t);
|
float_t easingOutQuad(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Quadratic easing in and out: slow at both ends, fastest in the
|
|
||||||
* middle.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInOutQuad(const float_t t);
|
float_t easingInOutQuad(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Cubic easing in: starts slow, accelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInCubic(const float_t t);
|
float_t easingInCubic(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Cubic easing out: starts fast, decelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingOutCubic(const float_t t);
|
float_t easingOutCubic(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Cubic easing in and out: slow at both ends, fastest in the
|
|
||||||
* middle.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInOutCubic(const float_t t);
|
float_t easingInOutCubic(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Quartic easing in: starts slow, accelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInQuart(const float_t t);
|
float_t easingInQuart(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Quartic easing out: starts fast, decelerates to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingOutQuart(const float_t t);
|
float_t easingOutQuart(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Quartic easing in and out: slow at both ends, fastest in the
|
|
||||||
* middle.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, in the range [0, 1].
|
|
||||||
*/
|
|
||||||
float_t easingInOutQuart(const float_t t);
|
float_t easingInOutQuart(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Back easing in: overshoots backwards before moving to the end.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, which may fall below 0.
|
|
||||||
*/
|
|
||||||
float_t easingInBack(const float_t t);
|
float_t easingInBack(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Back easing out: overshoots past the end before settling on it.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, which may rise above 1.
|
|
||||||
*/
|
|
||||||
float_t easingOutBack(const float_t t);
|
float_t easingOutBack(const float_t t);
|
||||||
|
|
||||||
/**
|
|
||||||
* Back easing in and out: overshoots backwards at the start and
|
|
||||||
* past the end before settling on it.
|
|
||||||
*
|
|
||||||
* @param t The input time, in the range [0, 1].
|
|
||||||
* @return The eased value, which may fall below 0 or rise above 1.
|
|
||||||
*/
|
|
||||||
float_t easingInOutBack(const float_t t);
|
float_t easingInOutBack(const float_t t);
|
||||||
|
|
||||||
@@ -1,44 +1,42 @@
|
|||||||
/**
|
// Copyright (c) 2026 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
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "keyframe.h"
|
#include "keyframe.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "util/math.h"
|
#include "util/math.h"
|
||||||
|
|
||||||
float_t keyframeGetValue(
|
float_t keyframeGetValue(
|
||||||
const keyframe_t *keyframes,
|
keyframe_t *keyframes,
|
||||||
const uint32_t keyframeCount,
|
const uint16_t keyframeCount,
|
||||||
const float_t time
|
const float_t time
|
||||||
) {
|
) {
|
||||||
assertNotNull(keyframes, "Keyframes pointer cannot be NULL.");
|
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
|
||||||
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
|
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
|
||||||
assertTrue(time >= 0, "Time must be non-negative.");
|
assertTrue(time >= 0, "Time must be non-negative.");
|
||||||
#ifdef DUSK_ASSERTIONS
|
|
||||||
// Checks that the keyframes are sorted by time.
|
|
||||||
for(uint32_t i = 1; i < keyframeCount; i++) {
|
|
||||||
assertTrue(
|
|
||||||
keyframes[i].time >= keyframes[i - 1].time,
|
|
||||||
"Keyframes must be sorted by time."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
keyframe_t *last = (keyframe_t *)(keyframes + keyframeCount - 1);
|
keyframe_t *first = keyframes;
|
||||||
|
keyframe_t *last = keyframes + keyframeCount - 1;
|
||||||
|
|
||||||
|
// Clamp to the boundary keyframes' values directly rather than
|
||||||
|
// interpolating -- start == end at either boundary would otherwise
|
||||||
|
// divide by zero.
|
||||||
|
if(time <= first->time) return first->value;
|
||||||
if(time >= last->time) return last->value;
|
if(time >= last->time) return last->value;
|
||||||
|
|
||||||
// Since time < last->time (checked above), current is guaranteed to stop
|
keyframe_t *start = first;
|
||||||
// at or before reaching last, so no separate end-of-array check is needed.
|
keyframe_t *end;
|
||||||
keyframe_t *current = (keyframe_t *)keyframes;
|
keyframe_t *current = first;
|
||||||
keyframe_t *start = current;
|
|
||||||
while(current->time <= time) {
|
do {
|
||||||
|
if(current->time > time) {
|
||||||
|
end = current;
|
||||||
|
break;
|
||||||
|
}
|
||||||
start = current;
|
start = current;
|
||||||
current++;
|
current++;
|
||||||
}
|
} while(true);
|
||||||
keyframe_t *end = current;
|
|
||||||
|
|
||||||
float_t t = (time - start->time) / (end->time - start->time);
|
float_t t = (time - start->time) / (end->time - start->time);
|
||||||
return mathLerp(start->value, end->value, easingApply(start->easing, t));
|
return mathLerp(start->value, end->value, easingApply(start->easing, t));
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
/**
|
// Copyright (c) 2026 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
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "easing.h"
|
#include "easing.h"
|
||||||
@@ -15,15 +13,15 @@ typedef struct {
|
|||||||
} keyframe_t;
|
} keyframe_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the value of a keyframe at a given time.
|
* Gets the eased, interpolated value of a keyframe array at a given time.
|
||||||
*
|
*
|
||||||
* @param keyframes The keyframes to get the value from.
|
* @param keyframes The keyframes to evaluate, ascending by time.
|
||||||
* @param keyframeCount The number of keyframes in the array.
|
* @param keyframeCount The number of keyframes.
|
||||||
* @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 keyframe at the given time.
|
* @return The interpolated value at the given time.
|
||||||
*/
|
*/
|
||||||
float_t keyframeGetValue(
|
float_t keyframeGetValue(
|
||||||
const keyframe_t *keyframes,
|
keyframe_t *keyframes,
|
||||||
const uint32_t keyframeCount,
|
const uint16_t keyframeCount,
|
||||||
const float_t time
|
const float_t time
|
||||||
);
|
);
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Copyright (c) 2026 Dominic Masters
|
||||||
|
//
|
||||||
|
// This software is released under the MIT License.
|
||||||
|
// https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
#include "keyframeset.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
|
||||||
|
void keyframeSetInit(
|
||||||
|
keyframeset_t *set,
|
||||||
|
keyframe_t **tracks,
|
||||||
|
uint16_t *trackCounts,
|
||||||
|
keyframesetcallback_t *callbacks,
|
||||||
|
void **users,
|
||||||
|
uint16_t trackCount,
|
||||||
|
void *user
|
||||||
|
) {
|
||||||
|
assertNotNull(set, "Keyframe set pointer cannot be null.");
|
||||||
|
assertNotNull(tracks, "Tracks pointer cannot be null.");
|
||||||
|
assertNotNull(trackCounts, "Track counts pointer cannot be null.");
|
||||||
|
assertTrue(trackCount > 0, "Track count must be more than 0.");
|
||||||
|
|
||||||
|
set->tracks = tracks;
|
||||||
|
set->trackCounts = trackCounts;
|
||||||
|
set->trackCount = trackCount;
|
||||||
|
set->callbacks = callbacks;
|
||||||
|
set->users = users;
|
||||||
|
set->user = user;
|
||||||
|
}
|
||||||
|
|
||||||
|
float_t keyframeSetGetValue(
|
||||||
|
keyframeset_t *set,
|
||||||
|
const uint16_t trackIndex,
|
||||||
|
const float_t time
|
||||||
|
) {
|
||||||
|
assertNotNull(set, "Keyframe set pointer cannot be null.");
|
||||||
|
assertTrue(trackIndex < set->trackCount, "Track index out of bounds.");
|
||||||
|
|
||||||
|
return keyframeGetValue(
|
||||||
|
set->tracks[trackIndex], set->trackCounts[trackIndex], time
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void keyframeSetGetValues(
|
||||||
|
keyframeset_t *set,
|
||||||
|
const float_t time,
|
||||||
|
float_t *outValues
|
||||||
|
) {
|
||||||
|
assertNotNull(set, "Keyframe set pointer cannot be null.");
|
||||||
|
assertNotNull(outValues, "Output values pointer cannot be null.");
|
||||||
|
|
||||||
|
for(uint16_t i = 0; i < set->trackCount; i++) {
|
||||||
|
outValues[i] = keyframeGetValue(set->tracks[i], set->trackCounts[i], time);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
float_t keyframeSetGetDuration(keyframeset_t *set) {
|
||||||
|
assertNotNull(set, "Keyframe set pointer cannot be null.");
|
||||||
|
|
||||||
|
float_t duration = 0.0f;
|
||||||
|
for(uint16_t i = 0; i < set->trackCount; i++) {
|
||||||
|
float_t trackDuration = set->tracks[i][set->trackCounts[i] - 1].time;
|
||||||
|
if(trackDuration > duration) duration = trackDuration;
|
||||||
|
}
|
||||||
|
return duration;
|
||||||
|
}
|
||||||
|
|
||||||
|
void keyframeSetFireCallback(keyframeset_t *set, const uint16_t trackIndex) {
|
||||||
|
assertNotNull(set, "Keyframe set pointer cannot be null.");
|
||||||
|
assertTrue(trackIndex < set->trackCount, "Track index out of bounds.");
|
||||||
|
|
||||||
|
if(!set->callbacks || !set->callbacks[trackIndex]) return;
|
||||||
|
set->callbacks[trackIndex](
|
||||||
|
set, trackIndex, set->users ? set->users[trackIndex] : NULL
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
// Copyright (c) 2026 Dominic Masters
|
||||||
|
//
|
||||||
|
// This software is released under the MIT License.
|
||||||
|
// https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "keyframe.h"
|
||||||
|
|
||||||
|
typedef struct keyframeset_t keyframeset_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callback associated with one track of a keyframe set (see
|
||||||
|
* keyframeSetFireCallback()).
|
||||||
|
*
|
||||||
|
* @param set The keyframe set the track belongs to.
|
||||||
|
* @param trackIndex The track this callback is registered for.
|
||||||
|
* @param user The per-track user pointer passed to keyframeSetInit().
|
||||||
|
*/
|
||||||
|
typedef void (*keyframesetcallback_t)(
|
||||||
|
keyframeset_t *set,
|
||||||
|
const uint16_t trackIndex,
|
||||||
|
void *user
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A group of N parallel keyframe tracks (e.g. one per animated channel --
|
||||||
|
* position.x/y/z, bone rotations, etc.) sharing a single timeline. Each
|
||||||
|
* track is independent: its own keyframe array and count, evaluated at
|
||||||
|
* whatever time is asked for.
|
||||||
|
*/
|
||||||
|
typedef struct keyframeset_t {
|
||||||
|
/** Caller-owned array of trackCount keyframe_t arrays. */
|
||||||
|
keyframe_t **tracks;
|
||||||
|
/** Caller-owned array of trackCount counts, one per entry in tracks. */
|
||||||
|
uint16_t *trackCounts;
|
||||||
|
uint16_t trackCount;
|
||||||
|
|
||||||
|
/** Caller-owned array of trackCount callbacks, one per track. Entries
|
||||||
|
* (or the whole array) may be NULL for tracks with no callback. */
|
||||||
|
keyframesetcallback_t *callbacks;
|
||||||
|
/** Caller-owned array of trackCount user pointers, one per track,
|
||||||
|
* passed to that track's callbacks[] entry. May be NULL. */
|
||||||
|
void **users;
|
||||||
|
/** Extra user data for the set as a whole, not tied to any one track. */
|
||||||
|
void *user;
|
||||||
|
} keyframeset_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes a keyframe set. None of the passed-in arrays (or the
|
||||||
|
* keyframe_t arrays tracks points to) are copied -- they must outlive
|
||||||
|
* this keyframeset_t.
|
||||||
|
*
|
||||||
|
* @param set The keyframe set to initialize.
|
||||||
|
* @param tracks Array of trackCount keyframe_t arrays.
|
||||||
|
* @param trackCounts Array of trackCount keyframe counts, matching tracks.
|
||||||
|
* @param callbacks Array of trackCount callbacks, one per track, or NULL
|
||||||
|
* if no track has one.
|
||||||
|
* @param users Array of trackCount user pointers, matching callbacks, or
|
||||||
|
* NULL.
|
||||||
|
* @param trackCount The number of tracks.
|
||||||
|
* @param user Extra user data for the set as a whole; may be NULL.
|
||||||
|
*/
|
||||||
|
void keyframeSetInit(
|
||||||
|
keyframeset_t *set,
|
||||||
|
keyframe_t **tracks,
|
||||||
|
uint16_t *trackCounts,
|
||||||
|
keyframesetcallback_t *callbacks,
|
||||||
|
void **users,
|
||||||
|
uint16_t trackCount,
|
||||||
|
void *user
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the value of a single track at a given time.
|
||||||
|
*
|
||||||
|
* @param set The keyframe set to evaluate.
|
||||||
|
* @param trackIndex The track to evaluate, in [0, set->trackCount).
|
||||||
|
* @param time The time at which to get the value, in seconds.
|
||||||
|
* @return The interpolated value of that track at the given time.
|
||||||
|
*/
|
||||||
|
float_t keyframeSetGetValue(
|
||||||
|
keyframeset_t *set,
|
||||||
|
const uint16_t trackIndex,
|
||||||
|
const float_t time
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the value of every track at a given time.
|
||||||
|
*
|
||||||
|
* @param set The keyframe set to evaluate.
|
||||||
|
* @param time The time at which to get the values, in seconds.
|
||||||
|
* @param outValues Destination array of at least set->trackCount floats.
|
||||||
|
*/
|
||||||
|
void keyframeSetGetValues(
|
||||||
|
keyframeset_t *set,
|
||||||
|
const float_t time,
|
||||||
|
float_t *outValues
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the set's duration: the latest final-keyframe time across every
|
||||||
|
* track, i.e. how long it takes for every track to finish.
|
||||||
|
*
|
||||||
|
* @param set The keyframe set to measure.
|
||||||
|
* @return The set's duration, in seconds.
|
||||||
|
*/
|
||||||
|
float_t keyframeSetGetDuration(keyframeset_t *set);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invokes a track's callback, if it (and its callbacks array) is set.
|
||||||
|
* No-op otherwise.
|
||||||
|
*
|
||||||
|
* @param set The keyframe set the track belongs to.
|
||||||
|
* @param trackIndex The track whose callback to invoke.
|
||||||
|
*/
|
||||||
|
void keyframeSetFireCallback(keyframeset_t *set, const uint16_t trackIndex);
|
||||||
@@ -8,6 +8,13 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "dusk.h"
|
#include "dusk.h"
|
||||||
|
|
||||||
|
// Release-style CMake configs (Release, RelWithDebInfo, MinSizeRel) define
|
||||||
|
// NDEBUG automatically; fake assertions there rather than requiring every
|
||||||
|
// platform's CMakeLists to set DUSK_ASSERTIONS_FAKED itself.
|
||||||
|
#if defined(NDEBUG) && !defined(DUSK_ASSERTIONS_FAKED)
|
||||||
|
#define DUSK_ASSERTIONS_FAKED
|
||||||
|
#endif
|
||||||
|
|
||||||
#ifdef DUSK_TEST_ASSERT
|
#ifdef DUSK_TEST_ASSERT
|
||||||
#include <cmocka.h>
|
#include <cmocka.h>
|
||||||
|
|
||||||
@@ -22,8 +29,6 @@
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifndef DUSK_ASSERTIONS_FAKED
|
#ifndef DUSK_ASSERTIONS_FAKED
|
||||||
#define DUSK_ASSERTIONS 1
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the assert system. Must be the very first call in engine
|
* Initializes the assert system. Must be the very first call in engine
|
||||||
* startup.
|
* startup.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
asset.c
|
asset.c
|
||||||
assetdsk.c
|
assetbatch.c
|
||||||
assetfile.c
|
assetfile.c
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+10
-37
@@ -19,17 +19,13 @@ asset_t ASSET;
|
|||||||
errorret_t assetInit(void) {
|
errorret_t assetInit(void) {
|
||||||
memoryZero(&ASSET, sizeof(asset_t));
|
memoryZero(&ASSET, sizeof(asset_t));
|
||||||
|
|
||||||
threadMutexInit(&ASSET.zipLock);
|
|
||||||
|
|
||||||
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
|
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
|
||||||
threadMutexInit(&ASSET.loading[i].mutex);
|
threadMutexInit(&ASSET.loading[i].mutex);
|
||||||
}
|
}
|
||||||
|
|
||||||
// assetInitPlatform must either define both ASSET.zip/ASSET.zipStored or
|
// assetInitPlatform must either define ASSET.zip or throw an error.
|
||||||
// throw an error.
|
|
||||||
errorChain(assetInitPlatform());
|
errorChain(assetInitPlatform());
|
||||||
assertNotNull(ASSET.zip, "Asset zip NULL without error.");
|
assertNotNull(ASSET.zip, "Asset zip null without error.");
|
||||||
assertNotNull(ASSET.zipStored, "Asset stored zip NULL without error.");
|
|
||||||
threadInit(&ASSET.loadThread, assetUpdateAsync);
|
threadInit(&ASSET.loadThread, assetUpdateAsync);
|
||||||
threadStart(&ASSET.loadThread);
|
threadStart(&ASSET.loadThread);
|
||||||
|
|
||||||
@@ -39,12 +35,9 @@ errorret_t assetInit(void) {
|
|||||||
bool_t assetFileExists(const char_t *filename) {
|
bool_t assetFileExists(const char_t *filename) {
|
||||||
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
|
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
|
||||||
|
|
||||||
threadMutexLock(&ASSET.zipLock);
|
zip_int64_t idx = zip_name_locate(ASSET.zip, filename, 0);
|
||||||
bool_t found =
|
if(idx < 0) return false;
|
||||||
zip_name_locate(ASSET.zip, filename, 0) >= 0 ||
|
return true;
|
||||||
zip_name_locate(ASSET.zipStored, filename, 0) >= 0;
|
|
||||||
threadMutexUnlock(&ASSET.zipLock);
|
|
||||||
return found;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
assetentry_t * assetGetEntry(
|
assetentry_t * assetGetEntry(
|
||||||
@@ -124,15 +117,6 @@ errorret_t assetRequireLoaded(assetentry_t *entry) {
|
|||||||
assetEntryLock(entry);
|
assetEntryLock(entry);
|
||||||
|
|
||||||
while(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
while(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
||||||
// A failed load transitions to ERROR, not LOADED - without this check
|
|
||||||
// this loop spins forever on any load failure (assetUpdate() itself
|
|
||||||
// still returns OK, since a single asset failing isn't meant to halt
|
|
||||||
// the whole update loop - see its ASSET_ENTRY_STATE_ERROR handling).
|
|
||||||
if(entry->state == ASSET_ENTRY_STATE_ERROR) {
|
|
||||||
assetEntryUnlock(entry);
|
|
||||||
errorThrow("Failed to load asset: %s", entry->name);
|
|
||||||
}
|
|
||||||
|
|
||||||
usleep(1000);
|
usleep(1000);
|
||||||
errorret_t ret = assetUpdate();
|
errorret_t ret = assetUpdate();
|
||||||
if(errorIsNotOk(ret)) {
|
if(errorIsNotOk(ret)) {
|
||||||
@@ -338,9 +322,7 @@ errorret_t assetUpdate(void) {
|
|||||||
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
|
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
|
||||||
assetentry_t *loadedEntry = loading->entry;
|
assetentry_t *loadedEntry = loading->entry;
|
||||||
loading->entry = NULL;
|
loading->entry = NULL;
|
||||||
if(loadedEntry->onLoaded) {
|
eventInvoke(&loadedEntry->onLoaded, loadedEntry);
|
||||||
loadedEntry->onLoaded(loadedEntry, loadedEntry->onLoadedUser);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loading++;
|
loading++;
|
||||||
@@ -364,10 +346,8 @@ errorret_t assetUpdate(void) {
|
|||||||
assetentry_t *errEntry = loading->entry;
|
assetentry_t *errEntry = loading->entry;
|
||||||
loading->entry = NULL;
|
loading->entry = NULL;
|
||||||
threadMutexUnlock(&loading->mutex);
|
threadMutexUnlock(&loading->mutex);
|
||||||
if(errEntry->onError) {
|
eventInvoke(&errEntry->onError, errEntry);
|
||||||
errEntry->onError(errEntry, errEntry->onErrorUser);
|
errorThrow("Failed to load asset asynchronously.");
|
||||||
}
|
|
||||||
loading++;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -445,21 +425,14 @@ errorret_t assetDispose(void) {
|
|||||||
|
|
||||||
errorChain(assetReapUnused());
|
errorChain(assetReapUnused());
|
||||||
|
|
||||||
// Cleanup zip files.
|
// Cleanup zip file.
|
||||||
if(ASSET.zip != NULL) {
|
if(ASSET.zip != NULL) {
|
||||||
if(zip_close(ASSET.zip) != 0) {
|
if(zip_close(ASSET.zip) != 0) {
|
||||||
errorThrow("Failed to close compressed asset zip archive.");
|
errorThrow("Failed to close asset zip archive.");
|
||||||
}
|
}
|
||||||
ASSET.zip = NULL;
|
ASSET.zip = NULL;
|
||||||
}
|
}
|
||||||
if(ASSET.zipStored != NULL) {
|
|
||||||
if(zip_close(ASSET.zipStored) != 0) {
|
|
||||||
errorThrow("Failed to close stored asset zip archive.");
|
|
||||||
}
|
|
||||||
ASSET.zipStored = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorChain(assetDisposePlatform());
|
errorChain(assetDisposePlatform());
|
||||||
threadMutexDispose(&ASSET.zipLock);
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
@@ -26,44 +26,10 @@
|
|||||||
#define ASSET_LOADING_COUNT_MAX 10
|
#define ASSET_LOADING_COUNT_MAX 10
|
||||||
#define ASSET_ENTRY_COUNT_MAX 64
|
#define ASSET_ENTRY_COUNT_MAX 64
|
||||||
|
|
||||||
#define ASSET_BASE_DIRECTORY_MAX 256
|
|
||||||
|
|
||||||
typedef struct asset_s {
|
typedef struct asset_s {
|
||||||
// Compressed (DEFLATE) archive - expected to hold the bulk of a game's
|
|
||||||
// binary assets. Looked up first by assetFileInit().
|
|
||||||
zip_t *zip;
|
zip_t *zip;
|
||||||
|
|
||||||
// Stored (uncompressed) archive - expected to hold small files that need
|
|
||||||
// reliable repeated seeking/re-opening (e.g. locale strings), which
|
|
||||||
// libzip only supports reliably for uncompressed entries. Looked up by
|
|
||||||
// assetFileInit() only if the name isn't found in `zip`.
|
|
||||||
zip_t *zipStored;
|
|
||||||
|
|
||||||
// Directory dusk.dsk was actually found/opened in (on PSP, the directory
|
|
||||||
// EBOOT.PBP lives in, since dusk.dsk is embedded inside it rather than a
|
|
||||||
// loose file) - populated by each platform's own assetInitXxx() once it
|
|
||||||
// locates the file. Save devices that persist to a real filesystem path
|
|
||||||
// (Linux, PSP, Wii SD) use this as their base directory instead of a
|
|
||||||
// separate hardcoded location, so saves live next to wherever the game
|
|
||||||
// itself was actually launched from rather than some unrelated fixed
|
|
||||||
// path. Not meaningful for devices with no filesystem-path concept at
|
|
||||||
// all (GameCube/Wii memory card, Wii NAND's ISFS namespace).
|
|
||||||
char_t baseDirectory[ASSET_BASE_DIRECTORY_MAX];
|
|
||||||
|
|
||||||
assetplatform_t platform;
|
assetplatform_t platform;
|
||||||
|
|
||||||
// Guards every libzip call against ASSET.zip/ASSET.zipStored (zip_fopen,
|
|
||||||
// zip_fread, zip_fclose, zip_fseek, zip_stat, zip_name_locate - see
|
|
||||||
// assetfile.c/assetFileExists). libzip is documented as not thread-safe,
|
|
||||||
// and this asset system genuinely calls it from multiple real threads at
|
|
||||||
// once (main thread, the background load thread below, and - on
|
|
||||||
// platforms that stream PCM from an asset on their own thread, like PSP
|
|
||||||
// - an audio feeder thread too). Confirmed necessary on real PSP
|
|
||||||
// hardware: without this lock, concurrent zip_fopen/zip_fread calls from
|
|
||||||
// different threads corrupted reads (EINVAL, then zlib data errors) once
|
|
||||||
// dusk.dsk stopped being read entirely into memory up front.
|
|
||||||
threadmutex_t zipLock;
|
|
||||||
|
|
||||||
// Background loading thread.
|
// Background loading thread.
|
||||||
thread_t loadThread;
|
thread_t loadThread;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetbatch.h"
|
||||||
|
#include "asset.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
void assetBatchInit(
|
||||||
|
assetbatch_t *batch,
|
||||||
|
const uint16_t count,
|
||||||
|
const assetbatchdesc_t *descs
|
||||||
|
) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
assertNotNull(descs, "Descs cannot be NULL.");
|
||||||
|
assertTrue(count > 0, "Count must be greater than 0.");
|
||||||
|
assertTrue(
|
||||||
|
count <= ASSET_BATCH_COUNT_MAX, "Count exceeds ASSET_BATCH_COUNT_MAX."
|
||||||
|
);
|
||||||
|
|
||||||
|
memoryZero(batch, sizeof(assetbatch_t));
|
||||||
|
batch->count = count;
|
||||||
|
|
||||||
|
eventInit(
|
||||||
|
&batch->onLoaded,
|
||||||
|
batch->onLoadedCallbacks, batch->onLoadedUsers, ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&batch->onEntryLoaded,
|
||||||
|
batch->onEntryLoadedCallbacks,
|
||||||
|
batch->onEntryLoadedUsers,
|
||||||
|
ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&batch->onError,
|
||||||
|
batch->onErrorCallbacks, batch->onErrorUsers, ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&batch->onEntryError,
|
||||||
|
batch->onEntryErrorCallbacks,
|
||||||
|
batch->onEntryErrorUsers,
|
||||||
|
ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
|
||||||
|
for(uint16_t i = 0; i < count; i++) {
|
||||||
|
batch->inputs[i] = descs[i].input;
|
||||||
|
batch->entries[i] = assetLock(
|
||||||
|
descs[i].path, descs[i].type, &batch->inputs[i]
|
||||||
|
);
|
||||||
|
|
||||||
|
if(batch->entries[i]->state == ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
// Already loaded (cached) - count it now, no subscription needed.
|
||||||
|
batch->loadedCount++;
|
||||||
|
} else if(batch->entries[i]->state == ASSET_ENTRY_STATE_ERROR) {
|
||||||
|
batch->errorCount++;
|
||||||
|
} else {
|
||||||
|
eventSubscribe(
|
||||||
|
&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb, batch
|
||||||
|
);
|
||||||
|
eventSubscribe(
|
||||||
|
&batch->entries[i]->onError, assetBatchEntryOnErrorCb, batch
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchLock(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
assetEntryLock(batch->entries[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchUnlock(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
assetEntryUnlock(batch->entries[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t assetBatchIsLoaded(const assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
if(batch->entries[i]->state != ASSET_ENTRY_STATE_LOADED) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t assetBatchHasError(const assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
if(batch->entries[i]->state == ASSET_ENTRY_STATE_ERROR) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetBatchRequireLoaded(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
|
||||||
|
bool_t allDone;
|
||||||
|
do {
|
||||||
|
allDone = true;
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
const assetentrystate_t state = batch->entries[i]->state;
|
||||||
|
if(state == ASSET_ENTRY_STATE_ERROR) {
|
||||||
|
errorThrow("Asset '%s' failed to load.", batch->entries[i]->name);
|
||||||
|
}
|
||||||
|
if(state != ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
allDone = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!allDone) {
|
||||||
|
usleep(1000);
|
||||||
|
errorChain(assetUpdate());
|
||||||
|
}
|
||||||
|
} while(!allDone);
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchDispose(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
if(batch->entries[i]) {
|
||||||
|
// Unsubscribe while we still hold a lock so the entry is live.
|
||||||
|
eventUnsubscribe(&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb);
|
||||||
|
eventUnsubscribe(&batch->entries[i]->onError, assetBatchEntryOnErrorCb);
|
||||||
|
assetUnlockEntry(batch->entries[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
memoryZero(batch, sizeof(assetbatch_t));
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchEntryOnLoadedCb(void *params, void *user) {
|
||||||
|
assetentry_t *entry = (assetentry_t *)params;
|
||||||
|
assetbatch_t *batch = (assetbatch_t *)user;
|
||||||
|
|
||||||
|
batch->loadedCount++;
|
||||||
|
eventInvoke(&batch->onEntryLoaded, entry);
|
||||||
|
|
||||||
|
if((uint16_t)(batch->loadedCount + batch->errorCount) >= batch->count) {
|
||||||
|
if(batch->errorCount == 0) {
|
||||||
|
eventInvoke(&batch->onLoaded, batch);
|
||||||
|
} else {
|
||||||
|
eventInvoke(&batch->onError, batch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchEntryOnErrorCb(void *params, void *user) {
|
||||||
|
assetentry_t *entry = (assetentry_t *)params;
|
||||||
|
assetbatch_t *batch = (assetbatch_t *)user;
|
||||||
|
|
||||||
|
batch->errorCount++;
|
||||||
|
eventInvoke(&batch->onEntryError, entry);
|
||||||
|
|
||||||
|
if((uint16_t)(batch->loadedCount + batch->errorCount) >= batch->count) {
|
||||||
|
eventInvoke(&batch->onError, batch);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
#include "asset/loader/assetloader.h"
|
||||||
|
#include "event/event.h"
|
||||||
|
|
||||||
|
#define ASSET_BATCH_COUNT_MAX 64
|
||||||
|
#define ASSET_BATCH_EVENT_MAX 4
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
const char_t *path;
|
||||||
|
assetloadertype_t type;
|
||||||
|
assetloaderinput_t input;
|
||||||
|
} assetbatchdesc_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetentry_t *entries[ASSET_BATCH_COUNT_MAX];
|
||||||
|
assetloaderinput_t inputs[ASSET_BATCH_COUNT_MAX];
|
||||||
|
uint16_t count;
|
||||||
|
uint16_t loadedCount;
|
||||||
|
uint16_t errorCount;
|
||||||
|
|
||||||
|
/** Fires once when every entry loaded. params = assetbatch_t * */
|
||||||
|
event_t onLoaded;
|
||||||
|
eventcallback_t onLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||||
|
void *onLoadedUsers[ASSET_BATCH_EVENT_MAX];
|
||||||
|
|
||||||
|
/** Fires each time a single entry loads. params = assetentry_t * */
|
||||||
|
event_t onEntryLoaded;
|
||||||
|
eventcallback_t onEntryLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||||
|
void *onEntryLoadedUsers[ASSET_BATCH_EVENT_MAX];
|
||||||
|
|
||||||
|
/** Fires when all entries finish (any with errors). params: assetbatch_t * */
|
||||||
|
event_t onError;
|
||||||
|
eventcallback_t onErrorCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||||
|
void *onErrorUsers[ASSET_BATCH_EVENT_MAX];
|
||||||
|
|
||||||
|
/** Fires each time a single entry errors. params = assetentry_t * */
|
||||||
|
event_t onEntryError;
|
||||||
|
eventcallback_t onEntryErrorCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||||
|
void *onEntryErrorUsers[ASSET_BATCH_EVENT_MAX];
|
||||||
|
} assetbatch_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialises the batch from an array of descriptors. Each entry is locked
|
||||||
|
* and queued for loading immediately.
|
||||||
|
*
|
||||||
|
* @param batch Batch to initialise.
|
||||||
|
* @param descs Array of entry descriptors (need not outlive this call).
|
||||||
|
* @param count Number of descriptors (must be <= ASSET_BATCH_COUNT_MAX).
|
||||||
|
*/
|
||||||
|
void assetBatchInit(
|
||||||
|
assetbatch_t *batch,
|
||||||
|
uint16_t count,
|
||||||
|
const assetbatchdesc_t *descs
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Acquires one additional lock on every entry in the batch.
|
||||||
|
*
|
||||||
|
* @param batch Batch to lock.
|
||||||
|
*/
|
||||||
|
void assetBatchLock(assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases one lock from every entry in the batch. When an entry's lock
|
||||||
|
* count reaches zero it will be reaped on the next assetUpdate.
|
||||||
|
*
|
||||||
|
* @param batch Batch to unlock.
|
||||||
|
*/
|
||||||
|
void assetBatchUnlock(assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if every entry in the batch has finished loading.
|
||||||
|
*
|
||||||
|
* @param batch Batch to query.
|
||||||
|
*/
|
||||||
|
bool_t assetBatchIsLoaded(const assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if any entry in the batch is in an error state.
|
||||||
|
*
|
||||||
|
* @param batch Batch to query.
|
||||||
|
*/
|
||||||
|
bool_t assetBatchHasError(const assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocks until every entry is loaded. Returns an error if any entry fails.
|
||||||
|
*
|
||||||
|
* @param batch Batch to wait on.
|
||||||
|
*/
|
||||||
|
errorret_t assetBatchRequireLoaded(assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases the batch's lock on every entry and clears the batch. After this
|
||||||
|
* call the batch struct may be reused with assetBatchInit.
|
||||||
|
*
|
||||||
|
* @param batch Batch to dispose.
|
||||||
|
*/
|
||||||
|
void assetBatchDispose(assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event trampoline invoked when a batch entry finishes loading.
|
||||||
|
* Increments the loaded counter and fires batch-level events.
|
||||||
|
*
|
||||||
|
* @param params The loaded assetentry_t pointer.
|
||||||
|
* @param user The owning assetbatch_t pointer.
|
||||||
|
*/
|
||||||
|
void assetBatchEntryOnLoadedCb(void *params, void *user);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event trampoline invoked when a batch entry fails to load.
|
||||||
|
* Increments the error counter and fires batch-level events.
|
||||||
|
*
|
||||||
|
* @param params The errored assetentry_t pointer.
|
||||||
|
* @param user The owning assetbatch_t pointer.
|
||||||
|
*/
|
||||||
|
void assetBatchEntryOnErrorCb(void *params, void *user);
|
||||||
@@ -1,289 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "assetdsk.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/endian.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include <zlib.h>
|
|
||||||
|
|
||||||
errorret_t assetDskParseHeader(
|
|
||||||
const uint8_t *bytes,
|
|
||||||
const size_t bytesSize,
|
|
||||||
assetdskheader_t *outHeader
|
|
||||||
) {
|
|
||||||
assertNotNull(bytes, "Bytes cannot be NULL.");
|
|
||||||
assertNotNull(outHeader, "Out header cannot be NULL.");
|
|
||||||
|
|
||||||
if(bytesSize < ASSET_DSK_HEADER_SIZE) {
|
|
||||||
errorThrow("dusk.dsk header is truncated.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if(memoryCompare(bytes, ASSET_DSK_MAGIC, ASSET_DSK_MAGIC_SIZE) != 0) {
|
|
||||||
errorThrow("dusk.dsk has an invalid magic header.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Every field is a little-endian uint32_t regardless of host - convert
|
|
||||||
// to host order (a no-op on little-endian hosts, a real byteswap on
|
|
||||||
// Dolphin's big-endian PowerPC).
|
|
||||||
uint32_t fields[7];
|
|
||||||
memoryCopy(fields, bytes + ASSET_DSK_MAGIC_SIZE, sizeof(fields));
|
|
||||||
for(uint8_t i = 0; i < 7; i++) {
|
|
||||||
fields[i] = endianLittleToHost32(fields[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
const uint32_t version = fields[0];
|
|
||||||
if(version != ASSET_DSK_VERSION) {
|
|
||||||
errorThrow("dusk.dsk has an unsupported version: %u", version);
|
|
||||||
}
|
|
||||||
|
|
||||||
outHeader->compressedOffset = fields[1];
|
|
||||||
outHeader->compressedSize = fields[2];
|
|
||||||
outHeader->compressedChecksum = fields[3];
|
|
||||||
outHeader->storedOffset = fields[4];
|
|
||||||
outHeader->storedSize = fields[5];
|
|
||||||
outHeader->storedChecksum = fields[6];
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetDskOpenFromPath(
|
|
||||||
const char_t *path,
|
|
||||||
zip_t **outCompressed,
|
|
||||||
zip_t **outStored
|
|
||||||
) {
|
|
||||||
errorChain(assetDskOpenFromPathRange(
|
|
||||||
path, 0, SIZE_MAX, outCompressed, outStored
|
|
||||||
));
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetDskOpenFromPathRange(
|
|
||||||
const char_t *path,
|
|
||||||
const size_t baseOffset,
|
|
||||||
const size_t baseSize,
|
|
||||||
zip_t **outCompressed,
|
|
||||||
zip_t **outStored
|
|
||||||
) {
|
|
||||||
assertNotNull(path, "Path cannot be NULL.");
|
|
||||||
assertNotNull(outCompressed, "Out compressed cannot be NULL.");
|
|
||||||
assertNotNull(outStored, "Out stored cannot be NULL.");
|
|
||||||
|
|
||||||
*outCompressed = NULL;
|
|
||||||
*outStored = NULL;
|
|
||||||
|
|
||||||
FILE *headerFile = fopen(path, "rb");
|
|
||||||
if(headerFile == NULL) {
|
|
||||||
errorThrow("Failed to open dusk.dsk: %s", path);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(fseek(headerFile, (long) baseOffset, SEEK_SET) != 0) {
|
|
||||||
fclose(headerFile);
|
|
||||||
errorThrow("Failed to seek to dusk.dsk range in file: %s", path);
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t headerBytes[ASSET_DSK_HEADER_SIZE];
|
|
||||||
size_t headerRead = fread(headerBytes, 1, sizeof(headerBytes), headerFile);
|
|
||||||
fclose(headerFile);
|
|
||||||
if(headerRead != sizeof(headerBytes)) {
|
|
||||||
errorThrow("Failed to read dusk.dsk header: %s", path);
|
|
||||||
}
|
|
||||||
|
|
||||||
assetdskheader_t header;
|
|
||||||
errorChain(assetDskParseHeader(headerBytes, sizeof(headerBytes), &header));
|
|
||||||
|
|
||||||
if(
|
|
||||||
(size_t) header.compressedOffset + header.compressedSize > baseSize ||
|
|
||||||
(size_t) header.storedOffset + header.storedSize > baseSize
|
|
||||||
) {
|
|
||||||
errorThrow("dusk.dsk header describes ranges beyond its containing file.");
|
|
||||||
}
|
|
||||||
|
|
||||||
zip_error_t zipError;
|
|
||||||
zip_error_init(&zipError);
|
|
||||||
|
|
||||||
zip_source_t *compressedSource = zip_source_file_create(
|
|
||||||
path,
|
|
||||||
(zip_uint64_t) (baseOffset + header.compressedOffset),
|
|
||||||
(zip_int64_t) header.compressedSize,
|
|
||||||
&zipError
|
|
||||||
);
|
|
||||||
if(compressedSource == NULL) {
|
|
||||||
errorThrow(
|
|
||||||
"Failed to create compressed dusk.dsk source: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
*outCompressed =
|
|
||||||
zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError);
|
|
||||||
if(*outCompressed == NULL) {
|
|
||||||
zip_source_free(compressedSource);
|
|
||||||
errorThrow(
|
|
||||||
"Failed to open compressed dusk.dsk archive: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
zip_source_t *storedSource = zip_source_file_create(
|
|
||||||
path,
|
|
||||||
(zip_uint64_t) (baseOffset + header.storedOffset),
|
|
||||||
(zip_int64_t) header.storedSize,
|
|
||||||
&zipError
|
|
||||||
);
|
|
||||||
if(storedSource == NULL) {
|
|
||||||
zip_close(*outCompressed);
|
|
||||||
*outCompressed = NULL;
|
|
||||||
errorThrow(
|
|
||||||
"Failed to create stored dusk.dsk source: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
*outStored = zip_open_from_source(storedSource, ZIP_RDONLY, &zipError);
|
|
||||||
if(*outStored == NULL) {
|
|
||||||
zip_source_free(storedSource);
|
|
||||||
zip_close(*outCompressed);
|
|
||||||
*outCompressed = NULL;
|
|
||||||
errorThrow(
|
|
||||||
"Failed to open stored dusk.dsk archive: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The stored archive is small by convention, so verifying its checksum
|
|
||||||
// here (one extra small read) is cheap; the compressed archive isn't
|
|
||||||
// checked since it's meant to be read lazily/on-demand from here on.
|
|
||||||
uint8_t *storedBytes = (uint8_t *) memoryAllocate(header.storedSize);
|
|
||||||
FILE *storedFile = fopen(path, "rb");
|
|
||||||
if(storedFile == NULL) {
|
|
||||||
memoryFree(storedBytes);
|
|
||||||
zip_close(*outStored);
|
|
||||||
zip_close(*outCompressed);
|
|
||||||
*outStored = NULL;
|
|
||||||
*outCompressed = NULL;
|
|
||||||
errorThrow(
|
|
||||||
"Failed to re-open dusk.dsk to verify stored checksum: %s", path
|
|
||||||
);
|
|
||||||
}
|
|
||||||
fseek(storedFile, (long) (baseOffset + header.storedOffset), SEEK_SET);
|
|
||||||
size_t storedRead = fread(storedBytes, 1, header.storedSize, storedFile);
|
|
||||||
fclose(storedFile);
|
|
||||||
if(storedRead != header.storedSize) {
|
|
||||||
memoryFree(storedBytes);
|
|
||||||
zip_close(*outStored);
|
|
||||||
zip_close(*outCompressed);
|
|
||||||
*outStored = NULL;
|
|
||||||
*outCompressed = NULL;
|
|
||||||
errorThrow(
|
|
||||||
"Failed to read dusk.dsk stored archive to verify checksum: %s", path
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t checksum =
|
|
||||||
(uint32_t) crc32(0L, storedBytes, (uInt) header.storedSize);
|
|
||||||
memoryFree(storedBytes);
|
|
||||||
if(checksum != header.storedChecksum) {
|
|
||||||
zip_close(*outStored);
|
|
||||||
zip_close(*outCompressed);
|
|
||||||
*outStored = NULL;
|
|
||||||
*outCompressed = NULL;
|
|
||||||
errorThrow(
|
|
||||||
"dusk.dsk stored archive failed checksum verification: %s", path
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetDskOpenFromBuffer(
|
|
||||||
uint8_t *buffer,
|
|
||||||
const size_t bufferSize,
|
|
||||||
zip_t **outCompressed,
|
|
||||||
zip_t **outStored
|
|
||||||
) {
|
|
||||||
assertNotNull(buffer, "Buffer cannot be NULL.");
|
|
||||||
assertNotNull(outCompressed, "Out compressed cannot be NULL.");
|
|
||||||
assertNotNull(outStored, "Out stored cannot be NULL.");
|
|
||||||
|
|
||||||
*outCompressed = NULL;
|
|
||||||
*outStored = NULL;
|
|
||||||
|
|
||||||
assetdskheader_t header;
|
|
||||||
errorChain(assetDskParseHeader(buffer, bufferSize, &header));
|
|
||||||
|
|
||||||
if(
|
|
||||||
(size_t) header.compressedOffset + header.compressedSize > bufferSize ||
|
|
||||||
(size_t) header.storedOffset + header.storedSize > bufferSize
|
|
||||||
) {
|
|
||||||
errorThrow("dusk.dsk header describes ranges beyond the buffer.");
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t compressedChecksum = (uint32_t) crc32(
|
|
||||||
0L, buffer + header.compressedOffset, (uInt) header.compressedSize
|
|
||||||
);
|
|
||||||
if(compressedChecksum != header.compressedChecksum) {
|
|
||||||
errorThrow("dusk.dsk compressed archive failed checksum verification.");
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t storedChecksum = (uint32_t) crc32(
|
|
||||||
0L, buffer + header.storedOffset, (uInt) header.storedSize
|
|
||||||
);
|
|
||||||
if(storedChecksum != header.storedChecksum) {
|
|
||||||
errorThrow("dusk.dsk stored archive failed checksum verification.");
|
|
||||||
}
|
|
||||||
|
|
||||||
zip_error_t zipError;
|
|
||||||
zip_error_init(&zipError);
|
|
||||||
|
|
||||||
// freep=0 for both - they're non-owning windows into the same caller-owned
|
|
||||||
// buffer, not independent allocations libzip should free.
|
|
||||||
zip_source_t *compressedSource = zip_source_buffer_create(
|
|
||||||
buffer + header.compressedOffset, header.compressedSize, 0, &zipError
|
|
||||||
);
|
|
||||||
if(compressedSource == NULL) {
|
|
||||||
errorThrow(
|
|
||||||
"Failed to create compressed dusk.dsk source: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
*outCompressed =
|
|
||||||
zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError);
|
|
||||||
if(*outCompressed == NULL) {
|
|
||||||
zip_source_free(compressedSource);
|
|
||||||
errorThrow(
|
|
||||||
"Failed to open compressed dusk.dsk archive: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
zip_source_t *storedSource = zip_source_buffer_create(
|
|
||||||
buffer + header.storedOffset, header.storedSize, 0, &zipError
|
|
||||||
);
|
|
||||||
if(storedSource == NULL) {
|
|
||||||
zip_close(*outCompressed);
|
|
||||||
*outCompressed = NULL;
|
|
||||||
errorThrow(
|
|
||||||
"Failed to create stored dusk.dsk source: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
*outStored = zip_open_from_source(storedSource, ZIP_RDONLY, &zipError);
|
|
||||||
if(*outStored == NULL) {
|
|
||||||
zip_source_free(storedSource);
|
|
||||||
zip_close(*outCompressed);
|
|
||||||
*outCompressed = NULL;
|
|
||||||
errorThrow(
|
|
||||||
"Failed to open stored dusk.dsk archive: %s",
|
|
||||||
zip_error_strerror(&zipError)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,128 +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"
|
|
||||||
#include <zip.h>
|
|
||||||
|
|
||||||
// "DSK2" - distinct from a plain zip's "PK\x03\x04" so a stray plain zip
|
|
||||||
// never gets misread as a valid dusk.dsk.
|
|
||||||
#define ASSET_DSK_MAGIC_SIZE 4
|
|
||||||
#define ASSET_DSK_MAGIC "DSK2"
|
|
||||||
#define ASSET_DSK_VERSION 1
|
|
||||||
|
|
||||||
// magic(4) + version(4) + compressedOffset(4) + compressedSize(4) +
|
|
||||||
// compressedChecksum(4) + storedOffset(4) + storedSize(4) +
|
|
||||||
// storedChecksum(4), all little-endian regardless of host - see
|
|
||||||
// assetDskParseHeader.
|
|
||||||
#define ASSET_DSK_HEADER_SIZE 32
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parsed dusk.dsk (DSK2 format) header. dusk.dsk is two independent, back
|
|
||||||
* to back zip archives (see tools/asset/pack) rather than a single plain
|
|
||||||
* zip: a "compressed" one (DEFLATE, expected to hold the bulk of a game's
|
|
||||||
* binary assets, opened lazily/on-demand) and a "stored" one (uncompressed,
|
|
||||||
* expected to hold small files - locale strings, config - that need
|
|
||||||
* reliable repeated seeking/re-opening, which libzip only supports for
|
|
||||||
* uncompressed entries).
|
|
||||||
*/
|
|
||||||
typedef struct {
|
|
||||||
uint32_t compressedOffset;
|
|
||||||
uint32_t compressedSize;
|
|
||||||
uint32_t compressedChecksum;
|
|
||||||
uint32_t storedOffset;
|
|
||||||
uint32_t storedSize;
|
|
||||||
uint32_t storedChecksum;
|
|
||||||
} assetdskheader_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses a DSK2 header from a raw byte buffer (at least
|
|
||||||
* ASSET_DSK_HEADER_SIZE bytes), validating the magic/version and
|
|
||||||
* byte-swapping the little-endian fields to host order.
|
|
||||||
*
|
|
||||||
* @param bytes Buffer containing the header (and beyond).
|
|
||||||
* @param bytesSize Number of bytes available at `bytes`.
|
|
||||||
* @param outHeader Filled with the parsed header on success.
|
|
||||||
* @return OK on success, error if too short, bad magic, or unsupported version.
|
|
||||||
*/
|
|
||||||
errorret_t assetDskParseHeader(
|
|
||||||
const uint8_t *bytes,
|
|
||||||
const size_t bytesSize,
|
|
||||||
assetdskheader_t *outHeader
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens both archives of a dusk.dsk file given a filesystem path, using
|
|
||||||
* lazy/windowed file-backed zip sources - no more memory used than the
|
|
||||||
* existing per-platform small read buffers, matching the memory
|
|
||||||
* characteristics of a plain zip_open() on the whole file. Verifies the
|
|
||||||
* (small, by convention) stored archive's checksum; the compressed
|
|
||||||
* archive's checksum is intentionally not verified here since doing so
|
|
||||||
* would require reading the bulk of the game's assets just to compute it.
|
|
||||||
*
|
|
||||||
* See assetDskOpenFromPathRange() for the case where the DSK2 blob isn't
|
|
||||||
* the whole file (e.g. embedded inside another container).
|
|
||||||
*
|
|
||||||
* @param path Filesystem path to the dusk.dsk file.
|
|
||||||
* @param outCompressed Set to the opened compressed archive on success.
|
|
||||||
* @param outStored Set to the opened stored archive on success.
|
|
||||||
* @return OK on success, error if the file is missing, too short, has a
|
|
||||||
* bad header, or either archive fails to open/verify.
|
|
||||||
*/
|
|
||||||
errorret_t assetDskOpenFromPath(
|
|
||||||
const char_t *path,
|
|
||||||
zip_t **outCompressed,
|
|
||||||
zip_t **outStored
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Same as assetDskOpenFromPath(), but the DSK2 blob doesn't start at the
|
|
||||||
* beginning of `path` - it's a byte range embedded inside a larger
|
|
||||||
* container file (e.g. the PSAR region of an EBOOT.PBP). Every offset the
|
|
||||||
* header describes is relative to `baseOffset`; `baseSize` bounds them
|
|
||||||
* (the size of the embedded blob, not the whole container file) - pass
|
|
||||||
* SIZE_MAX to skip that check when the caller doesn't know/care.
|
|
||||||
*
|
|
||||||
* @param path Filesystem path to the container file.
|
|
||||||
* @param baseOffset Byte offset within `path` where the DSK2 blob starts.
|
|
||||||
* @param baseSize Number of bytes available at `baseOffset`.
|
|
||||||
* @param outCompressed Set to the opened compressed archive on success.
|
|
||||||
* @param outStored Set to the opened stored archive on success.
|
|
||||||
* @return OK on success, error if the file is missing, too short, has a
|
|
||||||
* bad header, or either archive fails to open/verify.
|
|
||||||
*/
|
|
||||||
errorret_t assetDskOpenFromPathRange(
|
|
||||||
const char_t *path,
|
|
||||||
const size_t baseOffset,
|
|
||||||
const size_t baseSize,
|
|
||||||
zip_t **outCompressed,
|
|
||||||
zip_t **outStored
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens both archives of a dusk.dsk file already fully resident in memory
|
|
||||||
* (e.g. a PSAR embedded in an EBOOT.PBP, or an ISO-embedded file already
|
|
||||||
* read via DVD_ReadAbs - platforms that already buffer the whole file for
|
|
||||||
* reasons unrelated to this format). Neither archive takes ownership of
|
|
||||||
* `buffer` (both are opened as non-owning sub-ranges of it) - the caller
|
|
||||||
* remains responsible for freeing it, and must keep it alive for as long
|
|
||||||
* as either archive stays open. Verifies both archives' checksums, since
|
|
||||||
* the bytes are already resident.
|
|
||||||
*
|
|
||||||
* @param buffer The whole dusk.dsk file's bytes.
|
|
||||||
* @param bufferSize Number of bytes at `buffer`.
|
|
||||||
* @param outCompressed Set to the opened compressed archive on success.
|
|
||||||
* @param outStored Set to the opened stored archive on success.
|
|
||||||
* @return OK on success, error if too short, has a bad header/checksum, or
|
|
||||||
* either archive fails to open.
|
|
||||||
*/
|
|
||||||
errorret_t assetDskOpenFromBuffer(
|
|
||||||
uint8_t *buffer,
|
|
||||||
const size_t bufferSize,
|
|
||||||
zip_t **outCompressed,
|
|
||||||
zip_t **outStored
|
|
||||||
);
|
|
||||||
+28
-90
@@ -24,20 +24,9 @@ errorret_t assetFileInit(
|
|||||||
file->params = params;
|
file->params = params;
|
||||||
file->output = output;
|
file->output = output;
|
||||||
|
|
||||||
// Stat the file, trying the compressed archive first and falling back to
|
// Stat the file
|
||||||
// the stored one - remember which matched so assetFileOpen opens it from
|
|
||||||
// the right archive.
|
|
||||||
zip_stat_init(&file->stat);
|
zip_stat_init(&file->stat);
|
||||||
threadMutexLock(&ASSET.zipLock);
|
if(!zip_stat(ASSET.zip, filename, 0, &file->stat) == 0) {
|
||||||
if(zip_stat(ASSET.zip, filename, 0, &file->stat) == 0) {
|
|
||||||
file->sourceZip = ASSET.zip;
|
|
||||||
} else if(zip_stat(ASSET.zipStored, filename, 0, &file->stat) == 0) {
|
|
||||||
file->sourceZip = ASSET.zipStored;
|
|
||||||
} else {
|
|
||||||
file->sourceZip = NULL;
|
|
||||||
}
|
|
||||||
threadMutexUnlock(&ASSET.zipLock);
|
|
||||||
if(file->sourceZip == NULL) {
|
|
||||||
errorThrow("Failed to stat asset file: %s", filename);
|
errorThrow("Failed to stat asset file: %s", filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,25 +47,6 @@ errorret_t assetFileRewind(assetfile_t *file) {
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prefer seeking within the still-open handle over closing and
|
|
||||||
// re-opening it. Repeatedly closing/re-opening the same compressed zip
|
|
||||||
// entry (once per rewind - e.g. once per locale string lookup) was
|
|
||||||
// confirmed unreliable on at least one platform's zip backend, silently
|
|
||||||
// skipping ranges of the decompressed content on some re-opens after
|
|
||||||
// the first. A real seek avoids that failure mode entirely, with no
|
|
||||||
// extra memory cost over the close+reopen fallback.
|
|
||||||
threadMutexLock(&ASSET.zipLock);
|
|
||||||
bool_t seekable = zip_file_is_seekable(file->zipFile);
|
|
||||||
int seekResult = seekable ? zip_fseek(file->zipFile, 0, SEEK_SET) : -1;
|
|
||||||
threadMutexUnlock(&ASSET.zipLock);
|
|
||||||
if(seekable) {
|
|
||||||
if(seekResult != 0) {
|
|
||||||
errorThrow("Failed to seek asset file: %s", file->filename);
|
|
||||||
}
|
|
||||||
file->position = 0;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorChain(assetFileClose(file));
|
errorChain(assetFileClose(file));
|
||||||
errorChain(assetFileOpen(file));
|
errorChain(assetFileOpen(file));
|
||||||
errorOk();
|
errorOk();
|
||||||
@@ -85,12 +55,10 @@ errorret_t assetFileRewind(assetfile_t *file) {
|
|||||||
errorret_t assetFileOpen(assetfile_t *file) {
|
errorret_t assetFileOpen(assetfile_t *file) {
|
||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
assertNotNull(file->filename, "Asset file filename cannot be NULL.");
|
assertNotNull(file->filename, "Asset file filename cannot be NULL.");
|
||||||
assertNotNull(file->sourceZip, "Asset file must be inited before opening.");
|
assertNotNull(ASSET.zip, "Asset zip cannot be NULL.");
|
||||||
assertNull(file->zipFile, "Asset file already open.");
|
assertNull(file->zipFile, "Asset file already open.");
|
||||||
|
|
||||||
threadMutexLock(&ASSET.zipLock);
|
file->zipFile = zip_fopen(ASSET.zip, file->filename, 0);
|
||||||
file->zipFile = zip_fopen(file->sourceZip, file->filename, 0);
|
|
||||||
threadMutexUnlock(&ASSET.zipLock);
|
|
||||||
if(file->zipFile == NULL) {
|
if(file->zipFile == NULL) {
|
||||||
errorThrow("Failed to open asset file: %s", file->filename);
|
errorThrow("Failed to open asset file: %s", file->filename);
|
||||||
}
|
}
|
||||||
@@ -111,52 +79,21 @@ errorret_t assetFileRead(
|
|||||||
uint8_t tempBuffer[256];
|
uint8_t tempBuffer[256];
|
||||||
while(bytesRemaining > 0) {
|
while(bytesRemaining > 0) {
|
||||||
size_t chunkSize = mathMin(bytesRemaining, sizeof(tempBuffer));
|
size_t chunkSize = mathMin(bytesRemaining, sizeof(tempBuffer));
|
||||||
// The recursive call below already advances file->position by
|
|
||||||
// chunkSize (the non-NULL branch does this itself) - do not also
|
|
||||||
// advance it here, or every skip ends up double-counted.
|
|
||||||
errorChain(assetFileRead(file, tempBuffer, chunkSize));
|
errorChain(assetFileRead(file, tempBuffer, chunkSize));
|
||||||
|
file->position += chunkSize;
|
||||||
bytesRemaining -= chunkSize;
|
bytesRemaining -= chunkSize;
|
||||||
}
|
}
|
||||||
file->lastRead = bufferSize;
|
file->lastRead = bufferSize;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Some zip_fread() implementations (seen on PSP) reject a single call
|
// I assume zip_fread takes buffer NULL for skipping?
|
||||||
// asking for the entire (potentially large) file at once with EINVAL;
|
zip_int64_t bytesRead = zip_fread(file->zipFile, buffer, bufferSize);
|
||||||
// the line reader above only ever asks for up to 1024 bytes per call and
|
if(bytesRead < 0) {
|
||||||
// works fine, so read in bounded chunks here too.
|
errorThrow("Failed to read from asset file: %s", file->filename);
|
||||||
size_t totalRead = 0;
|
|
||||||
uint8_t *dest = (uint8_t *)buffer;
|
|
||||||
while(totalRead < bufferSize) {
|
|
||||||
size_t chunkSize = mathMin(
|
|
||||||
bufferSize - totalRead, ASSET_FILE_READ_CHUNK_MAX
|
|
||||||
);
|
|
||||||
threadMutexLock(&ASSET.zipLock);
|
|
||||||
zip_int64_t bytesRead = zip_fread(
|
|
||||||
file->zipFile, dest + totalRead, chunkSize
|
|
||||||
);
|
|
||||||
errorret_t readError = errorOkImpl();
|
|
||||||
if(bytesRead < 0) {
|
|
||||||
// Built (not thrown) while still holding the lock, so
|
|
||||||
// zip_file_strerror() reads the just-failed zipFile's error state
|
|
||||||
// before another thread can touch it - errorThrow() itself isn't
|
|
||||||
// used here since it returns immediately, which would leave
|
|
||||||
// ASSET.zipLock held forever.
|
|
||||||
readError = errorThrowImpl(
|
|
||||||
&ERROR_STATE, ERROR_NOT_OK, __FILE__, __func__, __LINE__,
|
|
||||||
"Failed to read from asset file: %s (%s)",
|
|
||||||
file->filename, zip_file_strerror(file->zipFile)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
threadMutexUnlock(&ASSET.zipLock);
|
|
||||||
if(errorIsNotOk(readError)) {
|
|
||||||
errorChain(readError);
|
|
||||||
}
|
|
||||||
if(bytesRead == 0) break;
|
|
||||||
totalRead += (size_t)bytesRead;
|
|
||||||
}
|
}
|
||||||
file->position += totalRead;
|
file->position += bytesRead;
|
||||||
file->lastRead = totalRead;
|
file->lastRead = bytesRead;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,10 +101,7 @@ errorret_t assetFileClose(assetfile_t *file) {
|
|||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
assertNotNull(file, "Asset file cannot be NULL.");
|
||||||
assertNotNull(file->zipFile, "Asset file must be opened before closing.");
|
assertNotNull(file->zipFile, "Asset file must be opened before closing.");
|
||||||
|
|
||||||
threadMutexLock(&ASSET.zipLock);
|
if(zip_fclose(file->zipFile) != 0) {
|
||||||
int closeResult = zip_fclose(file->zipFile);
|
|
||||||
threadMutexUnlock(&ASSET.zipLock);
|
|
||||||
if(closeResult != 0) {
|
|
||||||
errorThrow("Failed to close asset file: %s", file->filename);
|
errorThrow("Failed to close asset file: %s", file->filename);
|
||||||
}
|
}
|
||||||
file->zipFile = NULL;
|
file->zipFile = NULL;
|
||||||
@@ -267,7 +201,7 @@ const uint8_t *assetFileLineReaderUnreadPtr(
|
|||||||
return reader->readBuffer + reader->bufferStart;
|
return reader->readBuffer + reader->bufferStart;
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetFileLineReaderAppend(
|
static errorret_t assetFileLineReaderAppend(
|
||||||
assetfilelinereader_t *reader,
|
assetfilelinereader_t *reader,
|
||||||
const uint8_t *src,
|
const uint8_t *src,
|
||||||
size_t srcLength
|
size_t srcLength
|
||||||
@@ -279,7 +213,7 @@ errorret_t assetFileLineReaderAppend(
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
// reserve room for optional NUL terminator
|
/* reserve room for optional NUL terminator */
|
||||||
if(reader->lineLength + srcLength >= reader->outBufferSize) {
|
if(reader->lineLength + srcLength >= reader->outBufferSize) {
|
||||||
errorThrow("Line length exceeds output buffer size.");
|
errorThrow("Line length exceeds output buffer size.");
|
||||||
}
|
}
|
||||||
@@ -289,7 +223,7 @@ errorret_t assetFileLineReaderAppend(
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
|
static void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
|
||||||
assertNotNull(reader, "Reader cannot be NULL.");
|
assertNotNull(reader, "Reader cannot be NULL.");
|
||||||
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
|
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
|
||||||
assertTrue(
|
assertTrue(
|
||||||
@@ -299,7 +233,7 @@ void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
|
|||||||
reader->outBuffer[reader->lineLength] = '\0';
|
reader->outBuffer[reader->lineLength] = '\0';
|
||||||
}
|
}
|
||||||
|
|
||||||
ssize_t assetFileLineReaderFindNewline(
|
static ssize_t assetFileLineReaderFindNewline(
|
||||||
const assetfilelinereader_t *reader
|
const assetfilelinereader_t *reader
|
||||||
) {
|
) {
|
||||||
size_t i;
|
size_t i;
|
||||||
@@ -328,7 +262,7 @@ errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader) {
|
|||||||
|
|
||||||
size_t unreadBytes = assetFileLineReaderUnreadBytes(reader);
|
size_t unreadBytes = assetFileLineReaderUnreadBytes(reader);
|
||||||
|
|
||||||
// If buffer is fully consumed, refill from start.
|
/* If buffer is fully consumed, refill from start. */
|
||||||
if(unreadBytes == 0) {
|
if(unreadBytes == 0) {
|
||||||
reader->bufferStart = 0;
|
reader->bufferStart = 0;
|
||||||
reader->bufferEnd = 0;
|
reader->bufferEnd = 0;
|
||||||
@@ -349,14 +283,18 @@ errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader) {
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
// There are unread bytes left but no newline in them.
|
/*
|
||||||
// If bufferStart > 0, slide unread bytes to front so we can read more.
|
* There are unread bytes left but no newline in them.
|
||||||
// This only happens when necessary to make space.
|
* If bufferStart > 0, slide unread bytes to front so we can read more.
|
||||||
|
* This only happens when necessary to make space.
|
||||||
|
*/
|
||||||
if(reader->bufferEnd == reader->readBufferSize) {
|
if(reader->bufferEnd == reader->readBufferSize) {
|
||||||
if(reader->bufferStart == 0) {
|
if(reader->bufferStart == 0) {
|
||||||
// Entire read buffer is unread and contains no newline.
|
/*
|
||||||
// Caller must have a large enough outBuffer to accumulate across fills,
|
* Entire read buffer is unread and contains no newline.
|
||||||
// so we consume these bytes into outBuffer before refilling.
|
* Caller must have a large enough outBuffer to accumulate across fills,
|
||||||
|
* so we consume these bytes into outBuffer before refilling.
|
||||||
|
*/
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -399,7 +337,7 @@ errorret_t assetFileLineReaderNext(assetfilelinereader_t *reader) {
|
|||||||
size_t chunkLength = (size_t)newlineIndex - reader->bufferStart;
|
size_t chunkLength = (size_t)newlineIndex - reader->bufferStart;
|
||||||
errorret_t ret;
|
errorret_t ret;
|
||||||
|
|
||||||
// strip CR in CRLF
|
/* strip CR in CRLF */
|
||||||
if(
|
if(
|
||||||
chunkLength > 0 &&
|
chunkLength > 0 &&
|
||||||
reader->readBuffer[(size_t)newlineIndex - 1] == '\r'
|
reader->readBuffer[(size_t)newlineIndex - 1] == '\r'
|
||||||
|
|||||||
@@ -11,12 +11,6 @@
|
|||||||
|
|
||||||
#define ASSET_FILE_NAME_MAX 48
|
#define ASSET_FILE_NAME_MAX 48
|
||||||
|
|
||||||
// Max bytes requested per zip_fread() call in assetFileRead(). Some
|
|
||||||
// zip_fread() implementations (seen on PSP) reject a single call asking
|
|
||||||
// for very large amounts of data at once; the locale line reader has
|
|
||||||
// always used 1024-byte reads successfully, so that's the proven-safe cap.
|
|
||||||
#define ASSET_FILE_READ_CHUNK_MAX 1024
|
|
||||||
|
|
||||||
typedef struct assetfile_s assetfile_t;
|
typedef struct assetfile_s assetfile_t;
|
||||||
|
|
||||||
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
|
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
|
||||||
@@ -32,11 +26,6 @@ typedef struct assetfile_s {
|
|||||||
zip_int64_t position;
|
zip_int64_t position;
|
||||||
zip_int64_t lastRead;
|
zip_int64_t lastRead;
|
||||||
zip_file_t *zipFile;
|
zip_file_t *zipFile;
|
||||||
|
|
||||||
// The archive this file was found in (ASSET.zip or ASSET.zipStored),
|
|
||||||
// set by assetFileInit and used by assetFileOpen so lookups fall back
|
|
||||||
// correctly between the two dusk.dsk archives.
|
|
||||||
zip_t *sourceZip;
|
|
||||||
} assetfile_t;
|
} assetfile_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -155,63 +144,6 @@ void assetFileLineReaderInit(
|
|||||||
const size_t outBufferSize
|
const size_t outBufferSize
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the number of bytes still unread in the line reader's read buffer.
|
|
||||||
*
|
|
||||||
* @param reader The line reader to check.
|
|
||||||
* @return Number of unread bytes remaining in the read buffer.
|
|
||||||
*/
|
|
||||||
size_t assetFileLineReaderUnreadBytes(const assetfilelinereader_t *reader);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a pointer to the first unread byte in the line reader's read
|
|
||||||
* buffer.
|
|
||||||
*
|
|
||||||
* @param reader The line reader to check.
|
|
||||||
* @return Pointer to the first unread byte.
|
|
||||||
*/
|
|
||||||
const uint8_t *assetFileLineReaderUnreadPtr(
|
|
||||||
const assetfilelinereader_t *reader
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Appends src to the line reader's current line buffer, growing lineLength.
|
|
||||||
*
|
|
||||||
* @param reader The line reader whose out buffer to append to.
|
|
||||||
* @param src Bytes to append.
|
|
||||||
* @param srcLength Number of bytes in src.
|
|
||||||
* @return Error state if any (the line would exceed the output buffer).
|
|
||||||
*/
|
|
||||||
errorret_t assetFileLineReaderAppend(
|
|
||||||
assetfilelinereader_t *reader,
|
|
||||||
const uint8_t *src,
|
|
||||||
size_t srcLength
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Null-terminates the line reader's current line buffer at lineLength.
|
|
||||||
*
|
|
||||||
* @param reader The line reader whose out buffer to terminate.
|
|
||||||
*/
|
|
||||||
void assetFileLineReaderTerminate(assetfilelinereader_t *reader);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Searches the line reader's unread buffered bytes for a newline character.
|
|
||||||
*
|
|
||||||
* @param reader The line reader to search.
|
|
||||||
* @return The index of the newline within readBuffer, or -1 if not found.
|
|
||||||
*/
|
|
||||||
ssize_t assetFileLineReaderFindNewline(const assetfilelinereader_t *reader);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Refills the line reader's read buffer from the underlying file once its
|
|
||||||
* buffered bytes are fully consumed. A no-op once the file is at EOF.
|
|
||||||
*
|
|
||||||
* @param reader The line reader to refill.
|
|
||||||
* @return Error state if any.
|
|
||||||
*/
|
|
||||||
errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads the next line from the asset file into the line buffer. The line
|
* Reads the next line from the asset file into the line buffer. The line
|
||||||
* buffer is null-terminated and does not include the newline character.
|
* buffer is null-terminated and does not include the newline character.
|
||||||
|
|||||||
@@ -15,8 +15,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
|||||||
add_subdirectory(display)
|
add_subdirectory(display)
|
||||||
add_subdirectory(locale)
|
add_subdirectory(locale)
|
||||||
add_subdirectory(json)
|
add_subdirectory(json)
|
||||||
add_subdirectory(chunk)
|
|
||||||
add_subdirectory(dmf)
|
add_subdirectory(dmf)
|
||||||
add_subdirectory(cutscene)
|
add_subdirectory(animation)
|
||||||
add_subdirectory(wav)
|
|
||||||
add_subdirectory(mp3)
|
|
||||||
+1
-1
@@ -5,5 +5,5 @@
|
|||||||
|
|
||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
assetcutsceneloader.c
|
assetanimationloader.c
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetanimationloader.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/string.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
|
errorret_t assetAnimationLoaderAsync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertNotMainThread("Async loader should not be on main thread.");
|
||||||
|
|
||||||
|
if(
|
||||||
|
loading->loading.animation.state != ASSET_ANIMATION_LOADING_STATE_READ_FILE
|
||||||
|
) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNull(loading->loading.animation.buffer, "Buffer already defined?");
|
||||||
|
|
||||||
|
assetfile_t *file = &loading->loading.animation.file;
|
||||||
|
assetLoaderErrorChain(
|
||||||
|
loading, assetFileInit(file, loading->entry->name, NULL, NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
if(file->size > ASSET_ANIMATION_FILE_SIZE_MAX) {
|
||||||
|
assetLoaderErrorThrow(
|
||||||
|
loading, "Animation JSON exceeds maximum allowed size"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t *buffer;
|
||||||
|
size_t size;
|
||||||
|
assetLoaderErrorChain(loading, assetFileReadEntire(file, &buffer, &size));
|
||||||
|
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||||
|
|
||||||
|
loading->loading.animation.buffer = buffer;
|
||||||
|
loading->loading.animation.size = size;
|
||||||
|
loading->loading.animation.state = ASSET_ANIMATION_LOADING_STATE_PARSE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetAnimationLoaderSync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertTrue(loading->type == ASSET_LOADER_TYPE_ANIMATION, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
switch(loading->loading.animation.state) {
|
||||||
|
case ASSET_ANIMATION_LOADING_STATE_INITIAL:
|
||||||
|
loading->loading.animation.state =
|
||||||
|
ASSET_ANIMATION_LOADING_STATE_READ_FILE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_ANIMATION_LOADING_STATE_PARSE:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t *buffer = loading->loading.animation.buffer;
|
||||||
|
assertNotNull(buffer, "Animation buffer should have been loaded by now.");
|
||||||
|
|
||||||
|
yyjson_doc *doc = yyjson_read(
|
||||||
|
(char *)buffer,
|
||||||
|
loading->loading.animation.size,
|
||||||
|
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
|
||||||
|
);
|
||||||
|
memoryFree(buffer);
|
||||||
|
loading->loading.animation.buffer = NULL;
|
||||||
|
|
||||||
|
if(!doc) assetLoaderErrorThrow(loading, "Failed to parse animation JSON");
|
||||||
|
|
||||||
|
yyjson_val *root = yyjson_doc_get_root(doc);
|
||||||
|
yyjson_val *channelsVal = yyjson_obj_get(root, "channels");
|
||||||
|
if(!channelsVal || !yyjson_is_arr(channelsVal)) {
|
||||||
|
yyjson_doc_free(doc);
|
||||||
|
assetLoaderErrorThrow(loading, "Animation JSON missing 'channels' array");
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t channelCount = (uint16_t)yyjson_arr_size(channelsVal);
|
||||||
|
if(channelCount == 0) {
|
||||||
|
yyjson_doc_free(doc);
|
||||||
|
assetLoaderErrorThrow(loading, "Animation must have at least one channel");
|
||||||
|
}
|
||||||
|
|
||||||
|
keyframe_t **tracks = memoryAllocate(channelCount * sizeof(keyframe_t *));
|
||||||
|
uint16_t *trackCounts = memoryAllocate(channelCount * sizeof(uint16_t));
|
||||||
|
|
||||||
|
size_t idx, max;
|
||||||
|
yyjson_val *channelJson;
|
||||||
|
uint16_t parsed = 0;
|
||||||
|
yyjson_arr_foreach(channelsVal, idx, max, channelJson) {
|
||||||
|
keyframe_t *keyframes;
|
||||||
|
uint16_t count;
|
||||||
|
errorret_t ret =
|
||||||
|
assetAnimationParseChannel(channelJson, &keyframes, &count);
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
assetAnimationFreeChannels(tracks, parsed);
|
||||||
|
memoryFree(trackCounts);
|
||||||
|
yyjson_doc_free(doc);
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||||
|
errorChain(ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
tracks[idx] = keyframes;
|
||||||
|
trackCounts[idx] = count;
|
||||||
|
parsed++;
|
||||||
|
}
|
||||||
|
|
||||||
|
animationInit(
|
||||||
|
&loading->entry->data.animation, tracks, trackCounts, channelCount
|
||||||
|
);
|
||||||
|
|
||||||
|
yyjson_val *loopVal = yyjson_obj_get(root, "loop");
|
||||||
|
if(loopVal) loading->entry->data.animation.loop = yyjson_get_bool(loopVal);
|
||||||
|
|
||||||
|
yyjson_val *speedVal = yyjson_obj_get(root, "speed");
|
||||||
|
if(speedVal) {
|
||||||
|
loading->entry->data.animation.speed = (float_t)yyjson_get_num(speedVal);
|
||||||
|
}
|
||||||
|
|
||||||
|
yyjson_doc_free(doc);
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetAnimationDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
|
assertTrue(entry->type == ASSET_LOADER_TYPE_ANIMATION, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
// A load that failed before animationInit() ran (e.g. a parse error)
|
||||||
|
// never populated these -- nothing to free in that case.
|
||||||
|
keyframeset_t *set = &entry->data.animation.keyframes;
|
||||||
|
if(set->tracks) {
|
||||||
|
assetAnimationFreeChannels(set->tracks, set->trackCount);
|
||||||
|
memoryFree(set->trackCounts);
|
||||||
|
set->tracks = NULL;
|
||||||
|
set->trackCounts = NULL;
|
||||||
|
set->trackCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetAnimationParseEasing(
|
||||||
|
const char_t *name,
|
||||||
|
easingtype_t *outEasing
|
||||||
|
) {
|
||||||
|
if(stringEquals(name, "LINEAR")) *outEasing = EASING_LINEAR;
|
||||||
|
else if(stringEquals(name, "IN_SINE")) *outEasing = EASING_IN_SINE;
|
||||||
|
else if(stringEquals(name, "OUT_SINE")) *outEasing = EASING_OUT_SINE;
|
||||||
|
else if(stringEquals(name, "IN_OUT_SINE")) *outEasing = EASING_IN_OUT_SINE;
|
||||||
|
else if(stringEquals(name, "IN_QUAD")) *outEasing = EASING_IN_QUAD;
|
||||||
|
else if(stringEquals(name, "OUT_QUAD")) *outEasing = EASING_OUT_QUAD;
|
||||||
|
else if(stringEquals(name, "IN_OUT_QUAD")) *outEasing = EASING_IN_OUT_QUAD;
|
||||||
|
else if(stringEquals(name, "IN_CUBIC")) *outEasing = EASING_IN_CUBIC;
|
||||||
|
else if(stringEquals(name, "OUT_CUBIC")) *outEasing = EASING_OUT_CUBIC;
|
||||||
|
else if(stringEquals(name, "IN_OUT_CUBIC")) *outEasing = EASING_IN_OUT_CUBIC;
|
||||||
|
else if(stringEquals(name, "IN_QUART")) *outEasing = EASING_IN_QUART;
|
||||||
|
else if(stringEquals(name, "OUT_QUART")) *outEasing = EASING_OUT_QUART;
|
||||||
|
else if(stringEquals(name, "IN_OUT_QUART")) *outEasing = EASING_IN_OUT_QUART;
|
||||||
|
else if(stringEquals(name, "IN_BACK")) *outEasing = EASING_IN_BACK;
|
||||||
|
else if(stringEquals(name, "OUT_BACK")) *outEasing = EASING_OUT_BACK;
|
||||||
|
else if(stringEquals(name, "IN_OUT_BACK")) *outEasing = EASING_IN_OUT_BACK;
|
||||||
|
else errorThrow("Unknown easing type '%s'", name);
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetAnimationParseChannel(
|
||||||
|
yyjson_val *channelJson,
|
||||||
|
keyframe_t **outKeyframes,
|
||||||
|
uint16_t *outCount
|
||||||
|
) {
|
||||||
|
if(!yyjson_is_arr(channelJson)) {
|
||||||
|
errorThrow("Animation channel must be an array");
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t count = yyjson_arr_size(channelJson);
|
||||||
|
if(count == 0) {
|
||||||
|
errorThrow("Animation channel must have at least one keyframe");
|
||||||
|
}
|
||||||
|
|
||||||
|
keyframe_t *keyframes = memoryAllocate(count * sizeof(keyframe_t));
|
||||||
|
|
||||||
|
size_t idx, max;
|
||||||
|
yyjson_val *keyframeJson;
|
||||||
|
yyjson_arr_foreach(channelJson, idx, max, keyframeJson) {
|
||||||
|
yyjson_val *timeVal = yyjson_obj_get(keyframeJson, "time");
|
||||||
|
yyjson_val *valueVal = yyjson_obj_get(keyframeJson, "value");
|
||||||
|
if(!timeVal || !valueVal) {
|
||||||
|
memoryFree(keyframes);
|
||||||
|
errorThrow("Animation keyframe missing 'time' or 'value'");
|
||||||
|
}
|
||||||
|
|
||||||
|
keyframes[idx].time = (float_t)yyjson_get_num(timeVal);
|
||||||
|
keyframes[idx].value = (float_t)yyjson_get_num(valueVal);
|
||||||
|
|
||||||
|
yyjson_val *easingVal = yyjson_obj_get(keyframeJson, "easing");
|
||||||
|
if(!easingVal) {
|
||||||
|
keyframes[idx].easing = EASING_LINEAR;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t ret = assetAnimationParseEasing(
|
||||||
|
yyjson_get_str(easingVal), &keyframes[idx].easing
|
||||||
|
);
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
memoryFree(keyframes);
|
||||||
|
errorChain(ret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
*outKeyframes = keyframes;
|
||||||
|
*outCount = (uint16_t)count;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetAnimationFreeChannels(keyframe_t **tracks, const uint16_t count) {
|
||||||
|
for(uint16_t i = 0; i < count; i++) memoryFree(tracks[i]);
|
||||||
|
memoryFree(tracks);
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "error/error.h"
|
||||||
|
#include "asset/assetfile.h"
|
||||||
|
#include "animation/animation.h"
|
||||||
|
#include "yyjson.h"
|
||||||
|
|
||||||
|
#define ASSET_ANIMATION_FILE_SIZE_MAX 1024*256
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSON animation file format:
|
||||||
|
* {
|
||||||
|
* "loop": false,
|
||||||
|
* "speed": 1.0,
|
||||||
|
* "channels": [
|
||||||
|
* [
|
||||||
|
* { "time": 0.0, "value": 0.0, "easing": "LINEAR" },
|
||||||
|
* { "time": 1.0, "value": 10.0 }
|
||||||
|
* ]
|
||||||
|
* ]
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* "loop" and "speed" are optional, defaulting to false and 1.0 (see
|
||||||
|
* animationInit()). "channels" is required and must have at least one
|
||||||
|
* entry; each entry is itself a non-empty array of keyframes, ascending
|
||||||
|
* by "time", sharing one timeline with every other channel (see
|
||||||
|
* keyframeset_t). Each keyframe requires "time" and "value"; "easing" is
|
||||||
|
* optional and defaults to "LINEAR" (see easingtype_t for the full set of
|
||||||
|
* names, e.g. "IN_QUAD", "OUT_BACK", "IN_OUT_CUBIC").
|
||||||
|
*/
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_ANIMATION_LOADING_STATE_INITIAL,
|
||||||
|
ASSET_ANIMATION_LOADING_STATE_READ_FILE,
|
||||||
|
ASSET_ANIMATION_LOADING_STATE_PARSE,
|
||||||
|
ASSET_ANIMATION_LOADING_STATE_DONE
|
||||||
|
} assetanimationloadingstate_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetfile_t file;
|
||||||
|
assetanimationloadingstate_t state;
|
||||||
|
uint8_t *buffer;
|
||||||
|
size_t size;
|
||||||
|
} assetanimationloaderloading_t;
|
||||||
|
|
||||||
|
typedef animation_t assetanimationoutput_t;
|
||||||
|
|
||||||
|
errorret_t assetAnimationLoaderAsync(assetloading_t *loading);
|
||||||
|
errorret_t assetAnimationLoaderSync(assetloading_t *loading);
|
||||||
|
errorret_t assetAnimationDispose(assetentry_t *entry);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal. Maps a JSON easing name (e.g. "IN_OUT_QUAD") to its
|
||||||
|
* easingtype_t.
|
||||||
|
*
|
||||||
|
* @param name The easing name to parse.
|
||||||
|
* @param outEasing Destination for the parsed easing type.
|
||||||
|
* @return Error state; fails if name doesn't match any easingtype_t.
|
||||||
|
*/
|
||||||
|
errorret_t assetAnimationParseEasing(
|
||||||
|
const char_t *name,
|
||||||
|
easingtype_t *outEasing
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal. Parses one "channels" array entry into a heap-allocated
|
||||||
|
* keyframe_t array (memoryAllocate) -- freed later by
|
||||||
|
* assetAnimationFreeChannels() (on a parse failure) or
|
||||||
|
* assetAnimationDispose() (once loaded).
|
||||||
|
*
|
||||||
|
* @param channelJson The channel's JSON array of keyframe objects.
|
||||||
|
* @param outKeyframes Destination for the newly allocated keyframe array.
|
||||||
|
* @param outCount Destination for the number of keyframes parsed.
|
||||||
|
* @return Error state.
|
||||||
|
*/
|
||||||
|
errorret_t assetAnimationParseChannel(
|
||||||
|
yyjson_val *channelJson,
|
||||||
|
keyframe_t **outKeyframes,
|
||||||
|
uint16_t *outCount
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal. Frees the first count entries of tracks (each a
|
||||||
|
* memoryAllocate'd keyframe_t array from assetAnimationParseChannel()),
|
||||||
|
* then frees tracks itself. Used both to unwind a partially-parsed
|
||||||
|
* channel list on failure and to free a fully-loaded animation's
|
||||||
|
* channels in assetAnimationDispose().
|
||||||
|
*
|
||||||
|
* @param tracks The channel array to free.
|
||||||
|
* @param count The number of entries in tracks to free.
|
||||||
|
*/
|
||||||
|
void assetAnimationFreeChannels(keyframe_t **tracks, const uint16_t count);
|
||||||
@@ -35,6 +35,22 @@ void assetEntryInit(
|
|||||||
entry->input = NULL;
|
entry->input = NULL;
|
||||||
}
|
}
|
||||||
refInit(&entry->refs, entry, NULL, NULL, NULL);
|
refInit(&entry->refs, entry, NULL, NULL, NULL);
|
||||||
|
|
||||||
|
eventInit(
|
||||||
|
&entry->onLoaded,
|
||||||
|
entry->onLoadedCallbacks, entry->onLoadedUsers,
|
||||||
|
ASSET_ENTRY_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&entry->onUnloaded,
|
||||||
|
entry->onUnloadedCallbacks, entry->onUnloadedUsers,
|
||||||
|
ASSET_ENTRY_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&entry->onError,
|
||||||
|
entry->onErrorCallbacks, entry->onErrorUsers,
|
||||||
|
ASSET_ENTRY_EVENT_MAX
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void assetEntryLock(assetentry_t *entry) {
|
void assetEntryLock(assetentry_t *entry) {
|
||||||
@@ -81,7 +97,7 @@ errorret_t assetEntryDispose(assetentry_t *entry) {
|
|||||||
"Asset entry still refed at dispose time."
|
"Asset entry still refed at dispose time."
|
||||||
);
|
);
|
||||||
|
|
||||||
if(entry->onUnloaded) entry->onUnloaded(entry, entry->onUnloadedUser);
|
eventInvoke(&entry->onUnloaded, entry);
|
||||||
errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry));
|
errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry));
|
||||||
memoryZero(entry, sizeof(assetentry_t));
|
memoryZero(entry, sizeof(assetentry_t));
|
||||||
errorOk();
|
errorOk();
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/loader/assetloading.h"
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "event/event.h"
|
||||||
#include "util/ref.h"
|
#include "util/ref.h"
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
@@ -19,16 +20,10 @@ typedef enum {
|
|||||||
ASSET_ENTRY_STATE_ERROR
|
ASSET_ENTRY_STATE_ERROR
|
||||||
} assetentrystate_t;
|
} assetentrystate_t;
|
||||||
|
|
||||||
typedef struct assetentry_s assetentry_t;
|
/** Maximum number of subscribers for each per-entry event. */
|
||||||
|
#define ASSET_ENTRY_EVENT_MAX 2
|
||||||
|
|
||||||
/**
|
typedef struct assetentry_s assetentry_t;
|
||||||
* A single asset entry callback. Each entry supports at most one subscriber
|
|
||||||
* per event - a second assignment without clearing the first is a bug.
|
|
||||||
*
|
|
||||||
* @param entry The assetentry_t the event fired on.
|
|
||||||
* @param user The user pointer passed alongside the callback.
|
|
||||||
*/
|
|
||||||
typedef void (*assetentrycallback_t)(assetentry_t *entry, void *user);
|
|
||||||
|
|
||||||
struct assetentry_s {
|
struct assetentry_s {
|
||||||
char_t name[ASSET_FILE_NAME_MAX];
|
char_t name[ASSET_FILE_NAME_MAX];
|
||||||
@@ -38,27 +33,30 @@ struct assetentry_s {
|
|||||||
ref_t refs;
|
ref_t refs;
|
||||||
assetloaderinput_t *input;
|
assetloaderinput_t *input;
|
||||||
assetloaderinput_t inputData;
|
assetloaderinput_t inputData;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fired once when loading completes successfully.
|
* Fired once when loading completes successfully (params = assetentry_t *).
|
||||||
* Always invoked on the main thread.
|
* Always invoked on the main thread.
|
||||||
*/
|
*/
|
||||||
assetentrycallback_t onLoaded;
|
event_t onLoaded;
|
||||||
void *onLoadedUser;
|
eventcallback_t onLoadedCallbacks[ASSET_ENTRY_EVENT_MAX];
|
||||||
|
void *onLoadedUsers[ASSET_ENTRY_EVENT_MAX];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fired once when the entry is disposed/reaped. The asset data is still
|
* Fired once when the entry is disposed/reaped (params = assetentry_t *).
|
||||||
* accessible when the callback runs. Always invoked on the main thread.
|
* The asset data is still accessible when the callback runs.
|
||||||
*/
|
|
||||||
assetentrycallback_t onUnloaded;
|
|
||||||
void *onUnloadedUser;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fired once when loading fails.
|
|
||||||
* Always invoked on the main thread.
|
* Always invoked on the main thread.
|
||||||
*/
|
*/
|
||||||
assetentrycallback_t onError;
|
event_t onUnloaded;
|
||||||
void *onErrorUser;
|
eventcallback_t onUnloadedCallbacks[ASSET_ENTRY_EVENT_MAX];
|
||||||
|
void *onUnloadedUsers[ASSET_ENTRY_EVENT_MAX];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fired once when loading fails (params = assetentry_t *).
|
||||||
|
* Always invoked on the main thread.
|
||||||
|
*/
|
||||||
|
event_t onError;
|
||||||
|
eventcallback_t onErrorCallbacks[ASSET_ENTRY_EVENT_MAX];
|
||||||
|
void *onErrorUsers[ASSET_ENTRY_EVENT_MAX];
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -46,27 +46,9 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
|
|||||||
.dispose = assetJsonDispose
|
.dispose = assetJsonDispose
|
||||||
},
|
},
|
||||||
|
|
||||||
[ASSET_LOADER_TYPE_CHUNK] = {
|
[ASSET_LOADER_TYPE_ANIMATION] = {
|
||||||
.loadSync = assetChunkLoaderSync,
|
.loadSync = assetAnimationLoaderSync,
|
||||||
.loadAsync = assetChunkLoaderAsync,
|
.loadAsync = assetAnimationLoaderAsync,
|
||||||
.dispose = assetChunkDispose
|
.dispose = assetAnimationDispose
|
||||||
},
|
|
||||||
|
|
||||||
[ASSET_LOADER_TYPE_CUTSCENE] = {
|
|
||||||
.loadSync = assetCutsceneLoaderSync,
|
|
||||||
.loadAsync = assetCutsceneLoaderAsync,
|
|
||||||
.dispose = assetCutsceneDispose
|
|
||||||
},
|
|
||||||
|
|
||||||
[ASSET_LOADER_TYPE_WAV] = {
|
|
||||||
.loadSync = assetWavLoaderSync,
|
|
||||||
.loadAsync = assetWavLoaderAsync,
|
|
||||||
.dispose = assetWavDispose
|
|
||||||
},
|
|
||||||
|
|
||||||
[ASSET_LOADER_TYPE_MP3] = {
|
|
||||||
.loadSync = assetMp3LoaderSync,
|
|
||||||
.loadAsync = assetMp3LoaderAsync,
|
|
||||||
.dispose = assetMp3Dispose
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -12,10 +12,7 @@
|
|||||||
#include "asset/loader/display/assettilesetloader.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"
|
||||||
#include "asset/loader/chunk/assetchunkloader.h"
|
#include "asset/loader/animation/assetanimationloader.h"
|
||||||
#include "asset/loader/cutscene/assetcutsceneloader.h"
|
|
||||||
#include "asset/loader/wav/assetwavloader.h"
|
|
||||||
#include "asset/loader/mp3/assetmp3loader.h"
|
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
ASSET_LOADER_TYPE_NULL,
|
ASSET_LOADER_TYPE_NULL,
|
||||||
@@ -26,10 +23,7 @@ typedef enum {
|
|||||||
ASSET_LOADER_TYPE_TILESET,
|
ASSET_LOADER_TYPE_TILESET,
|
||||||
ASSET_LOADER_TYPE_LOCALE,
|
ASSET_LOADER_TYPE_LOCALE,
|
||||||
ASSET_LOADER_TYPE_JSON,
|
ASSET_LOADER_TYPE_JSON,
|
||||||
ASSET_LOADER_TYPE_CHUNK,
|
ASSET_LOADER_TYPE_ANIMATION,
|
||||||
ASSET_LOADER_TYPE_CUTSCENE,
|
|
||||||
ASSET_LOADER_TYPE_WAV,
|
|
||||||
ASSET_LOADER_TYPE_MP3,
|
|
||||||
|
|
||||||
ASSET_LOADER_TYPE_COUNT
|
ASSET_LOADER_TYPE_COUNT
|
||||||
} assetloadertype_t;
|
} assetloadertype_t;
|
||||||
@@ -41,10 +35,7 @@ typedef union {
|
|||||||
assettilesetloaderloading_t tileset;
|
assettilesetloaderloading_t tileset;
|
||||||
assetlocaleloaderloading_t locale;
|
assetlocaleloaderloading_t locale;
|
||||||
assetjsonloaderloading_t json;
|
assetjsonloaderloading_t json;
|
||||||
assetchunkloaderloading_t chunk;
|
assetanimationloaderloading_t animation;
|
||||||
assetcutsceneloaderloading_t cutscene;
|
|
||||||
assetwavloaderloading_t wav;
|
|
||||||
assetmp3loaderloading_t mp3;
|
|
||||||
} assetloaderloading_t;
|
} assetloaderloading_t;
|
||||||
|
|
||||||
typedef union {
|
typedef union {
|
||||||
@@ -54,10 +45,7 @@ typedef union {
|
|||||||
assettilesetoutput_t tileset;
|
assettilesetoutput_t tileset;
|
||||||
assetlocaleoutput_t locale;
|
assetlocaleoutput_t locale;
|
||||||
assetjsonoutput_t json;
|
assetjsonoutput_t json;
|
||||||
assetchunkoutput_t chunk;
|
assetanimationoutput_t animation;
|
||||||
assetcutsceneoutput_t cutscene;
|
|
||||||
assetwavoutput_t wav;
|
|
||||||
assetmp3output_t mp3;
|
|
||||||
} assetloaderoutput_t;
|
} assetloaderoutput_t;
|
||||||
|
|
||||||
typedef union {
|
typedef union {
|
||||||
@@ -65,10 +53,6 @@ typedef union {
|
|||||||
assettilesetloaderinput_t tileset;
|
assettilesetloaderinput_t tileset;
|
||||||
assetlocaleloaderinput_t locale;
|
assetlocaleloaderinput_t locale;
|
||||||
assetjsonloaderinput_t json;
|
assetjsonloaderinput_t json;
|
||||||
assetchunkloaderinput_t chunk;
|
|
||||||
assetcutsceneloaderinput_t cutscene;
|
|
||||||
assetwavloaderinput_t wav;
|
|
||||||
assetmp3loaderinput_t mp3;
|
|
||||||
} assetloaderinput_t;
|
} assetloaderinput_t;
|
||||||
|
|
||||||
typedef struct assetloading_s assetloading_t;
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
|||||||
@@ -1,238 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "assetchunkloader.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/endian.h"
|
|
||||||
#include "asset/loader/assetloading.h"
|
|
||||||
#include "asset/loader/assetentry.h"
|
|
||||||
#include "asset/loader/assetloader.h"
|
|
||||||
#include "asset/asset.h"
|
|
||||||
#include "rpg/overworld/worldpos.h"
|
|
||||||
|
|
||||||
errorret_t assetChunkLoaderAsync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertNotMainThread("Should be called from an async thread.");
|
|
||||||
|
|
||||||
if(loading->loading.chunk.state != ASSET_CHUNK_LOADING_STATE_READ_FILE) {
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
assertNull(loading->loading.chunk.data, "Data already defined?");
|
|
||||||
|
|
||||||
assetfile_t *file = &loading->loading.chunk.file;
|
|
||||||
assetLoaderErrorChain(loading,
|
|
||||||
assetFileInit(file, loading->entry->name, NULL, NULL)
|
|
||||||
);
|
|
||||||
|
|
||||||
uint8_t *data = memoryAllocate(file->size);
|
|
||||||
assetLoaderErrorChain(loading, assetFileOpen(file));
|
|
||||||
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size));
|
|
||||||
assetLoaderErrorChain(loading, assetFileClose(file));
|
|
||||||
assetLoaderErrorChain(loading, assetFileDispose(file));
|
|
||||||
assertTrue(
|
|
||||||
file->lastRead == file->size,
|
|
||||||
"Failed to read entire chunk file."
|
|
||||||
);
|
|
||||||
|
|
||||||
loading->loading.chunk.data = data;
|
|
||||||
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_PARSE;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetChunkLoaderSync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertTrue(loading->type == ASSET_LOADER_TYPE_CHUNK, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
assetchunkoutput_t *out = &loading->entry->data.chunk;
|
|
||||||
|
|
||||||
switch(loading->loading.chunk.state) {
|
|
||||||
case ASSET_CHUNK_LOADING_STATE_INITIAL:
|
|
||||||
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_READ_FILE;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
|
||||||
errorOk();
|
|
||||||
|
|
||||||
case ASSET_CHUNK_LOADING_STATE_PARSE:
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ASSET_CHUNK_LOADING_STATE_LOAD_MODELS:
|
|
||||||
while(loading->loading.chunk.modelIndex < out->meshCount) {
|
|
||||||
uint8_t m = loading->loading.chunk.modelIndex;
|
|
||||||
if(out->modelEntries[m] == NULL) {
|
|
||||||
out->modelEntries[m] = assetLock(
|
|
||||||
out->modelNames[m], ASSET_LOADER_TYPE_MODEL, NULL
|
|
||||||
);
|
|
||||||
assertNotNull(
|
|
||||||
out->modelEntries[m], "Failed to lock model."
|
|
||||||
);
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
if(out->modelEntries[m]->state == ASSET_ENTRY_STATE_ERROR) {
|
|
||||||
assetLoaderErrorThrow(
|
|
||||||
loading, "Model failed to load: %s", out->modelNames[m]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if(out->modelEntries[m]->state != ASSET_ENTRY_STATE_LOADED) {
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
loading->loading.chunk.modelIndex++;
|
|
||||||
}
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
|
||||||
errorOk();
|
|
||||||
|
|
||||||
default:
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t *data = loading->loading.chunk.data;
|
|
||||||
assertNotNull(data, "Chunk data should have been loaded by now.");
|
|
||||||
|
|
||||||
if(data[0] != 'D' || data[1] != 'C' || data[2] != 'F') {
|
|
||||||
memoryFree(data);
|
|
||||||
assetLoaderErrorThrow(loading, "Invalid chunk file header");
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t version = endianLittleToHost32(*(uint32_t *)(data + 4));
|
|
||||||
if(version != ASSET_CHUNK_FILE_VERSION) {
|
|
||||||
memoryFree(data);
|
|
||||||
assetLoaderErrorThrow(
|
|
||||||
loading, "Unsupported chunk file version %u", version
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t offset = 8;
|
|
||||||
|
|
||||||
size_t tileSize = CHUNK_TILE_COUNT * sizeof(tile_t);
|
|
||||||
out->tiles = memoryAllocate(tileSize);
|
|
||||||
memoryCopy(out->tiles, data + offset, tileSize);
|
|
||||||
offset += tileSize;
|
|
||||||
|
|
||||||
for(size_t t = 0; t < CHUNK_TILE_COUNT; t++) {
|
|
||||||
uint32_t *shape = (uint32_t *)&out->tiles[t].shape;
|
|
||||||
*shape = endianLittleToHost32(*shape);
|
|
||||||
}
|
|
||||||
|
|
||||||
out->meshCount = data[offset];
|
|
||||||
offset += sizeof(uint8_t);
|
|
||||||
assertTrue(
|
|
||||||
out->meshCount <= CHUNK_MESH_COUNT_MAX,
|
|
||||||
"Chunk mesh count exceeds maximum."
|
|
||||||
);
|
|
||||||
|
|
||||||
for(uint8_t m = 0; m < out->meshCount; m++) {
|
|
||||||
uint8_t nameLen = 0;
|
|
||||||
while(
|
|
||||||
data[offset + nameLen] != '\0' &&
|
|
||||||
nameLen < CHUNK_MESH_NAME_MAX - 1
|
|
||||||
) {
|
|
||||||
nameLen++;
|
|
||||||
}
|
|
||||||
memoryCopy(out->modelNames[m], data + offset, nameLen);
|
|
||||||
out->modelNames[m][nameLen] = '\0';
|
|
||||||
offset += nameLen + 1;
|
|
||||||
|
|
||||||
memoryCopy(out->meshOffsets[m], data + offset, sizeof(vec3));
|
|
||||||
offset += sizeof(vec3);
|
|
||||||
out->meshOffsets[m][0] = endianLittleToHostFloat(out->meshOffsets[m][0]);
|
|
||||||
out->meshOffsets[m][1] = endianLittleToHostFloat(out->meshOffsets[m][1]);
|
|
||||||
out->meshOffsets[m][2] = endianLittleToHostFloat(out->meshOffsets[m][2]);
|
|
||||||
}
|
|
||||||
|
|
||||||
out->entitySpawnCount = data[offset];
|
|
||||||
offset += sizeof(uint8_t);
|
|
||||||
assertTrue(
|
|
||||||
out->entitySpawnCount <= CHUNK_ENTITY_SPAWN_COUNT_MAX,
|
|
||||||
"Chunk entity spawn count exceeds maximum."
|
|
||||||
);
|
|
||||||
|
|
||||||
for(uint8_t s = 0; s < out->entitySpawnCount; s++) {
|
|
||||||
chunkentityspawn_t *spawn = &out->entitySpawns[s];
|
|
||||||
spawn->kind = (chunkentityspawnkind_t)data[offset];
|
|
||||||
offset += sizeof(uint8_t);
|
|
||||||
|
|
||||||
uint16_t a;
|
|
||||||
memoryCopy(&a, data + offset, sizeof(uint16_t));
|
|
||||||
a = endianLittleToHost16(a);
|
|
||||||
offset += sizeof(uint16_t);
|
|
||||||
|
|
||||||
uint8_t b = data[offset];
|
|
||||||
offset += sizeof(uint8_t);
|
|
||||||
|
|
||||||
if(spawn->kind == CHUNK_ENTITY_SPAWN_KIND_ITEM) {
|
|
||||||
spawn->globalId = 0;
|
|
||||||
spawn->itemId = a;
|
|
||||||
spawn->itemQuantity = b;
|
|
||||||
} else {
|
|
||||||
spawn->globalId = a;
|
|
||||||
spawn->itemId = 0;
|
|
||||||
spawn->itemQuantity = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
spawn->position = worldPosReadLE(data, &offset);
|
|
||||||
}
|
|
||||||
|
|
||||||
out->areaSpawnCount = data[offset];
|
|
||||||
offset += sizeof(uint8_t);
|
|
||||||
assertTrue(
|
|
||||||
out->areaSpawnCount <= CHUNK_AREA_COUNT_MAX,
|
|
||||||
"Chunk area spawn count exceeds maximum."
|
|
||||||
);
|
|
||||||
|
|
||||||
for(uint8_t s = 0; s < out->areaSpawnCount; s++) {
|
|
||||||
chunkareaspawn_t *area = &out->areaSpawns[s];
|
|
||||||
area->min = worldPosReadLE(data, &offset);
|
|
||||||
area->max = worldPosReadLE(data, &offset);
|
|
||||||
|
|
||||||
uint16_t callbackId;
|
|
||||||
memoryCopy(&callbackId, data + offset, sizeof(uint16_t));
|
|
||||||
area->callbackId = endianLittleToHost16(callbackId);
|
|
||||||
offset += sizeof(uint16_t);
|
|
||||||
|
|
||||||
area->notify = data[offset];
|
|
||||||
offset += sizeof(uint8_t);
|
|
||||||
area->trigger = data[offset];
|
|
||||||
offset += sizeof(uint8_t);
|
|
||||||
}
|
|
||||||
|
|
||||||
memoryFree(data);
|
|
||||||
loading->loading.chunk.data = NULL;
|
|
||||||
|
|
||||||
if(out->meshCount == 0) {
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_LOAD_MODELS;
|
|
||||||
loading->loading.chunk.modelIndex = 0;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetChunkDispose(assetentry_t *entry) {
|
|
||||||
assertNotNull(entry, "Entry cannot be NULL");
|
|
||||||
assertTrue(entry->type == ASSET_LOADER_TYPE_CHUNK, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
assetchunkoutput_t *out = &entry->data.chunk;
|
|
||||||
|
|
||||||
if(out->tiles != NULL) {
|
|
||||||
memoryFree(out->tiles);
|
|
||||||
out->tiles = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
for(uint8_t m = 0; m < out->meshCount; m++) {
|
|
||||||
if(out->modelEntries[m] == NULL) continue;
|
|
||||||
assetUnlockEntry(out->modelEntries[m]);
|
|
||||||
out->modelEntries[m] = NULL;
|
|
||||||
}
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "asset/assetfile.h"
|
|
||||||
#include "rpg/overworld/chunk.h"
|
|
||||||
|
|
||||||
#define ASSET_CHUNK_FILE_VERSION 5
|
|
||||||
|
|
||||||
typedef struct assetloading_s assetloading_t;
|
|
||||||
typedef struct assetentry_s assetentry_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
void *nothing;
|
|
||||||
} assetchunkloaderinput_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ASSET_CHUNK_LOADING_STATE_INITIAL,
|
|
||||||
ASSET_CHUNK_LOADING_STATE_READ_FILE,
|
|
||||||
ASSET_CHUNK_LOADING_STATE_PARSE,
|
|
||||||
ASSET_CHUNK_LOADING_STATE_LOAD_MODELS,
|
|
||||||
ASSET_CHUNK_LOADING_STATE_DONE
|
|
||||||
} assetchunkloadingstate_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
assetfile_t file;
|
|
||||||
assetchunkloadingstate_t state;
|
|
||||||
uint8_t *data;
|
|
||||||
uint8_t modelIndex;
|
|
||||||
} assetchunkloaderloading_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
CHUNK_ENTITY_SPAWN_KIND_GLOBAL,
|
|
||||||
CHUNK_ENTITY_SPAWN_KIND_ITEM
|
|
||||||
} chunkentityspawnkind_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
chunkentityspawnkind_t kind;
|
|
||||||
uint16_t globalId; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_GLOBAL.
|
|
||||||
uint16_t itemId; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_ITEM.
|
|
||||||
uint8_t itemQuantity; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_ITEM.
|
|
||||||
worldpos_t position;
|
|
||||||
} chunkentityspawn_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
worldpos_t min;
|
|
||||||
worldpos_t max;
|
|
||||||
uint16_t callbackId; // Index into MAP_AREA_CALLBACK_LIST.
|
|
||||||
uint8_t notify;
|
|
||||||
uint8_t trigger;
|
|
||||||
} chunkareaspawn_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
tile_t *tiles;
|
|
||||||
uint8_t meshCount;
|
|
||||||
char_t modelNames[CHUNK_MESH_COUNT_MAX][CHUNK_MESH_NAME_MAX];
|
|
||||||
vec3 meshOffsets[CHUNK_MESH_COUNT_MAX];
|
|
||||||
assetentry_t *modelEntries[CHUNK_MESH_COUNT_MAX];
|
|
||||||
|
|
||||||
uint8_t entitySpawnCount;
|
|
||||||
chunkentityspawn_t entitySpawns[CHUNK_ENTITY_SPAWN_COUNT_MAX];
|
|
||||||
|
|
||||||
uint8_t areaSpawnCount;
|
|
||||||
chunkareaspawn_t areaSpawns[CHUNK_AREA_COUNT_MAX];
|
|
||||||
} assetchunkoutput_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Asynchronous loader for chunk assets. Reads the raw DCF file bytes into
|
|
||||||
* the loading buffer so the sync phase can parse without blocking the
|
|
||||||
* main thread on I/O.
|
|
||||||
*
|
|
||||||
* @param loading Loading information for the asset being loaded.
|
|
||||||
* @return Error code indicating success or failure of the load operation.
|
|
||||||
*/
|
|
||||||
errorret_t assetChunkLoaderAsync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Synchronous loader for chunk assets. Validates the DCF binary previously
|
|
||||||
* read by the async phase and populates the output assetchunkoutput_t with
|
|
||||||
* tile data and model paths.
|
|
||||||
*
|
|
||||||
* @param loading Loading information for the asset being loaded.
|
|
||||||
* @return Error code indicating success or failure of the load operation.
|
|
||||||
*/
|
|
||||||
errorret_t assetChunkLoaderSync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disposer for chunk assets.
|
|
||||||
*
|
|
||||||
* @param entry Asset entry containing the chunk data to dispose.
|
|
||||||
* @return Error code indicating success or failure of the dispose operation.
|
|
||||||
*/
|
|
||||||
errorret_t assetChunkDispose(assetentry_t *entry);
|
|
||||||
@@ -1,225 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "assetcutsceneloader.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/string.h"
|
|
||||||
#include "asset/loader/assetloading.h"
|
|
||||||
#include "asset/loader/assetentry.h"
|
|
||||||
#include "asset/loader/assetloader.h"
|
|
||||||
#include "asset/asset.h"
|
|
||||||
#include "rpg/cutscene/item/json/cutscenejsonpauseflags.h"
|
|
||||||
|
|
||||||
errorret_t assetCutsceneParseItem(
|
|
||||||
assetloading_t *loading,
|
|
||||||
yyjson_val *itemObj,
|
|
||||||
cutsceneitem_t *item,
|
|
||||||
uint8_t *pool,
|
|
||||||
size_t *poolOffset,
|
|
||||||
const uint8_t index
|
|
||||||
) {
|
|
||||||
if(!yyjson_is_obj(itemObj)) {
|
|
||||||
assetLoaderErrorThrow(
|
|
||||||
loading,
|
|
||||||
"Cutscene item %u is not an object",
|
|
||||||
(uint32_t)index
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const char_t *typeName = yyjson_get_str(yyjson_obj_get(itemObj, "type"));
|
|
||||||
if(!cutsceneItemLookupType(typeName, &item->type)) {
|
|
||||||
assetLoaderErrorThrow(
|
|
||||||
loading,
|
|
||||||
"Cutscene item %u: missing/unsupported item type %s",
|
|
||||||
(uint32_t)index,
|
|
||||||
typeName
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
cutsceneitemloadcallback_t *load = CUTSCENE_ITEM_CALLBACKS[item->type].load;
|
|
||||||
if(load == NULL) {
|
|
||||||
assetLoaderErrorThrow(
|
|
||||||
loading, "Cutscene item %u: unhandled item type %u", (uint32_t)index,
|
|
||||||
(uint32_t)item->type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t result = load(itemObj, item, pool, poolOffset);
|
|
||||||
if(errorIsNotOk(result)) {
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
|
||||||
errorChain(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t assetCutsceneComputePoolSize(yyjson_val *itemsArr) {
|
|
||||||
size_t size = 0;
|
|
||||||
yyjson_arr_iter iter = yyjson_arr_iter_with(itemsArr);
|
|
||||||
yyjson_val *itemVal;
|
|
||||||
while((itemVal = yyjson_arr_iter_next(&iter)) != NULL) {
|
|
||||||
const char_t *typeName = yyjson_get_str(yyjson_obj_get(itemVal, "type"));
|
|
||||||
cutsceneitemtype_t type;
|
|
||||||
if(!cutsceneItemLookupType(typeName, &type)) continue;
|
|
||||||
|
|
||||||
cutsceneitempoolsizecallback_t *poolSize =
|
|
||||||
CUTSCENE_ITEM_CALLBACKS[type].poolSize;
|
|
||||||
if(poolSize == NULL) continue;
|
|
||||||
|
|
||||||
size = cutsceneJsonPoolAlign(size) + poolSize(itemVal);
|
|
||||||
}
|
|
||||||
return size;
|
|
||||||
}
|
|
||||||
|
|
||||||
void assetCutsceneFreeParsed(assetcutsceneoutput_t *out) {
|
|
||||||
if(out->items != NULL) {
|
|
||||||
memoryFree(out->items);
|
|
||||||
out->items = NULL;
|
|
||||||
}
|
|
||||||
if(out->pool != NULL) {
|
|
||||||
memoryFree(out->pool);
|
|
||||||
out->pool = NULL;
|
|
||||||
}
|
|
||||||
if(out->doc != NULL) {
|
|
||||||
yyjson_doc_free(out->doc);
|
|
||||||
out->doc = NULL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertNotMainThread("Should be called from an async thread.");
|
|
||||||
|
|
||||||
if(
|
|
||||||
loading->loading.cutscene.state != ASSET_CUTSCENE_LOADING_STATE_READ_FILE
|
|
||||||
) {
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
assertNull(loading->loading.cutscene.buffer, "Buffer already defined?");
|
|
||||||
|
|
||||||
assetfile_t *file = &loading->loading.cutscene.file;
|
|
||||||
assetLoaderErrorChain(loading,
|
|
||||||
assetFileInit(file, loading->entry->name, NULL, NULL)
|
|
||||||
);
|
|
||||||
|
|
||||||
if(file->size > ASSET_CUTSCENE_FILE_SIZE_MAX) {
|
|
||||||
assetLoaderErrorThrow(
|
|
||||||
loading, "Cutscene JSON exceeds maximum allowed size"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t fileSize = (size_t)file->size;
|
|
||||||
uint8_t *buffer = memoryAllocate(fileSize);
|
|
||||||
assetLoaderErrorChain(loading, assetFileOpen(file));
|
|
||||||
assetLoaderErrorChain(loading, assetFileRead(file, buffer, fileSize));
|
|
||||||
assertTrue(
|
|
||||||
file->lastRead == file->size,
|
|
||||||
"Failed to read entire cutscene file."
|
|
||||||
);
|
|
||||||
assetLoaderErrorChain(loading, assetFileClose(file));
|
|
||||||
assetLoaderErrorChain(loading, assetFileDispose(file));
|
|
||||||
|
|
||||||
loading->loading.cutscene.buffer = buffer;
|
|
||||||
loading->loading.cutscene.size = fileSize;
|
|
||||||
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetCutsceneLoaderSync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertTrue(loading->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
if(loading->loading.cutscene.state == ASSET_CUTSCENE_LOADING_STATE_INITIAL) {
|
|
||||||
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_READ_FILE;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
assetcutsceneoutput_t *out = &loading->entry->data.cutscene;
|
|
||||||
uint8_t *buffer = loading->loading.cutscene.buffer;
|
|
||||||
assertNotNull(buffer, "Cutscene data should have been loaded by now.");
|
|
||||||
size_t bufferSize = loading->loading.cutscene.size;
|
|
||||||
|
|
||||||
yyjson_doc *doc = yyjson_read(
|
|
||||||
(char *)buffer, bufferSize,
|
|
||||||
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
|
|
||||||
);
|
|
||||||
memoryFree(buffer);
|
|
||||||
loading->loading.cutscene.buffer = NULL;
|
|
||||||
|
|
||||||
if(doc == NULL) {
|
|
||||||
assetLoaderErrorThrow(loading, "Failed to parse cutscene JSON");
|
|
||||||
}
|
|
||||||
out->doc = doc;
|
|
||||||
|
|
||||||
yyjson_val *root = yyjson_doc_get_root(doc);
|
|
||||||
yyjson_val *itemsArr = yyjson_obj_get(root, "items");
|
|
||||||
if(!yyjson_is_arr(itemsArr)) {
|
|
||||||
assetCutsceneFreeParsed(out);
|
|
||||||
assetLoaderErrorThrow(loading, "Cutscene JSON is missing an 'items' array");
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t itemCount = yyjson_arr_size(itemsArr);
|
|
||||||
if(itemCount > UINT8_MAX) {
|
|
||||||
assetCutsceneFreeParsed(out);
|
|
||||||
assetLoaderErrorThrow(loading, "Cutscene has more than 255 items");
|
|
||||||
}
|
|
||||||
|
|
||||||
cutscenepause_t pause = CUTSCENE_PAUSE_DEFAULT;
|
|
||||||
yyjson_val *pauseArr = yyjson_obj_get(root, "pause");
|
|
||||||
if(yyjson_is_arr(pauseArr)) {
|
|
||||||
if(!cutsceneJsonParsePauseFlags(pauseArr, &pause)) {
|
|
||||||
assetCutsceneFreeParsed(out);
|
|
||||||
assetLoaderErrorThrow(
|
|
||||||
loading, "Cutscene JSON has an invalid 'pause' flag"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
out->items = memoryAllocate(itemCount * sizeof(cutsceneitem_t));
|
|
||||||
memoryZero(out->items, itemCount * sizeof(cutsceneitem_t));
|
|
||||||
|
|
||||||
size_t poolSize = assetCutsceneComputePoolSize(itemsArr);
|
|
||||||
out->pool = poolSize > 0 ? memoryAllocate(poolSize) : NULL;
|
|
||||||
|
|
||||||
size_t poolOffset = 0;
|
|
||||||
yyjson_arr_iter itemIter = yyjson_arr_iter_with(itemsArr);
|
|
||||||
yyjson_val *itemVal;
|
|
||||||
uint8_t index = 0;
|
|
||||||
while((itemVal = yyjson_arr_iter_next(&itemIter)) != NULL) {
|
|
||||||
errorret_t itemResult = assetCutsceneParseItem(
|
|
||||||
loading, itemVal, &out->items[index], out->pool, &poolOffset, index
|
|
||||||
);
|
|
||||||
if(errorIsNotOk(itemResult)) {
|
|
||||||
assetCutsceneFreeParsed(out);
|
|
||||||
errorChain(itemResult);
|
|
||||||
}
|
|
||||||
index++;
|
|
||||||
}
|
|
||||||
|
|
||||||
out->cutscene.items = out->items;
|
|
||||||
out->cutscene.itemCount = (uint8_t)itemCount;
|
|
||||||
out->cutscene.pause = pause;
|
|
||||||
out->cutscene.dataSize = 0;
|
|
||||||
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetCutsceneDispose(assetentry_t *entry) {
|
|
||||||
assertNotNull(entry, "Entry cannot be NULL");
|
|
||||||
assertTrue(entry->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
assetCutsceneFreeParsed(&entry->data.cutscene);
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "asset/assetfile.h"
|
|
||||||
#include "rpg/cutscene/cutscene.h"
|
|
||||||
#include "rpg/cutscene/item/cutsceneitem.h"
|
|
||||||
#include "rpg/cutscene/item/json/cutscenejsonpool.h"
|
|
||||||
#include "yyjson.h"
|
|
||||||
|
|
||||||
#define ASSET_CUTSCENE_FILE_SIZE_MAX (1024 * 64)
|
|
||||||
|
|
||||||
typedef struct assetloading_s assetloading_t;
|
|
||||||
typedef struct assetentry_s assetentry_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
void *nothing;
|
|
||||||
} assetcutsceneloaderinput_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ASSET_CUTSCENE_LOADING_STATE_INITIAL,
|
|
||||||
ASSET_CUTSCENE_LOADING_STATE_READ_FILE,
|
|
||||||
ASSET_CUTSCENE_LOADING_STATE_PARSE
|
|
||||||
} assetcutsceneloadingstate_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
assetfile_t file;
|
|
||||||
assetcutsceneloadingstate_t state;
|
|
||||||
uint8_t *buffer;
|
|
||||||
size_t size;
|
|
||||||
} assetcutsceneloaderloading_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
cutscene_t cutscene;
|
|
||||||
cutsceneitem_t *items;
|
|
||||||
uint8_t *pool;
|
|
||||||
yyjson_doc *doc;
|
|
||||||
} assetcutsceneoutput_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses one cutscene item object into item, writing any pool-backed
|
|
||||||
* array data (entityWalkTo positions, mapAreaWait areaIds) into pool at
|
|
||||||
* *poolOffset and advancing it. Every field/enum name is validated as
|
|
||||||
* real (untrusted, authored) file content - failures are real errors, not
|
|
||||||
* asserts. Dispatches to the matching type's Load callback (see
|
|
||||||
* CUTSCENE_ITEM_CALLBACKS in rpg/cutscene/item/cutsceneitem.h) - the
|
|
||||||
* per-type parsing logic itself lives there now, colocated with that
|
|
||||||
* type's runtime behavior.
|
|
||||||
*
|
|
||||||
* @param loading Loading information for the asset being loaded.
|
|
||||||
* @param itemObj The item's JSON object.
|
|
||||||
* @param item Destination item, already zeroed by the caller.
|
|
||||||
* @param pool Base pointer of the entry's pool allocation (may be NULL if
|
|
||||||
* assetCutsceneComputePoolSize returned 0).
|
|
||||||
* @param poolOffset In/out cursor into pool.
|
|
||||||
* @param index Index of this item within the cutscene, for error messages.
|
|
||||||
* @return Error code indicating success or failure of the parse.
|
|
||||||
*/
|
|
||||||
errorret_t assetCutsceneParseItem(
|
|
||||||
assetloading_t *loading,
|
|
||||||
yyjson_val *itemObj,
|
|
||||||
cutsceneitem_t *item,
|
|
||||||
uint8_t *pool,
|
|
||||||
size_t *poolOffset,
|
|
||||||
const uint8_t index
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Frees whatever of out->items/out->pool/out->doc is currently non-NULL
|
|
||||||
* and clears them - shared by both the normal disposer and every parse
|
|
||||||
* failure path's cleanup.
|
|
||||||
*
|
|
||||||
* @param out The output to free.
|
|
||||||
*/
|
|
||||||
void assetCutsceneFreeParsed(assetcutsceneoutput_t *out);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Asynchronous loader for cutscene assets. Reads the raw JSONC file bytes
|
|
||||||
* into the loading buffer so the sync phase can parse without blocking the
|
|
||||||
* main thread on I/O.
|
|
||||||
*
|
|
||||||
* @param loading Loading information for the asset being loaded.
|
|
||||||
* @return Error code indicating success or failure of the load operation.
|
|
||||||
*/
|
|
||||||
errorret_t assetCutsceneLoaderAsync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Synchronous loader for cutscene assets. Parses the JSONC previously read
|
|
||||||
* by the async phase into a heap-allocated cutsceneitem_t array + pool.
|
|
||||||
*
|
|
||||||
* @param loading Loading information for the asset being loaded.
|
|
||||||
* @return Error code indicating success or failure of the load operation.
|
|
||||||
*/
|
|
||||||
errorret_t assetCutsceneLoaderSync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disposer for cutscene assets.
|
|
||||||
*
|
|
||||||
* @param entry Asset entry containing the cutscene data to dispose.
|
|
||||||
* @return Error code indicating success or failure of the dispose operation.
|
|
||||||
*/
|
|
||||||
errorret_t assetCutsceneDispose(assetentry_t *entry);
|
|
||||||
@@ -127,14 +127,6 @@ errorret_t assetMeshLoaderSync(assetloading_t *loading) {
|
|||||||
errorChain(ret);
|
errorChain(ret);
|
||||||
}
|
}
|
||||||
|
|
||||||
#if defined(DUSK_OPENGL) && !defined(DUSK_OPENGL_LEGACY)
|
|
||||||
// VBO owns the data now; CPU copy is no longer needed. The platform
|
|
||||||
// mesh object itself still needs meshDispose later - tracked via
|
|
||||||
// out->meshInitialized, independent of the CPU buffer's lifetime.
|
|
||||||
memoryFree(out->vertices);
|
|
||||||
out->vertices = NULL;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ errorret_t assetModelLoaderSync(assetloading_t *loading) {
|
|||||||
|
|
||||||
// Parse required mesh path.
|
// Parse required mesh path.
|
||||||
yyjson_val *meshVal = yyjson_obj_get(root, "mesh");
|
yyjson_val *meshVal = yyjson_obj_get(root, "mesh");
|
||||||
if(meshVal == NULL || !yyjson_is_str(meshVal)) {
|
if(!meshVal || !yyjson_is_str(meshVal)) {
|
||||||
assetUnlockEntry(jsonEntry);
|
assetUnlockEntry(jsonEntry);
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||||
errorThrow("Model JSON missing 'mesh' string");
|
errorThrow("Model JSON missing 'mesh' string");
|
||||||
@@ -115,8 +115,7 @@ errorret_t assetModelLoaderSync(assetloading_t *loading) {
|
|||||||
assetUnlockEntry(jsonEntry);
|
assetUnlockEntry(jsonEntry);
|
||||||
|
|
||||||
// Lock and load the mesh sub-asset.
|
// Lock and load the mesh sub-asset.
|
||||||
assetentry_t *meshEntry =
|
assetentry_t *meshEntry = assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
|
||||||
assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
|
|
||||||
ret = assetRequireLoaded(meshEntry);
|
ret = assetRequireLoaded(meshEntry);
|
||||||
if(errorIsNotOk(ret)) {
|
if(errorIsNotOk(ret)) {
|
||||||
assetUnlockEntry(meshEntry);
|
assetUnlockEntry(meshEntry);
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ typedef struct {
|
|||||||
* on the main thread; this callback is never reached.
|
* on the main thread; this callback is never reached.
|
||||||
*
|
*
|
||||||
* @param loading Loading information for the asset being loaded.
|
* @param loading Loading information for the asset being loaded.
|
||||||
* @return Always success.
|
* @returns Always success.
|
||||||
*/
|
*/
|
||||||
errorret_t assetModelLoaderAsync(assetloading_t *loading);
|
errorret_t assetModelLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ errorret_t assetModelLoaderAsync(assetloading_t *loading);
|
|||||||
* within ASSET_LOADING_COUNT_MAX slot limits.
|
* within ASSET_LOADING_COUNT_MAX slot limits.
|
||||||
*
|
*
|
||||||
* @param loading Loading information for the asset being loaded.
|
* @param loading Loading information for the asset being loaded.
|
||||||
* @return Error code indicating success or failure.
|
* @returns Error code indicating success or failure.
|
||||||
*/
|
*/
|
||||||
errorret_t assetModelLoaderSync(assetloading_t *loading);
|
errorret_t assetModelLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
@@ -53,6 +53,6 @@ errorret_t assetModelLoaderSync(assetloading_t *loading);
|
|||||||
* sub-asset entries.
|
* sub-asset entries.
|
||||||
*
|
*
|
||||||
* @param entry Asset entry containing the model to dispose.
|
* @param entry Asset entry containing the model to dispose.
|
||||||
* @return Error code indicating success or failure.
|
* @returns Error code indicating success or failure.
|
||||||
*/
|
*/
|
||||||
errorret_t assetModelDispose(assetentry_t *entry);
|
errorret_t assetModelDispose(assetentry_t *entry);
|
||||||
@@ -77,7 +77,7 @@ errorret_t assetJsonLoaderSync(assetloading_t *loading) {
|
|||||||
memoryFree(buffer);
|
memoryFree(buffer);
|
||||||
loading->loading.json.buffer = NULL;
|
loading->loading.json.buffer = NULL;
|
||||||
|
|
||||||
if(loading->entry->data.json == NULL) {
|
if(!loading->entry->data.json) {
|
||||||
assetLoaderErrorThrow(loading, "Failed to parse JSON");
|
assetLoaderErrorThrow(loading, "Failed to parse JSON");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,32 +41,6 @@ typedef struct {
|
|||||||
|
|
||||||
typedef yyjson_doc * assetjsonoutput_t;
|
typedef yyjson_doc * assetjsonoutput_t;
|
||||||
|
|
||||||
/**
|
|
||||||
* Asynchronous loader callback. Opens the JSON file and reads the whole of
|
|
||||||
* it into a heap buffer, so the main thread is not blocked on I/O. The
|
|
||||||
* buffer is parsed later, on the main thread, by assetJsonLoaderSync. Sets
|
|
||||||
* the entry state to `ASSET_ENTRY_STATE_PENDING_SYNC` on success.
|
|
||||||
*
|
|
||||||
* @param loading The loading slot for this asset entry.
|
|
||||||
* @return OK on success, error otherwise.
|
|
||||||
*/
|
|
||||||
errorret_t assetJsonLoaderAsync(assetloading_t *loading);
|
errorret_t assetJsonLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
/**
|
|
||||||
* Synchronous loader callback. Drives the load state machine: on the first
|
|
||||||
* call it queues the async read, and once that has completed it parses the
|
|
||||||
* buffer into a `yyjson_doc` (comments and trailing commas allowed), frees
|
|
||||||
* the buffer and marks the entry `ASSET_ENTRY_STATE_LOADED`.
|
|
||||||
*
|
|
||||||
* @param loading The loading slot for this asset entry.
|
|
||||||
* @return OK on success, error otherwise.
|
|
||||||
*/
|
|
||||||
errorret_t assetJsonLoaderSync(assetloading_t *loading);
|
errorret_t assetJsonLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
/**
|
|
||||||
* Dispose callback. Frees the parsed `yyjson_doc` held by the entry.
|
|
||||||
*
|
|
||||||
* @param entry The asset entry to dispose.
|
|
||||||
* @return OK on success, error otherwise.
|
|
||||||
*/
|
|
||||||
errorret_t assetJsonDispose(assetentry_t *entry);
|
errorret_t assetJsonDispose(assetentry_t *entry);
|
||||||
@@ -30,8 +30,8 @@ errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
|
|||||||
assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file));
|
assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file));
|
||||||
|
|
||||||
char_t buffer[1024];
|
char_t buffer[1024];
|
||||||
assetLoaderErrorChain(loading, assetLocaleGetHeader(
|
assetLoaderErrorChain(loading, assetLocaleGetString(
|
||||||
localeFile, buffer, sizeof(buffer)
|
localeFile, "", 0, buffer, sizeof(buffer)
|
||||||
));
|
));
|
||||||
assetLoaderErrorChain(loading, assetLocaleParseHeader(
|
assetLoaderErrorChain(loading, assetLocaleParseHeader(
|
||||||
localeFile, buffer, sizeof(buffer)
|
localeFile, buffer, sizeof(buffer)
|
||||||
@@ -71,12 +71,6 @@ errorret_t assetLocaleDispose(assetentry_t *entry) {
|
|||||||
assertIsMainThread("Must be called from the main thread.");
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
assetlocalefile_t *localeFile = &entry->data.locale;
|
assetlocalefile_t *localeFile = &entry->data.locale;
|
||||||
|
|
||||||
if(localeFile->cache != NULL) {
|
|
||||||
memoryFree(localeFile->cache);
|
|
||||||
localeFile->cache = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorChain(assetFileClose(&localeFile->file));
|
errorChain(assetFileClose(&localeFile->file));
|
||||||
return assetFileDispose(&localeFile->file);
|
return assetFileDispose(&localeFile->file);
|
||||||
}
|
}
|
||||||
@@ -93,7 +87,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
|
|
||||||
// Find "Plural-Forms: " line and parse out plural form info
|
// Find "Plural-Forms: " line and parse out plural form info
|
||||||
char_t *pluralFormsLine = strstr(headerBuffer, "Plural-Forms:");
|
char_t *pluralFormsLine = strstr(headerBuffer, "Plural-Forms:");
|
||||||
if(pluralFormsLine == NULL) {
|
if(!pluralFormsLine) {
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +95,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
|
|
||||||
// Expect nplurals
|
// Expect nplurals
|
||||||
char_t *npluralsStr = strstr(pluralFormsLine, "nplurals=");
|
char_t *npluralsStr = strstr(pluralFormsLine, "nplurals=");
|
||||||
if(npluralsStr == NULL) {
|
if(!npluralsStr) {
|
||||||
errorThrow("Failed to find nplurals in Plural-Forms header.");
|
errorThrow("Failed to find nplurals in Plural-Forms header.");
|
||||||
}
|
}
|
||||||
npluralsStr += strlen("nplurals=");
|
npluralsStr += strlen("nplurals=");
|
||||||
@@ -120,7 +114,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
|
|
||||||
// Expect plural=
|
// Expect plural=
|
||||||
char_t *pluralStr = strstr(pluralFormsLine, "plural=");
|
char_t *pluralStr = strstr(pluralFormsLine, "plural=");
|
||||||
if(pluralStr == NULL) {
|
if(!pluralStr) {
|
||||||
errorThrow("Failed to find plural in Plural-Forms header.");
|
errorThrow("Failed to find plural in Plural-Forms header.");
|
||||||
}
|
}
|
||||||
pluralStr += strlen("plural=");
|
pluralStr += strlen("plural=");
|
||||||
@@ -128,7 +122,7 @@ errorret_t assetLocaleParseHeader(
|
|||||||
// Expect ( [expressions] )
|
// Expect ( [expressions] )
|
||||||
char_t *openParen = strchr(pluralStr, '(');
|
char_t *openParen = strchr(pluralStr, '(');
|
||||||
char_t *closeParen = strrchr(pluralStr, ')');
|
char_t *closeParen = strrchr(pluralStr, ')');
|
||||||
if(openParen == NULL || closeParen == NULL || closeParen < openParen) {
|
if(!openParen || !closeParen || closeParen < openParen) {
|
||||||
errorThrow("Failed to find plural expression in Plural-Forms header.");
|
errorThrow("Failed to find plural expression in Plural-Forms header.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -399,12 +393,12 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
|
|
||||||
// At the point this funciton is called, we are looking for an opening quote.
|
// At the point this funciton is called, we are looking for an opening quote.
|
||||||
char_t *start = strchr((char_t *)lineBuffer, '"');
|
char_t *start = strchr((char_t *)lineBuffer, '"');
|
||||||
if(start == NULL) {
|
if(!start) {
|
||||||
errorThrow("Expected open (0) \"");
|
errorThrow("Expected open (0) \"");
|
||||||
}
|
}
|
||||||
|
|
||||||
char *end = strchr(start + 1, '"');
|
char *end = strchr(start + 1, '"');
|
||||||
if(end == NULL) {
|
if(!end) {
|
||||||
errorThrow("Expected close (0) \"");
|
errorThrow("Expected close (0) \"");
|
||||||
}
|
}
|
||||||
*end = '\0';
|
*end = '\0';
|
||||||
@@ -476,94 +470,7 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetLocaleCacheFind(
|
errorret_t assetLocaleGetString(
|
||||||
assetlocalefile_t *file,
|
|
||||||
const char_t *messageId,
|
|
||||||
const int32_t pluralCount,
|
|
||||||
char_t *stringBuffer,
|
|
||||||
const size_t stringBufferSize,
|
|
||||||
bool_t *outHit
|
|
||||||
) {
|
|
||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
|
||||||
assertNotNull(messageId, "Message ID cannot be NULL.");
|
|
||||||
assertNotNull(outHit, "outHit cannot be NULL.");
|
|
||||||
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
|
|
||||||
|
|
||||||
*outHit = false;
|
|
||||||
if(file->cache == NULL) errorOk();
|
|
||||||
|
|
||||||
assetlocalecache_t *cache = file->cache;
|
|
||||||
for(uint8_t i = 0; i < ASSET_LOCALE_CACHE_COUNT; i++) {
|
|
||||||
assetlocalecacheentry_t *entry = &cache->entries[i];
|
|
||||||
if(entry->messageId[0] == '\0') break;// unused tail - nothing further
|
|
||||||
if(entry->pluralCount != pluralCount) continue;
|
|
||||||
if(!stringEquals(entry->messageId, messageId)) continue;
|
|
||||||
|
|
||||||
// Move to the front of the LRU order (a no-op when already there).
|
|
||||||
if(i > 0) {
|
|
||||||
assetlocalecacheentry_t hit = *entry;
|
|
||||||
memoryMove(
|
|
||||||
&cache->entries[1], &cache->entries[0],
|
|
||||||
i * sizeof(assetlocalecacheentry_t)
|
|
||||||
);
|
|
||||||
cache->entries[0] = hit;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t len = strlen(cache->entries[0].value);
|
|
||||||
if(len >= stringBufferSize) errorThrow("String buffer overflow");
|
|
||||||
memoryCopy(stringBuffer, cache->entries[0].value, len + 1);
|
|
||||||
*outHit = true;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
void assetLocaleCacheInsert(
|
|
||||||
assetlocalefile_t *file,
|
|
||||||
const char_t *messageId,
|
|
||||||
const int32_t pluralCount,
|
|
||||||
const char_t *value
|
|
||||||
) {
|
|
||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
|
||||||
assertNotNull(messageId, "Message ID cannot be NULL.");
|
|
||||||
assertNotNull(value, "Value cannot be NULL.");
|
|
||||||
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
|
|
||||||
|
|
||||||
// Caching is a pure optimization - a message ID or value too long for a
|
|
||||||
// fixed cache slot is just never cached, not an error.
|
|
||||||
if(strlen(messageId) >= ASSET_LOCALE_CACHE_KEY_MAX) return;
|
|
||||||
if(strlen(value) >= ASSET_LOCALE_CACHE_VALUE_MAX) return;
|
|
||||||
|
|
||||||
if(file->cache == NULL) {
|
|
||||||
file->cache =
|
|
||||||
(assetlocalecache_t *)memoryAllocate(sizeof(assetlocalecache_t));
|
|
||||||
memoryZero(file->cache, sizeof(assetlocalecache_t));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Shift every entry down one slot, dropping the least-recently-used one
|
|
||||||
// off the end, to make room for the new entry at the front. This assumes
|
|
||||||
// messageId is never already present elsewhere in the cache, which holds
|
|
||||||
// as long as callers only insert after a confirmed assetLocaleCacheFind
|
|
||||||
// miss (a hit would have returned before reaching this point).
|
|
||||||
memoryMove(
|
|
||||||
&file->cache->entries[1], &file->cache->entries[0],
|
|
||||||
(ASSET_LOCALE_CACHE_COUNT - 1) * sizeof(assetlocalecacheentry_t)
|
|
||||||
);
|
|
||||||
|
|
||||||
assetlocalecacheentry_t *entry = &file->cache->entries[0];
|
|
||||||
stringCopy(entry->messageId, messageId, ASSET_LOCALE_CACHE_KEY_MAX);
|
|
||||||
entry->pluralCount = pluralCount;
|
|
||||||
stringCopy(entry->value, value, ASSET_LOCALE_CACHE_VALUE_MAX);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Shared by assetLocaleGetString (external callers, messageId required
|
|
||||||
// non-empty) and assetLocaleGetHeader (messageId "", the PO format's own
|
|
||||||
// sentinel for its header entry - see assetLocaleGetHeader). Caching is
|
|
||||||
// skipped entirely for an empty messageId: assetLocaleCacheFind/Insert
|
|
||||||
// both reject one outright (same guard as assetLocaleGetString's own),
|
|
||||||
// and it's a one-shot boot-time read anyway, not worth caching.
|
|
||||||
errorret_t assetLocaleGetStringLookup(
|
|
||||||
assetlocalefile_t *file,
|
assetlocalefile_t *file,
|
||||||
const char_t *messageId,
|
const char_t *messageId,
|
||||||
const int32_t pluralCount,
|
const int32_t pluralCount,
|
||||||
@@ -575,15 +482,6 @@ errorret_t assetLocaleGetStringLookup(
|
|||||||
assertTrue(pluralCount >= 0, "Plural index cannot be negative.");
|
assertTrue(pluralCount >= 0, "Plural index cannot be negative.");
|
||||||
assertNotNull(stringBuffer, "String buffer cannot be NULL.");
|
assertNotNull(stringBuffer, "String buffer cannot be NULL.");
|
||||||
assertTrue(stringBufferSize > 0, "String buffer size must be > 0");
|
assertTrue(stringBufferSize > 0, "String buffer size must be > 0");
|
||||||
|
|
||||||
bool_t cacheHit = false;
|
|
||||||
if(messageId[0] != '\0') {
|
|
||||||
errorChain(assetLocaleCacheFind(
|
|
||||||
file, messageId, pluralCount, stringBuffer, stringBufferSize, &cacheHit
|
|
||||||
));
|
|
||||||
if(cacheHit) errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
assetfilelinereader_t reader;
|
assetfilelinereader_t reader;
|
||||||
|
|
||||||
bool_t msgidFound = false, msgidPluralFound = false, msgstrFound = false;
|
bool_t msgidFound = false, msgidPluralFound = false, msgstrFound = false;
|
||||||
@@ -690,7 +588,7 @@ errorret_t assetLocaleGetStringLookup(
|
|||||||
|
|
||||||
// Parse until ]
|
// Parse until ]
|
||||||
char *end = strchr(ptr, ']');
|
char *end = strchr(ptr, ']');
|
||||||
if(end == NULL) {
|
if(!end) {
|
||||||
errorThrow("Expected ] for plural form, found: %s", lineBuffer);
|
errorThrow("Expected ] for plural form, found: %s", lineBuffer);
|
||||||
}
|
}
|
||||||
*end = '\0';
|
*end = '\0';
|
||||||
@@ -727,38 +625,9 @@ errorret_t assetLocaleGetStringLookup(
|
|||||||
errorThrow("Failed to find msgstr for message ID: %s", messageId);
|
errorThrow("Failed to find msgstr for message ID: %s", messageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(messageId[0] != '\0') {
|
|
||||||
assetLocaleCacheInsert(file, messageId, pluralCount, stringBuffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetLocaleGetString(
|
|
||||||
assetlocalefile_t *file,
|
|
||||||
const char_t *messageId,
|
|
||||||
const int32_t pluralCount,
|
|
||||||
char_t *stringBuffer,
|
|
||||||
const size_t stringBufferSize
|
|
||||||
) {
|
|
||||||
assertNotNull(messageId, "Message ID cannot be NULL.");
|
|
||||||
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
|
|
||||||
|
|
||||||
return assetLocaleGetStringLookup(
|
|
||||||
file, messageId, pluralCount, stringBuffer, stringBufferSize
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetLocaleGetHeader(
|
|
||||||
assetlocalefile_t *file,
|
|
||||||
char_t *stringBuffer,
|
|
||||||
const size_t stringBufferSize
|
|
||||||
) {
|
|
||||||
return assetLocaleGetStringLookup(
|
|
||||||
file, "", 0, stringBuffer, stringBufferSize
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetLocaleGetStringWithVA(
|
errorret_t assetLocaleGetStringWithVA(
|
||||||
assetlocalefile_t *file,
|
assetlocalefile_t *file,
|
||||||
const char_t *messageId,
|
const char_t *messageId,
|
||||||
@@ -854,7 +723,7 @@ errorret_t assetLocaleGetStringWithArgs(
|
|||||||
|
|
||||||
inIndex++;
|
inIndex++;
|
||||||
|
|
||||||
// Escaped percent
|
/* Escaped percent */
|
||||||
if(format[inIndex] == '%') {
|
if(format[inIndex] == '%') {
|
||||||
if(outIndex + 1 >= bufferSize) {
|
if(outIndex + 1 >= bufferSize) {
|
||||||
memoryFree(format);
|
memoryFree(format);
|
||||||
@@ -880,7 +749,7 @@ errorret_t assetLocaleGetStringWithArgs(
|
|||||||
|
|
||||||
specBuffer[specLength++] = '%';
|
specBuffer[specLength++] = '%';
|
||||||
|
|
||||||
// Allow flags / width / precision
|
/* Allow flags / width / precision */
|
||||||
while(format[inIndex] != '\0') {
|
while(format[inIndex] != '\0') {
|
||||||
char_t ch = format[inIndex];
|
char_t ch = format[inIndex];
|
||||||
|
|
||||||
|
|||||||
@@ -70,41 +70,6 @@ typedef struct {
|
|||||||
};
|
};
|
||||||
} assetlocalearg_t;
|
} assetlocalearg_t;
|
||||||
|
|
||||||
/** Number of recently resolved strings @ref assetlocalecache_t remembers. */
|
|
||||||
#define ASSET_LOCALE_CACHE_COUNT 128
|
|
||||||
|
|
||||||
/** Max length (excluding null terminator) of a cacheable message ID. */
|
|
||||||
#define ASSET_LOCALE_CACHE_KEY_MAX 64
|
|
||||||
|
|
||||||
/** Max length (excluding null terminator) of a cacheable resolved string. */
|
|
||||||
#define ASSET_LOCALE_CACHE_VALUE_MAX 256
|
|
||||||
|
|
||||||
/** One (messageId, pluralCount) -> resolved string cache slot. */
|
|
||||||
typedef struct {
|
|
||||||
char_t messageId[ASSET_LOCALE_CACHE_KEY_MAX];
|
|
||||||
int32_t pluralCount;
|
|
||||||
char_t value[ASSET_LOCALE_CACHE_VALUE_MAX];
|
|
||||||
} assetlocalecacheentry_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fixed-size move-to-front LRU cache of recently resolved locale strings.
|
|
||||||
* assetLocaleGetString() re-scans and re-decompresses the whole PO file on
|
|
||||||
* every miss, which is expensive to repeat for strings a screen fetches
|
|
||||||
* every time it opens (menu labels, etc) - this cache lets identical
|
|
||||||
* (messageId, pluralCount) lookups skip that entirely.
|
|
||||||
*
|
|
||||||
* Lazily allocated on the first cache insert (see assetlocalefile_t.cache)
|
|
||||||
* so locale entries that are never queried, or a file that's disposed
|
|
||||||
* before anything is cached, never pay for it.
|
|
||||||
*/
|
|
||||||
typedef struct {
|
|
||||||
/**
|
|
||||||
* Entries ordered most-recently-used first. An entry with
|
|
||||||
* messageId[0] == '\0' (and every entry after it) is unused.
|
|
||||||
*/
|
|
||||||
assetlocalecacheentry_t entries[ASSET_LOCALE_CACHE_COUNT];
|
|
||||||
} assetlocalecache_t;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runtime state for an open locale file.
|
* Runtime state for an open locale file.
|
||||||
*
|
*
|
||||||
@@ -133,16 +98,6 @@ typedef struct {
|
|||||||
|
|
||||||
/** Form index used when no conditional clause matches. */
|
/** Form index used when no conditional clause matches. */
|
||||||
uint8_t pluralDefaultIndex;
|
uint8_t pluralDefaultIndex;
|
||||||
|
|
||||||
/**
|
|
||||||
* Recently resolved string cache, or NULL if nothing has been cached yet.
|
|
||||||
* Heap-allocated rather than embedded because assetlocalefile_t lives
|
|
||||||
* inside the shared assetloaderoutput_t union alongside every other
|
|
||||||
* asset type - embedding a 128-entry cache there would size that union
|
|
||||||
* (and therefore every one of the ASSET_ENTRY_COUNT_MAX asset slots,
|
|
||||||
* regardless of what type of asset occupies it) up by the same amount.
|
|
||||||
*/
|
|
||||||
assetlocalecache_t *cache;
|
|
||||||
} assetlocalefile_t;
|
} assetlocalefile_t;
|
||||||
|
|
||||||
/** Convenience alias - the loaded output type of a locale asset entry. */
|
/** Convenience alias - the loaded output type of a locale asset entry. */
|
||||||
@@ -248,93 +203,15 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
const size_t stringBufferSize
|
const size_t stringBufferSize
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
|
||||||
* Searches a locale file's cache for a previously resolved
|
|
||||||
* (messageId, pluralCount) pair.
|
|
||||||
*
|
|
||||||
* On a hit, copies the cached value into `stringBuffer` (erroring if it
|
|
||||||
* doesn't fit, same contract as @ref assetLocaleGetString) and moves the
|
|
||||||
* entry to the front of the cache's move-to-front LRU order. On a miss,
|
|
||||||
* `stringBuffer` is left untouched.
|
|
||||||
*
|
|
||||||
* @param file Locale file whose cache to search. Its cache may be NULL
|
|
||||||
* (nothing cached yet), which is treated as a miss.
|
|
||||||
* @param messageId Message ID to look up.
|
|
||||||
* @param pluralCount Plural count the original lookup used.
|
|
||||||
* @param stringBuffer Destination buffer, filled only on a hit.
|
|
||||||
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
|
||||||
* @param outHit Set to true on a cache hit, false on a miss.
|
|
||||||
* @return OK on success (hit or miss), error if a hit's cached value does
|
|
||||||
* not fit `stringBuffer`.
|
|
||||||
*/
|
|
||||||
errorret_t assetLocaleCacheFind(
|
|
||||||
assetlocalefile_t *file,
|
|
||||||
const char_t *messageId,
|
|
||||||
const int32_t pluralCount,
|
|
||||||
char_t *stringBuffer,
|
|
||||||
const size_t stringBufferSize,
|
|
||||||
bool_t *outHit
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records a resolved (messageId, pluralCount) -> value string at the front
|
|
||||||
* of the cache's move-to-front LRU order, evicting the least-recently-used
|
|
||||||
* entry if the cache is already full. Lazily allocates the cache (see
|
|
||||||
* assetlocalefile_t.cache) on the first call.
|
|
||||||
*
|
|
||||||
* Caching is a pure optimization: if `messageId` or `value` is too long to
|
|
||||||
* fit the cache's fixed-size slots, this silently does nothing rather than
|
|
||||||
* erroring or growing the cache.
|
|
||||||
*
|
|
||||||
* @param file Locale file whose cache to insert into.
|
|
||||||
* @param messageId Message ID that was looked up.
|
|
||||||
* @param pluralCount Plural count the lookup was made with.
|
|
||||||
* @param value Resolved string to cache.
|
|
||||||
*/
|
|
||||||
void assetLocaleCacheInsert(
|
|
||||||
assetlocalefile_t *file,
|
|
||||||
const char_t *messageId,
|
|
||||||
const int32_t pluralCount,
|
|
||||||
const char_t *value
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shared lookup core behind assetLocaleGetString and assetLocaleGetHeader:
|
|
||||||
* checks the file's cache first (see @ref assetLocaleCacheFind; skipped
|
|
||||||
* entirely for an empty messageId, since the cache rejects one), on a
|
|
||||||
* miss rewinds the file and scans from the beginning, then caches the
|
|
||||||
* result (see @ref assetLocaleCacheInsert, same empty-messageId skip)
|
|
||||||
* before returning. For plural entries (`msgid_plural`) the
|
|
||||||
* `pluralCount` is evaluated against the loaded plural rules to select
|
|
||||||
* the correct `msgstr[N]` form.
|
|
||||||
*
|
|
||||||
* Unlike assetLocaleGetString, messageId may be `""` here (see
|
|
||||||
* assetLocaleGetHeader) - this is the shared implementation both of
|
|
||||||
* them delegate to, not a public entry point of its own in practice.
|
|
||||||
*
|
|
||||||
* @param file Locale file to search. Must be open.
|
|
||||||
* @param messageId PO message ID to find, or `""` for the header entry.
|
|
||||||
* @param pluralCount Count used to select the plural form (ignored for
|
|
||||||
* singular entries).
|
|
||||||
* @param stringBuffer Buffer to receive the translated string.
|
|
||||||
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
|
||||||
* @return OK on success, error if the message ID is not found or I/O fails.
|
|
||||||
*/
|
|
||||||
errorret_t assetLocaleGetStringLookup(
|
|
||||||
assetlocalefile_t *file,
|
|
||||||
const char_t *messageId,
|
|
||||||
const int32_t pluralCount,
|
|
||||||
char_t *stringBuffer,
|
|
||||||
const size_t stringBufferSize
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Looks up a translated string by message ID from the open locale file.
|
* Looks up a translated string by message ID from the open locale file.
|
||||||
* See @ref assetLocaleGetStringLookup for the lookup/caching mechanics.
|
*
|
||||||
|
* Rewinds the file and scans from the beginning on every call. For plural
|
||||||
|
* entries (`msgid_plural`) the `pluralCount` is evaluated against the loaded
|
||||||
|
* plural rules to select the correct `msgstr[N]` form.
|
||||||
*
|
*
|
||||||
* @param file Locale file to search. Must be open.
|
* @param file Locale file to search. Must be open.
|
||||||
* @param messageId PO message ID to find. Must be non-empty - use
|
* @param messageId PO message ID to find (`""` retrieves the header entry).
|
||||||
* @ref assetLocaleGetHeader to read the header entry.
|
|
||||||
* @param pluralCount Count used to select the plural form (ignored for
|
* @param pluralCount Count used to select the plural form (ignored for
|
||||||
* singular entries).
|
* singular entries).
|
||||||
* @param stringBuffer Buffer to receive the translated string.
|
* @param stringBuffer Buffer to receive the translated string.
|
||||||
@@ -349,27 +226,6 @@ errorret_t assetLocaleGetString(
|
|||||||
const size_t stringBufferSize
|
const size_t stringBufferSize
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads the PO file's header entry (the `msgid ""` block every PO file
|
|
||||||
* starts with, holding metadata like the plural-forms rule) - see @ref
|
|
||||||
* assetLocaleParseHeader, its caller. A dedicated function rather than
|
|
||||||
* calling assetLocaleGetString(file, "", ...) since messageId "" is a
|
|
||||||
* PO-format-internal sentinel, not a real (untrusted) caller-supplied
|
|
||||||
* message ID, so it doesn't go through assetLocaleGetString's normal
|
|
||||||
* non-empty validation.
|
|
||||||
*
|
|
||||||
* @param file Locale file to search. Must be open.
|
|
||||||
* @param stringBuffer Buffer to receive the raw header block.
|
|
||||||
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
|
||||||
* @return OK on success, error if the header entry is missing or I/O
|
|
||||||
* fails.
|
|
||||||
*/
|
|
||||||
errorret_t assetLocaleGetHeader(
|
|
||||||
assetlocalefile_t *file,
|
|
||||||
char_t *stringBuffer,
|
|
||||||
const size_t stringBufferSize
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Looks up a translated string and formats it with a `printf`-style variadic
|
* Looks up a translated string and formats it with a `printf`-style variadic
|
||||||
* argument list.
|
* argument list.
|
||||||
|
|||||||
@@ -1,255 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "assetmp3loader.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/math.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "asset/loader/assetloading.h"
|
|
||||||
#include "asset/loader/assetentry.h"
|
|
||||||
|
|
||||||
// How far into the file (after any ID3v2 tag) assetMp3ParseHeader() will
|
|
||||||
// search for the first valid MPEG frame sync. Real encoders write it
|
|
||||||
// within the first handful of bytes; this is a generous sane upper bound
|
|
||||||
// (matching assetwavloader.c's own approach to bounding a stack buffer)
|
|
||||||
// rather than a real expectation of needing that much.
|
|
||||||
#define ASSET_MP3_HEADER_SEARCH_MAX 8192
|
|
||||||
|
|
||||||
// MPEG-1 Layer III bitrates (kbps), indexed by the header's 4-bit bitrate
|
|
||||||
// index. Index 0 ("free format") and 15 (reserved) aren't supported.
|
|
||||||
static const uint16_t ASSET_MP3_BITRATE_MPEG1_L3[16] = {
|
|
||||||
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0
|
|
||||||
};
|
|
||||||
|
|
||||||
// MPEG-2/2.5 Layer III bitrates (kbps) - a different table from MPEG-1's.
|
|
||||||
static const uint16_t ASSET_MP3_BITRATE_MPEG2_L3[16] = {
|
|
||||||
0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0
|
|
||||||
};
|
|
||||||
|
|
||||||
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG1[4] = {
|
|
||||||
44100, 48000, 32000, 0
|
|
||||||
};
|
|
||||||
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG2[4] = {
|
|
||||||
22050, 24000, 16000, 0
|
|
||||||
};
|
|
||||||
static const uint32_t ASSET_MP3_SAMPLE_RATE_MPEG25[4] = {
|
|
||||||
11025, 12000, 8000, 0
|
|
||||||
};
|
|
||||||
|
|
||||||
errorret_t assetMp3LoaderAsync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertNotMainThread("Async loader should not be on main thread.");
|
|
||||||
|
|
||||||
if(loading->loading.mp3.state != ASSET_MP3_LOADER_STATE_READ_HEADER) {
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
assetmp3file_t *mp3File = &loading->entry->data.mp3;
|
|
||||||
memoryZero(mp3File, sizeof(assetmp3file_t));
|
|
||||||
|
|
||||||
assetfile_t file;
|
|
||||||
assetLoaderErrorChain(loading, assetFileInit(
|
|
||||||
&file, loading->entry->name, NULL, NULL
|
|
||||||
));
|
|
||||||
assetLoaderErrorChain(loading, assetFileOpen(&file));
|
|
||||||
assetLoaderErrorChain(loading, assetMp3ParseHeader(&file, mp3File));
|
|
||||||
assetLoaderErrorChain(loading, assetFileClose(&file));
|
|
||||||
assetLoaderErrorChain(loading, assetFileDispose(&file));
|
|
||||||
|
|
||||||
loading->loading.mp3.state = ASSET_MP3_LOADER_STATE_DONE;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetMp3LoaderSync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertTrue(loading->type == ASSET_LOADER_TYPE_MP3, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
switch(loading->loading.mp3.state) {
|
|
||||||
case ASSET_MP3_LOADER_STATE_INITIAL:
|
|
||||||
loading->loading.mp3.state = ASSET_MP3_LOADER_STATE_READ_HEADER;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
|
||||||
errorOk();
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ASSET_MP3_LOADER_STATE_DONE:
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetMp3Dispose(assetentry_t *entry) {
|
|
||||||
assertNotNull(entry, "Asset entry cannot be NULL");
|
|
||||||
assertTrue(entry->type == ASSET_LOADER_TYPE_MP3, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetMp3ParseHeader(assetfile_t *file, assetmp3file_t *mp3File) {
|
|
||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
|
||||||
assertNotNull(mp3File, "Mp3 file cannot be NULL.");
|
|
||||||
|
|
||||||
memoryZero(mp3File, sizeof(assetmp3file_t));
|
|
||||||
|
|
||||||
// Skip a leading ID3v2 tag if present: "ID3" + version(2) + flags(1) + a
|
|
||||||
// 4-byte syncsafe (7 usable bits/byte) size covering everything after
|
|
||||||
// this 10-byte header.
|
|
||||||
uint8_t id3Header[10];
|
|
||||||
errorChain(assetFileRead(file, id3Header, sizeof(id3Header)));
|
|
||||||
|
|
||||||
size_t searchBase;
|
|
||||||
if(memoryCompare(id3Header, "ID3", 3) == 0) {
|
|
||||||
const uint32_t tagSize = (
|
|
||||||
((uint32_t) (id3Header[6] & 0x7F) << 21) |
|
|
||||||
((uint32_t) (id3Header[7] & 0x7F) << 14) |
|
|
||||||
((uint32_t) (id3Header[8] & 0x7F) << 7) |
|
|
||||||
((uint32_t) (id3Header[9] & 0x7F))
|
|
||||||
);
|
|
||||||
errorChain(assetFileRead(file, NULL, tagSize));
|
|
||||||
searchBase = sizeof(id3Header) + tagSize;
|
|
||||||
} else {
|
|
||||||
// No ID3v2 tag - rewind the probe bytes just consumed so the frame
|
|
||||||
// sync search below starts from the true beginning of the file.
|
|
||||||
errorChain(assetFileRewind(file));
|
|
||||||
searchBase = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t searchWindowSize = mathMin(
|
|
||||||
(size_t) ASSET_MP3_HEADER_SEARCH_MAX,
|
|
||||||
(size_t) file->size > searchBase ? (size_t) file->size - searchBase : 0
|
|
||||||
);
|
|
||||||
if(searchWindowSize < 4) {
|
|
||||||
errorThrow(
|
|
||||||
"MP3 file is too short to contain a frame header: %s", file->filename
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t *window = (uint8_t *) memoryAllocate(searchWindowSize);
|
|
||||||
errorret_t readRet = assetFileRead(file, window, searchWindowSize);
|
|
||||||
if(errorIsNotOk(readRet)) {
|
|
||||||
memoryFree(window);
|
|
||||||
errorChain(readRet);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool_t found = false;
|
|
||||||
size_t frameIndex = 0;
|
|
||||||
|
|
||||||
for(size_t i = 0; i + 4 <= searchWindowSize; i++) {
|
|
||||||
if(window[i] != 0xFF || (window[i + 1] & 0xE0) != 0xE0) continue;
|
|
||||||
|
|
||||||
const uint8_t versionBits = (window[i + 1] >> 3) & 0x3;
|
|
||||||
const uint8_t layerBits = (window[i + 1] >> 1) & 0x3;
|
|
||||||
// reserved version, or not Layer III
|
|
||||||
if(versionBits == 1 || layerBits != 1) continue;
|
|
||||||
|
|
||||||
const uint8_t bitrateIndex = (window[i + 2] >> 4) & 0xF;
|
|
||||||
const uint8_t sampleRateIndex = (window[i + 2] >> 2) & 0x3;
|
|
||||||
if(
|
|
||||||
bitrateIndex == 0 || bitrateIndex == 15 || sampleRateIndex == 3
|
|
||||||
) continue;
|
|
||||||
|
|
||||||
const uint8_t channelMode = (window[i + 3] >> 6) & 0x3;
|
|
||||||
const bool_t isMpeg1 = versionBits == 3;
|
|
||||||
|
|
||||||
mp3File->bitrateKbps = isMpeg1
|
|
||||||
? ASSET_MP3_BITRATE_MPEG1_L3[bitrateIndex]
|
|
||||||
: ASSET_MP3_BITRATE_MPEG2_L3[bitrateIndex];
|
|
||||||
mp3File->sampleRate = isMpeg1
|
|
||||||
? ASSET_MP3_SAMPLE_RATE_MPEG1[sampleRateIndex]
|
|
||||||
: (versionBits == 2
|
|
||||||
? ASSET_MP3_SAMPLE_RATE_MPEG2[sampleRateIndex]
|
|
||||||
: ASSET_MP3_SAMPLE_RATE_MPEG25[sampleRateIndex]);
|
|
||||||
mp3File->samplesPerFrame = isMpeg1 ? 1152 : 576;
|
|
||||||
mp3File->channels = channelMode == 3 ? 1 : 2;
|
|
||||||
|
|
||||||
// A Xing/Info header, if present, sits right after the side info -
|
|
||||||
// whose size depends on MPEG version and channel mode - immediately
|
|
||||||
// following the 4-byte header (plus a 2-byte CRC, if the protection
|
|
||||||
// bit says one follows).
|
|
||||||
const bool_t hasCrc = (window[i + 1] & 0x1) == 0;
|
|
||||||
const size_t sideInfoSize = isMpeg1
|
|
||||||
? (mp3File->channels == 1 ? 17 : 32)
|
|
||||||
: (mp3File->channels == 1 ? 9 : 17);
|
|
||||||
const size_t xingOffset = i + 4 + (hasCrc ? 2 : 0) + sideInfoSize;
|
|
||||||
|
|
||||||
if(
|
|
||||||
xingOffset + 8 <= searchWindowSize &&
|
|
||||||
(
|
|
||||||
memoryCompare(window + xingOffset, "Xing", 4) == 0 ||
|
|
||||||
memoryCompare(window + xingOffset, "Info", 4) == 0
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
const uint8_t *flagsBytes = window + xingOffset + 4;
|
|
||||||
const uint32_t flags = (
|
|
||||||
((uint32_t) flagsBytes[0] << 24) | ((uint32_t) flagsBytes[1] << 16) |
|
|
||||||
((uint32_t) flagsBytes[2] << 8) | (uint32_t) flagsBytes[3]
|
|
||||||
);
|
|
||||||
if((flags & 0x1) != 0 && xingOffset + 12 <= searchWindowSize) {
|
|
||||||
const uint8_t *framesBytes = window + xingOffset + 8;
|
|
||||||
const uint32_t xingFrameCount = (
|
|
||||||
((uint32_t) framesBytes[0] << 24) |
|
|
||||||
((uint32_t) framesBytes[1] << 16) |
|
|
||||||
((uint32_t) framesBytes[2] << 8) |
|
|
||||||
(uint32_t) framesBytes[3]
|
|
||||||
);
|
|
||||||
// The Xing/Info header's frame count includes the header's own
|
|
||||||
// frame (this one, at `i`) - which libmad (and sceMp3) will
|
|
||||||
// attempt to decode like any other, but which doesn't contribute a
|
|
||||||
// real decodable frame of audio the way every other one does.
|
|
||||||
// Confirmed against a real LAME-encoded file: its Xing header
|
|
||||||
// declared 40 frames, but decoding actually produced exactly 39
|
|
||||||
// frames' worth of real PCM - without this -1, playback would
|
|
||||||
// permanently stall one frame short of the declared total (audible
|
|
||||||
// as "never loops"), since real decode output can never catch up
|
|
||||||
// to an overstated total.
|
|
||||||
if(xingFrameCount > 0) {
|
|
||||||
mp3File->totalFrames =
|
|
||||||
(size_t) (xingFrameCount - 1) * mp3File->samplesPerFrame;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
frameIndex = i;
|
|
||||||
found = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
memoryFree(window);
|
|
||||||
|
|
||||||
if(!found) {
|
|
||||||
errorThrow(
|
|
||||||
"MP3 file has no valid MPEG-1/2/2.5 Layer III frame within the first "
|
|
||||||
"%u bytes: %s",
|
|
||||||
(uint32_t) searchWindowSize, file->filename
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
mp3File->dataOffset = searchBase + frameIndex;
|
|
||||||
mp3File->dataSize = (size_t) file->size - mp3File->dataOffset;
|
|
||||||
|
|
||||||
// No Xing/Info header found - estimate assuming constant bitrate (the
|
|
||||||
// common case when one's genuinely absent; a real VBR file without one
|
|
||||||
// is rare and will just get an approximate duration/loop point instead
|
|
||||||
// of an exact one).
|
|
||||||
if(mp3File->totalFrames == 0) {
|
|
||||||
const float_t durationSeconds = (
|
|
||||||
((float_t) mp3File->dataSize * 8.0f) /
|
|
||||||
((float_t) mp3File->bitrateKbps * 1000.0f)
|
|
||||||
);
|
|
||||||
mp3File->totalFrames =
|
|
||||||
(size_t) (durationSeconds * (float_t) mp3File->sampleRate);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,113 +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"
|
|
||||||
#include "asset/assetfile.h"
|
|
||||||
|
|
||||||
typedef struct assetloading_s assetloading_t;
|
|
||||||
typedef struct assetentry_s assetentry_t;
|
|
||||||
|
|
||||||
typedef struct { void *nothing; } assetmp3loaderinput_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ASSET_MP3_LOADER_STATE_INITIAL,
|
|
||||||
ASSET_MP3_LOADER_STATE_READ_HEADER,
|
|
||||||
ASSET_MP3_LOADER_STATE_DONE
|
|
||||||
} assetmp3loaderstate_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
assetmp3loaderstate_t state;
|
|
||||||
} assetmp3loaderloading_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parsed metadata for an MP3 asset - deliberately just enough to configure
|
|
||||||
* a decoder and know the clip's total length, not anything about its
|
|
||||||
* actual compressed content (which is read/decoded on demand at playback
|
|
||||||
* time - see audiostreammp3.c). Only MPEG-1/2/2.5 Layer III ("MP3" in the
|
|
||||||
* everyday sense) is supported; Layers I/II are rejected.
|
|
||||||
*/
|
|
||||||
typedef struct {
|
|
||||||
uint32_t sampleRate;
|
|
||||||
uint8_t channels;
|
|
||||||
|
|
||||||
// 1152 for MPEG-1, 576 for MPEG-2/2.5 - how many PCM samples (per
|
|
||||||
// channel) one compressed MPEG frame decodes to.
|
|
||||||
uint16_t samplesPerFrame;
|
|
||||||
|
|
||||||
// The first frame's bitrate, in kbps. Used only as a fallback duration
|
|
||||||
// estimate (assuming CBR) when no Xing/Info header is found - see
|
|
||||||
// assetMp3ParseHeader()'s own comment.
|
|
||||||
uint32_t bitrateKbps;
|
|
||||||
|
|
||||||
// Byte offset (from the start of the file) of the first real MPEG
|
|
||||||
// frame, i.e. right after any leading ID3v2 tag.
|
|
||||||
size_t dataOffset;
|
|
||||||
|
|
||||||
// Bytes of compressed MPEG data, from dataOffset to the end of the file.
|
|
||||||
size_t dataSize;
|
|
||||||
|
|
||||||
// Decoded PCM frame count for the whole clip - exact if a Xing/Info
|
|
||||||
// header was found (the common case for anything encoded with a modern
|
|
||||||
// tool), otherwise estimated from bitrateKbps/dataSize assuming CBR (see
|
|
||||||
// assetMp3ParseHeader()'s own comment) - unlike assetwavfile_t.dataSize,
|
|
||||||
// MP3 has no header field that gives this directly.
|
|
||||||
size_t totalFrames;
|
|
||||||
} assetmp3file_t;
|
|
||||||
|
|
||||||
typedef assetmp3file_t assetmp3output_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Async (background-thread) half of the MP3 loader - opens the asset file,
|
|
||||||
* parses its header (see assetMp3ParseHeader()), and closes it again. Never
|
|
||||||
* buffers the compressed MPEG data itself; that's read on demand at
|
|
||||||
* playback time by audiostreammp3.c via its own independent file handle.
|
|
||||||
*
|
|
||||||
* @param loading The asset loading slot.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t assetMp3LoaderAsync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sync (main-thread) half of the MP3 loader - a simple state machine that
|
|
||||||
* schedules the async header parse and marks the entry loaded once it's
|
|
||||||
* done, mirroring assetWavLoaderSync()'s shape exactly.
|
|
||||||
*
|
|
||||||
* @param loading The asset loading slot.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t assetMp3LoaderSync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disposes an MP3 asset entry. A no-op - an assetmp3file_t owns no heap
|
|
||||||
* allocations, and playback streams open their own independent file
|
|
||||||
* handles (see audiostreammp3.c).
|
|
||||||
*
|
|
||||||
* @param entry The asset entry to dispose.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t assetMp3Dispose(assetentry_t *entry);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses an MP3 file's metadata from an already-opened asset file
|
|
||||||
* positioned at its very start: skips a leading ID3v2 tag if present,
|
|
||||||
* scans forward for the first valid MPEG-1/2/2.5 Layer III frame header
|
|
||||||
* (rejecting anything else - other layers, or no valid frame found within
|
|
||||||
* a sane search window), and checks that frame for a Xing/Info header
|
|
||||||
* (found in the vast majority of real-world MP3s, VBR or CBR) to get an
|
|
||||||
* exact total-frame count; falls back to a CBR estimate from the first
|
|
||||||
* frame's bitrate and the file's remaining size if absent.
|
|
||||||
*
|
|
||||||
* Never reads more than a bounded lookahead window into memory - the bulk
|
|
||||||
* of the file (the actual compressed audio, following the parsed frame's
|
|
||||||
* position) is left untouched, exactly like assetWavParseHeader().
|
|
||||||
*
|
|
||||||
* @param file Asset file to parse, positioned at offset 0.
|
|
||||||
* @param mp3File Filled with the parsed metadata on success.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t assetMp3ParseHeader(assetfile_t *file, assetmp3file_t *mp3File);
|
|
||||||
@@ -1,181 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "assetwavloader.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/endian.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "asset/loader/assetloading.h"
|
|
||||||
#include "asset/loader/assetentry.h"
|
|
||||||
|
|
||||||
// "RIFF" + chunkSize + "WAVE", before any sub-chunks begin.
|
|
||||||
#define ASSET_WAV_RIFF_HEADER_SIZE 12
|
|
||||||
|
|
||||||
// A sub-chunk header is a 4-byte id followed by a 4-byte little-endian size.
|
|
||||||
#define ASSET_WAV_CHUNK_HEADER_SIZE 8
|
|
||||||
|
|
||||||
#define ASSET_WAV_FMT_CHUNK_SIZE_MIN 16
|
|
||||||
// Sane upper bound for a stack buffer - real fmt chunks (PCM or otherwise)
|
|
||||||
// never come close to this; anything bigger is treated as malformed.
|
|
||||||
#define ASSET_WAV_FMT_CHUNK_SIZE_MAX 64
|
|
||||||
|
|
||||||
errorret_t assetWavLoaderAsync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertNotMainThread("Async loader should not be on main thread.");
|
|
||||||
|
|
||||||
if(loading->loading.wav.state != ASSET_WAV_LOADER_STATE_READ_HEADER) {
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
assetwavfile_t *wavFile = &loading->entry->data.wav;
|
|
||||||
memoryZero(wavFile, sizeof(assetwavfile_t));
|
|
||||||
|
|
||||||
assetfile_t file;
|
|
||||||
assetLoaderErrorChain(loading, assetFileInit(
|
|
||||||
&file, loading->entry->name, NULL, NULL
|
|
||||||
));
|
|
||||||
assetLoaderErrorChain(loading, assetFileOpen(&file));
|
|
||||||
assetLoaderErrorChain(loading, assetWavParseHeader(&file, wavFile));
|
|
||||||
assetLoaderErrorChain(loading, assetFileClose(&file));
|
|
||||||
assetLoaderErrorChain(loading, assetFileDispose(&file));
|
|
||||||
|
|
||||||
loading->loading.wav.state = ASSET_WAV_LOADER_STATE_DONE;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetWavLoaderSync(assetloading_t *loading) {
|
|
||||||
assertNotNull(loading, "Loading cannot be NULL");
|
|
||||||
assertTrue(loading->type == ASSET_LOADER_TYPE_WAV, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
switch(loading->loading.wav.state) {
|
|
||||||
case ASSET_WAV_LOADER_STATE_INITIAL:
|
|
||||||
loading->loading.wav.state = ASSET_WAV_LOADER_STATE_READ_HEADER;
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
|
||||||
errorOk();
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ASSET_WAV_LOADER_STATE_DONE:
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetWavDispose(assetentry_t *entry) {
|
|
||||||
assertNotNull(entry, "Asset entry cannot be NULL");
|
|
||||||
assertTrue(entry->type == ASSET_LOADER_TYPE_WAV, "Invalid type.");
|
|
||||||
assertIsMainThread("Must be called from the main thread.");
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t assetWavParseHeader(
|
|
||||||
assetfile_t *file,
|
|
||||||
assetwavfile_t *wavFile
|
|
||||||
) {
|
|
||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
|
||||||
assertNotNull(wavFile, "Wav file cannot be NULL.");
|
|
||||||
|
|
||||||
uint8_t riffHeader[ASSET_WAV_RIFF_HEADER_SIZE];
|
|
||||||
errorChain(assetFileRead(file, riffHeader, sizeof(riffHeader)));
|
|
||||||
|
|
||||||
if(memoryCompare(riffHeader, "RIFF", 4) != 0) {
|
|
||||||
errorThrow("WAV file has an invalid RIFF header: %s", file->filename);
|
|
||||||
}
|
|
||||||
if(memoryCompare(riffHeader + 8, "WAVE", 4) != 0) {
|
|
||||||
errorThrow("WAV file has an invalid WAVE header: %s", file->filename);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool_t foundFormat = false;
|
|
||||||
bool_t foundData = false;
|
|
||||||
uint16_t audioFormat = 0;
|
|
||||||
|
|
||||||
// Walk the chunk list, reading only chunk headers (and the small "fmt "
|
|
||||||
// body) - every other chunk, "data"'s sample bytes included, is skipped
|
|
||||||
// via a NULL-buffer read rather than buffered into memory. Stops as soon
|
|
||||||
// as "data" is found; nothing after it matters here.
|
|
||||||
while(!foundData && (size_t) file->position < (size_t) file->size) {
|
|
||||||
uint8_t chunkHeader[ASSET_WAV_CHUNK_HEADER_SIZE];
|
|
||||||
errorChain(assetFileRead(file, chunkHeader, sizeof(chunkHeader)));
|
|
||||||
|
|
||||||
uint32_t chunkSizeLE;
|
|
||||||
memoryCopy(&chunkSizeLE, chunkHeader + 4, sizeof(chunkSizeLE));
|
|
||||||
const uint32_t chunkSize = endianLittleToHost32(chunkSizeLE);
|
|
||||||
|
|
||||||
// Chunks are padded to an even total size - the pad byte (if any)
|
|
||||||
// isn't included in chunkSize but still needs to be skipped over.
|
|
||||||
const uint32_t chunkSizePadded = chunkSize + (chunkSize % 2);
|
|
||||||
|
|
||||||
if(memoryCompare(chunkHeader, "fmt ", 4) == 0) {
|
|
||||||
if(
|
|
||||||
chunkSize < ASSET_WAV_FMT_CHUNK_SIZE_MIN ||
|
|
||||||
chunkSize > ASSET_WAV_FMT_CHUNK_SIZE_MAX
|
|
||||||
) {
|
|
||||||
errorThrow("WAV 'fmt ' chunk has an unsupported size: %u", chunkSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t fmtBuffer[ASSET_WAV_FMT_CHUNK_SIZE_MAX];
|
|
||||||
errorChain(assetFileRead(file, fmtBuffer, chunkSize));
|
|
||||||
if(chunkSize % 2 != 0) {
|
|
||||||
errorChain(assetFileRead(file, NULL, 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
uint16_t u16;
|
|
||||||
uint32_t u32;
|
|
||||||
|
|
||||||
memoryCopy(&u16, fmtBuffer + 0, sizeof(u16));
|
|
||||||
audioFormat = endianLittleToHost16(u16);
|
|
||||||
|
|
||||||
memoryCopy(&u16, fmtBuffer + 2, sizeof(u16));
|
|
||||||
wavFile->channels = (uint8_t) endianLittleToHost16(u16);
|
|
||||||
|
|
||||||
memoryCopy(&u32, fmtBuffer + 4, sizeof(u32));
|
|
||||||
wavFile->sampleRate = endianLittleToHost32(u32);
|
|
||||||
|
|
||||||
memoryCopy(&u16, fmtBuffer + 14, sizeof(u16));
|
|
||||||
wavFile->bitsPerSample = (uint8_t) endianLittleToHost16(u16);
|
|
||||||
|
|
||||||
foundFormat = true;
|
|
||||||
} else if(memoryCompare(chunkHeader, "data", 4) == 0) {
|
|
||||||
wavFile->dataOffset = (size_t) file->position;
|
|
||||||
wavFile->dataSize = chunkSize;
|
|
||||||
foundData = true;
|
|
||||||
} else {
|
|
||||||
errorChain(assetFileRead(file, NULL, chunkSizePadded));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!foundFormat) {
|
|
||||||
errorThrow("WAV file is missing its 'fmt ' chunk: %s", file->filename);
|
|
||||||
}
|
|
||||||
if(!foundData) {
|
|
||||||
errorThrow("WAV file is missing its 'data' chunk: %s", file->filename);
|
|
||||||
}
|
|
||||||
if(audioFormat != 1) {
|
|
||||||
errorThrow(
|
|
||||||
"Unsupported WAV audio format: %u (only PCM is supported): %s",
|
|
||||||
audioFormat, file->filename
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if(wavFile->bitsPerSample != 16 && wavFile->bitsPerSample != 24) {
|
|
||||||
errorThrow(
|
|
||||||
"Unsupported WAV bits per sample: %u (only 16/24-bit is supported): %s",
|
|
||||||
wavFile->bitsPerSample, file->filename
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if(wavFile->channels == 0) {
|
|
||||||
errorThrow("WAV file declares 0 channels: %s", file->filename);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "asset/assetfile.h"
|
|
||||||
|
|
||||||
typedef struct assetloading_s assetloading_t;
|
|
||||||
typedef struct assetentry_s assetentry_t;
|
|
||||||
|
|
||||||
/** Input passed to the wav loader - currently unused. */
|
|
||||||
typedef struct { void *nothing; } assetwavloaderinput_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ASSET_WAV_LOADER_STATE_INITIAL,
|
|
||||||
ASSET_WAV_LOADER_STATE_READ_HEADER,
|
|
||||||
ASSET_WAV_LOADER_STATE_DONE
|
|
||||||
} assetwavloaderstate_t;
|
|
||||||
|
|
||||||
/** Per-slot scratch data used while the wav file is loading. */
|
|
||||||
typedef struct {
|
|
||||||
assetwavloaderstate_t state;
|
|
||||||
} assetwavloaderloading_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parsed metadata for a WAV asset - only the RIFF/WAVE/fmt/data chunk
|
|
||||||
* headers are ever read; the PCM sample data itself is never loaded here
|
|
||||||
* (see @ref assetWavParseHeader). Playback reads sample data directly
|
|
||||||
* from the archive on demand instead - see audiostreampcm.h.
|
|
||||||
*/
|
|
||||||
typedef struct {
|
|
||||||
/** Sample rate of the PCM data, in Hz. */
|
|
||||||
uint32_t sampleRate;
|
|
||||||
|
|
||||||
/** Number of interleaved channels in the PCM data. */
|
|
||||||
uint8_t channels;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bits per sample of the *source* file data - 16 or 24 (see
|
|
||||||
* assetWavParseHeader). Playback always reads 16-bit samples out via
|
|
||||||
* audioStreamPcmRead() regardless of this - a 24-bit source is
|
|
||||||
* truncated to 16-bit there, since none of this project's audio
|
|
||||||
* backends (PSP/Dolphin hardware, SDL2 on Linux) accept anything wider.
|
|
||||||
*/
|
|
||||||
uint8_t bitsPerSample;
|
|
||||||
|
|
||||||
/** Byte offset from the start of the file to the first PCM sample. */
|
|
||||||
size_t dataOffset;
|
|
||||||
|
|
||||||
/** Size of the PCM data, in bytes. */
|
|
||||||
size_t dataSize;
|
|
||||||
} assetwavfile_t;
|
|
||||||
|
|
||||||
/** Convenience alias - the loaded output type of a wav asset entry. */
|
|
||||||
typedef assetwavfile_t assetwavoutput_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Asynchronous loader callback. Opens the WAV file and reads just enough of
|
|
||||||
* it to locate and parse the `fmt ` chunk and locate (not read) the `data`
|
|
||||||
* chunk - see @ref assetWavParseHeader. All I/O happens here so the main
|
|
||||||
* thread is not blocked. Sets entry state to `ASSET_ENTRY_STATE_PENDING_SYNC`
|
|
||||||
* on success or `ASSET_ENTRY_STATE_ERROR` on failure.
|
|
||||||
*
|
|
||||||
* @param loading The loading slot for this asset entry.
|
|
||||||
* @return OK on success, error otherwise.
|
|
||||||
*/
|
|
||||||
errorret_t assetWavLoaderAsync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Synchronous loader callback. Confirms the async phase completed and marks
|
|
||||||
* the entry as `ASSET_ENTRY_STATE_LOADED`.
|
|
||||||
*
|
|
||||||
* @param loading The loading slot for this asset entry.
|
|
||||||
* @return OK on success, error otherwise.
|
|
||||||
*/
|
|
||||||
errorret_t assetWavLoaderSync(assetloading_t *loading);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Dispose callback. The wav asset owns no allocations of its own (its data
|
|
||||||
* chunk is read directly from the archive by whichever streams are playing
|
|
||||||
* it, each through their own handle - see audiostreampcm.h), so this is
|
|
||||||
* currently a no-op beyond the standard asserts.
|
|
||||||
*
|
|
||||||
* @param entry The asset entry to dispose.
|
|
||||||
* @return OK on success, error otherwise.
|
|
||||||
*/
|
|
||||||
errorret_t assetWavDispose(assetentry_t *entry);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses a RIFF/WAVE file's chunk structure from an already-open asset
|
|
||||||
* file, reading only chunk headers (and the small `fmt ` chunk body) -
|
|
||||||
* every other chunk, including `data`'s actual sample bytes, is skipped
|
|
||||||
* over via `assetFileRead(file, NULL, size)` rather than read into memory,
|
|
||||||
* so this never buffers the (potentially large) PCM payload.
|
|
||||||
*
|
|
||||||
* Stops as soon as the `data` chunk header is found, recording its file
|
|
||||||
* offset and declared size in `wavFile` without reading any of its bytes -
|
|
||||||
* the file is left positioned at the start of the PCM data.
|
|
||||||
*
|
|
||||||
* Only PCM (audio format 1), 16- or 24-bit-per-sample WAV data is
|
|
||||||
* supported - see audiostreampcm.h's audioStreamPcmRead() for how a
|
|
||||||
* 24-bit source gets truncated to the 16-bit output every platform
|
|
||||||
* backend expects. Requires the `fmt ` chunk to appear before `data`, per
|
|
||||||
* the WAV spec's recommended ordering.
|
|
||||||
*
|
|
||||||
* @param file An open asset file, positioned at the start of the WAV data.
|
|
||||||
* @param wavFile Struct whose fields will be filled in.
|
|
||||||
* @return OK on success, error if the file is malformed or an unsupported
|
|
||||||
* format.
|
|
||||||
*/
|
|
||||||
errorret_t assetWavParseHeader(
|
|
||||||
assetfile_t *file,
|
|
||||||
assetwavfile_t *wavFile
|
|
||||||
);
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "audio.h"
|
|
||||||
#include "audio/mixer/audiomixer.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
|
|
||||||
audio_t AUDIO;
|
|
||||||
|
|
||||||
errorret_t audioInit() {
|
|
||||||
memoryZero(&AUDIO, sizeof(audio_t));
|
|
||||||
|
|
||||||
errorChain(audioPlatformInit());
|
|
||||||
errorChain(audioMixerInit());
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
audiostream_t * audioAquireStream(assetentry_t *asset) {
|
|
||||||
assertNotNull(asset, "Asset cannot be NULL.");
|
|
||||||
// Same check audioStreamInit() makes - see its own comment on why this
|
|
||||||
// is an assert (a programmer error, not untrusted data). Checking here
|
|
||||||
// too catches the mistake as early as possible, before any stream slot
|
|
||||||
// is handed out for it.
|
|
||||||
assertTrue(
|
|
||||||
audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
|
|
||||||
"Unsupported asset type for an audio stream."
|
|
||||||
);
|
|
||||||
|
|
||||||
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
|
|
||||||
audiostream_t *stream = &AUDIO.streams[i];
|
|
||||||
if(stream->type == AUDIO_STREAM_TYPE_NULL) {
|
|
||||||
return stream;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioUpdateEarly() {
|
|
||||||
errorChain(audioPlatformUpdate());
|
|
||||||
errorChain(audioMixerUpdateEarly());
|
|
||||||
|
|
||||||
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
|
|
||||||
audiostream_t *stream = &AUDIO.streams[i];
|
|
||||||
errorChain(audioStreamUpdate(stream));
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioUpdateLate() {
|
|
||||||
errorChain(audioMixerUpdateLate());
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioDispose() {
|
|
||||||
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
|
|
||||||
audiostream_t *stream = &AUDIO.streams[i];
|
|
||||||
errorChain(audioStreamDispose(stream));
|
|
||||||
}
|
|
||||||
|
|
||||||
errorChain(audioMixerDispose());
|
|
||||||
errorChain(audioPlatformDispose());
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "dusk.h"
|
|
||||||
#include "audio/stream/audiostream.h"
|
|
||||||
#include "audio/audioplatform.h"
|
|
||||||
|
|
||||||
#ifndef audioPlatformInit
|
|
||||||
#error "audioPlatformInit is not defined"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef audioPlatformUpdate
|
|
||||||
#error "audioPlatformUpdate is not defined"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef audioPlatformDispose
|
|
||||||
#error "audioPlatformDispose is not defined"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
audiostream_t streams[AUDIO_STREAMS_MAX];
|
|
||||||
} audio_t;
|
|
||||||
|
|
||||||
extern audio_t AUDIO;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes the audio subsystem.
|
|
||||||
*
|
|
||||||
* @return Error indicating success or failure of the operation.
|
|
||||||
*/
|
|
||||||
errorret_t audioInit();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aquires an available audio stream for playing the given asset. Can return
|
|
||||||
* NULL if there is no available stream slot.
|
|
||||||
*
|
|
||||||
* The returned stream is not yet configured to play `asset` - call
|
|
||||||
* audioStreamInit(stream, asset) next.
|
|
||||||
*
|
|
||||||
* @param asset The asset the caller intends to play - validated eagerly so
|
|
||||||
* an unsupported asset type is caught here rather than only
|
|
||||||
* once audioStreamInit() is called.
|
|
||||||
* @return Pointer to an available audio stream, or NULL if none are free.
|
|
||||||
*/
|
|
||||||
audiostream_t * audioAquireStream(assetentry_t *asset);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the audio subsystem, updating every active stream. Should be
|
|
||||||
* called once per frame, before rendering - keeps stream buffering/decode
|
|
||||||
* work off the render thread's critical path (see duskmad's MP3 decode
|
|
||||||
* ring for why this matters).
|
|
||||||
*
|
|
||||||
* @return Error indicating success or failure of the operation.
|
|
||||||
*/
|
|
||||||
errorret_t audioUpdateEarly();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the audio subsystem's end-of-frame work - currently just starting
|
|
||||||
* whatever the audio mixer queued this frame (see
|
|
||||||
* audioMixerUpdateLate()'s own comment). Should be called once per frame,
|
|
||||||
* after rendering.
|
|
||||||
*
|
|
||||||
* @return Error indicating success or failure of the operation.
|
|
||||||
*/
|
|
||||||
errorret_t audioUpdateLate();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disposes the audio subsystem, stopping and disposing every active stream.
|
|
||||||
*
|
|
||||||
* @return Error indicating success or failure of the operation.
|
|
||||||
*/
|
|
||||||
errorret_t audioDispose();
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Copyright (c) 2026 Dominic Masters
|
|
||||||
#
|
|
||||||
# This software is released under the MIT License.
|
|
||||||
# https://opensource.org/licenses/MIT
|
|
||||||
|
|
||||||
# Sources
|
|
||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
|
||||||
PUBLIC
|
|
||||||
audiomixer.c
|
|
||||||
audiomixerchannel.c
|
|
||||||
)
|
|
||||||
@@ -1,199 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "audiomixer.h"
|
|
||||||
#include "audio/stream/audiostream.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/string.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
|
|
||||||
audiomixer_t AUDIO_MIXER;
|
|
||||||
|
|
||||||
errorret_t audioMixerInit() {
|
|
||||||
memoryZero(&AUDIO_MIXER, sizeof(audiomixer_t));
|
|
||||||
|
|
||||||
audiomixerchannel_t channel = 0;
|
|
||||||
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
|
||||||
AUDIO_MIXER.channels[channel].fade = 1.0f;
|
|
||||||
// -1 means "no fade in progress" - see its own comment; zero-init
|
|
||||||
// would otherwise look like an active fade at time 0.
|
|
||||||
AUDIO_MIXER.channels[channel].fadeTime = -1.0f;
|
|
||||||
channel++;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioMixerUpdateEarly() {
|
|
||||||
audiomixerchannel_t channel = 0;
|
|
||||||
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
|
||||||
// One channel's error (e.g. a failed asset load) must not stop every
|
|
||||||
// other channel from being updated this frame - caught and logged
|
|
||||||
// rather than propagated, same as audioStream*IsFinished()'s own
|
|
||||||
// per-stream error handling.
|
|
||||||
errorret_t ret = audioMixerChannelUpdateEarly(
|
|
||||||
channel, &AUDIO_MIXER.channels[channel]
|
|
||||||
);
|
|
||||||
if(errorIsNotOk(ret)) errorCatch(errorPrint(ret));
|
|
||||||
channel++;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioMixerUpdateLate() {
|
|
||||||
audiomixerchannel_t channel = 0;
|
|
||||||
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
|
||||||
errorret_t ret =
|
|
||||||
audioMixerChannelUpdateLate(&AUDIO_MIXER.channels[channel]);
|
|
||||||
if(errorIsNotOk(ret)) errorCatch(errorPrint(ret));
|
|
||||||
channel++;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerPlay(
|
|
||||||
const char_t *file,
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t volume,
|
|
||||||
const float_t pan
|
|
||||||
) {
|
|
||||||
audioMixerQueuePlay(file, channel, volume, pan, false, 0, -1.0f, 0.0f);
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerPlayLooped(
|
|
||||||
const char_t *file,
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t volume,
|
|
||||||
const float_t pan,
|
|
||||||
const uint8_t loopCount,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
) {
|
|
||||||
audioMixerQueuePlay(
|
|
||||||
file, channel, volume, pan, true, loopCount, loopStart, loopTo
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerQueuePlay(
|
|
||||||
const char_t *file,
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t volume,
|
|
||||||
const float_t pan,
|
|
||||||
const bool_t looping,
|
|
||||||
const uint8_t loopCount,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
) {
|
|
||||||
assertStrLenMin(file, 1, "File is required, to stop use audioMixerStop");
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
assertTrue(volume > 0.0f && volume <= 1.0f, "Volume is out of range");
|
|
||||||
assertTrue(
|
|
||||||
pan >= AUDIO_STREAM_LEFT && pan <= AUDIO_STREAM_RIGHT,
|
|
||||||
"Pan is out of range"
|
|
||||||
);
|
|
||||||
assertTrue(
|
|
||||||
!looping || loopStart < 0.0f || loopTo < loopStart,
|
|
||||||
"Loop points incorrect"
|
|
||||||
);
|
|
||||||
|
|
||||||
audiomixercommand_t *command = &AUDIO_MIXER.channels[channel].pending;
|
|
||||||
|
|
||||||
command->command = AUDIO_MIXER_COMMAND_PLAY;
|
|
||||||
stringCopy(command->file, file, AUDIO_PATH_MAX);
|
|
||||||
command->volume = volume;
|
|
||||||
command->pan = pan;
|
|
||||||
command->looping = looping;
|
|
||||||
command->loopCount = loopCount;
|
|
||||||
command->loopStart = loopStart;
|
|
||||||
command->loopTo = loopTo;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerStop(const audiomixerchannel_t channel) {
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
|
|
||||||
AUDIO_MIXER.channels[channel].pending.command = AUDIO_MIXER_COMMAND_STOP;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerPause(const audiomixerchannel_t channel) {
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
|
|
||||||
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
|
||||||
if(stream != NULL) audioStreamPause(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerResume(const audiomixerchannel_t channel) {
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
|
|
||||||
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
|
||||||
if(stream != NULL) audioStreamPlay(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerSetPan(const audiomixerchannel_t channel, const float_t pan) {
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
assertTrue(
|
|
||||||
pan >= AUDIO_STREAM_LEFT && pan <= AUDIO_STREAM_RIGHT,
|
|
||||||
"Pan is out of range"
|
|
||||||
);
|
|
||||||
|
|
||||||
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
|
||||||
if(stream != NULL) audioStreamSetDirectionality(stream, pan);
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerSetLoop(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const bool_t looping,
|
|
||||||
const uint8_t loopCount,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
) {
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
assertTrue(
|
|
||||||
!looping || loopStart < 0.0f || loopTo < loopStart,
|
|
||||||
"Loop points incorrect"
|
|
||||||
);
|
|
||||||
|
|
||||||
audiostream_t *stream = AUDIO_MIXER.channels[channel].stream;
|
|
||||||
if(stream == NULL) return;
|
|
||||||
|
|
||||||
audioStreamSetLooping(stream, looping);
|
|
||||||
if(looping) {
|
|
||||||
audioStreamSetLoopPoints(stream, loopStart, loopTo);
|
|
||||||
audioStreamSetLoopLimit(stream, loopCount);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerFadeTo(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t from,
|
|
||||||
const float_t to,
|
|
||||||
const float_t duration,
|
|
||||||
const easingtype_t easing
|
|
||||||
) {
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
|
|
||||||
audioMixerChannelFadeTo(
|
|
||||||
&AUDIO_MIXER.channels[channel], from, to, duration, easing
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool_t audioMixerIsFading(const audiomixerchannel_t channel) {
|
|
||||||
assertTrue(channel < AUDIO_MIXER_CHANNEL_COUNT, "Channel is out of range");
|
|
||||||
|
|
||||||
return audioMixerChannelIsFading(&AUDIO_MIXER.channels[channel]);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioMixerDispose() {
|
|
||||||
audiomixerchannel_t channel = 0;
|
|
||||||
while(channel < AUDIO_MIXER_CHANNEL_COUNT) {
|
|
||||||
errorChain(audioMixerChannelStopStream(&AUDIO_MIXER.channels[channel]));
|
|
||||||
channel++;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,204 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "audio/mixer/audiomixerchannel.h"
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
audiomixerchannelstate_t channels[AUDIO_MIXER_CHANNEL_COUNT];
|
|
||||||
} audiomixer_t;
|
|
||||||
|
|
||||||
extern audiomixer_t AUDIO_MIXER;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes the audio mixer.
|
|
||||||
*/
|
|
||||||
errorret_t audioMixerInit();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the audio mixer, called before rendering (the start of the
|
|
||||||
* frame) - see audioMixerChannelUpdateEarly()'s own comment, run for every
|
|
||||||
* channel.
|
|
||||||
*/
|
|
||||||
errorret_t audioMixerUpdateEarly();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the audio mixer, called at the end of each frame - see
|
|
||||||
* audioMixerChannelUpdateLate()'s own comment, run for every channel.
|
|
||||||
*/
|
|
||||||
errorret_t audioMixerUpdateLate();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Same as audioMixerPlayLooped() but with no looping.
|
|
||||||
*
|
|
||||||
* @param file File to be played.
|
|
||||||
* @param channel Channel you want to play this sound on.
|
|
||||||
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
|
|
||||||
* AUDIO_STREAM_RIGHT.
|
|
||||||
*/
|
|
||||||
void audioMixerPlay(
|
|
||||||
const char_t *file,
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t volume,
|
|
||||||
const float_t pan
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Queues a sound to be played on the next audio mixer update, which occurs at
|
|
||||||
* the end of each frame.
|
|
||||||
*
|
|
||||||
* Mixer channels can only hold one voice (audio stream) at a time. If you try
|
|
||||||
* to queue multiple sounds on the same channel only the last one will be played
|
|
||||||
* and will stop any actively playing on that channel currently.
|
|
||||||
*
|
|
||||||
* Volume is also mixed based on the channel, so supplying volume 1.0 is then
|
|
||||||
* multiplied by the channel's volume, e.g. 0.5*1.0 = 0.5.
|
|
||||||
*
|
|
||||||
* @param file File to be played.
|
|
||||||
* @param channel Channel you want to play this sound on.
|
|
||||||
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
|
|
||||||
* AUDIO_STREAM_RIGHT.
|
|
||||||
* @param loopCount How many times to loop the sound, 0 for infinite looping.
|
|
||||||
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
|
||||||
* the whole stream (the default).
|
|
||||||
* @param loopTo Where the loop segment starts, in seconds.
|
|
||||||
*/
|
|
||||||
void audioMixerPlayLooped(
|
|
||||||
const char_t *file,
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t volume,
|
|
||||||
const float_t pan,
|
|
||||||
const uint8_t loopCount,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shared implementation behind audioMixerPlay()/audioMixerPlayLooped() -
|
|
||||||
* queues an AUDIO_MIXER_COMMAND_PLAY for the given channel, to be loaded at
|
|
||||||
* the end of this frame and started at the start of the next (see
|
|
||||||
* audioMixerUpdateLate()/audioMixerUpdateEarly()).
|
|
||||||
*
|
|
||||||
* @param file File to be played.
|
|
||||||
* @param channel Channel you want to play this sound on.
|
|
||||||
* @param volume Volume of the sound, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
* @param pan Stereo panning of the sound, from AUDIO_STREAM_LEFT to
|
|
||||||
* AUDIO_STREAM_RIGHT.
|
|
||||||
* @param looping Whether the stream should loop once it finishes.
|
|
||||||
* @param loopCount How many times to loop the sound, 0 for infinite looping.
|
|
||||||
* Ignored unless looping is true.
|
|
||||||
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
|
||||||
* the whole stream. Ignored unless looping is true.
|
|
||||||
* @param loopTo Where the loop segment starts, in seconds. Ignored unless
|
|
||||||
* looping is true.
|
|
||||||
*/
|
|
||||||
void audioMixerQueuePlay(
|
|
||||||
const char_t *file,
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t volume,
|
|
||||||
const float_t pan,
|
|
||||||
const bool_t looping,
|
|
||||||
const uint8_t loopCount,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stops playing sound on the given channel.
|
|
||||||
*
|
|
||||||
* @param channel Channel to stop.
|
|
||||||
*/
|
|
||||||
void audioMixerStop(const audiomixerchannel_t channel);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pauses the given channel's currently playing stream, if any - a safe
|
|
||||||
* no-op if the channel isn't playing anything. Playback position is
|
|
||||||
* retained, so audioMixerResume() continues from the same point.
|
|
||||||
*
|
|
||||||
* @param channel Channel to pause.
|
|
||||||
*/
|
|
||||||
void audioMixerPause(const audiomixerchannel_t channel);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resumes the given channel's currently paused stream, if any - a safe
|
|
||||||
* no-op if the channel isn't playing anything.
|
|
||||||
*
|
|
||||||
* @param channel Channel to resume.
|
|
||||||
*/
|
|
||||||
void audioMixerResume(const audiomixerchannel_t channel);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the stereo panning of the given channel's currently playing stream,
|
|
||||||
* if any - a safe no-op if the channel isn't playing anything. Only
|
|
||||||
* affects what's playing right now; a later audioMixerPlay()/
|
|
||||||
* audioMixerPlayLooped() call on this channel uses its own `pan` argument
|
|
||||||
* instead.
|
|
||||||
*
|
|
||||||
* @param channel Channel to update.
|
|
||||||
* @param pan Stereo panning, from AUDIO_STREAM_LEFT to AUDIO_STREAM_RIGHT.
|
|
||||||
*/
|
|
||||||
void audioMixerSetPan(const audiomixerchannel_t channel, const float_t pan);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the looping behaviour of the given channel's currently playing
|
|
||||||
* stream, if any - a safe no-op if the channel isn't playing anything.
|
|
||||||
* Only affects what's playing right now; a later audioMixerPlay()/
|
|
||||||
* audioMixerPlayLooped() call on this channel uses its own loop arguments
|
|
||||||
* instead.
|
|
||||||
*
|
|
||||||
* @param channel Channel to update.
|
|
||||||
* @param looping Whether the stream should loop.
|
|
||||||
* @param loopCount How many times to loop, 0 for infinite. Ignored unless
|
|
||||||
* looping is true.
|
|
||||||
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
|
||||||
* the whole stream. Ignored unless looping is true.
|
|
||||||
* @param loopTo Where the loop segment starts, in seconds. Ignored unless
|
|
||||||
* looping is true.
|
|
||||||
*/
|
|
||||||
void audioMixerSetLoop(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const bool_t looping,
|
|
||||||
const uint8_t loopCount,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Starts fading the given channel from `from` to `to` over `duration`
|
|
||||||
* seconds, eased by `easing` - see audioMixerChannelFadeTo()'s own
|
|
||||||
* comment. Continues running (advanced every audioMixerUpdateEarly()) even
|
|
||||||
* if the channel isn't currently playing anything.
|
|
||||||
*
|
|
||||||
* @param channel Channel to fade.
|
|
||||||
* @param from Starting fade value, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
* @param to Ending fade value, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
* @param duration How long the fade takes, in seconds.
|
|
||||||
* @param easing Easing curve to apply to the fade's progress.
|
|
||||||
*/
|
|
||||||
void audioMixerFadeTo(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
const float_t from,
|
|
||||||
const float_t to,
|
|
||||||
const float_t duration,
|
|
||||||
const easingtype_t easing
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether the given channel currently has a fade in progress (started via
|
|
||||||
* audioMixerFadeTo() and not yet finished).
|
|
||||||
*
|
|
||||||
* @param channel Channel to check.
|
|
||||||
* @return true if a fade is still in progress.
|
|
||||||
*/
|
|
||||||
bool_t audioMixerIsFading(const audiomixerchannel_t channel);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disposes the audio mixer.
|
|
||||||
*/
|
|
||||||
errorret_t audioMixerDispose();
|
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "audiomixerchannel.h"
|
|
||||||
#include "asset/asset.h"
|
|
||||||
#include "audio/audio.h"
|
|
||||||
#include "audio/stream/audiostream.h"
|
|
||||||
#include "audio/stream/audiostreamtype.h"
|
|
||||||
#include "save/save.h"
|
|
||||||
#include "time/time.h"
|
|
||||||
#include "util/math.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
|
|
||||||
errorret_t audioMixerChannelStopStream(audiomixerchannelstate_t *state) {
|
|
||||||
assertNotNull(state, "State cannot be NULL.");
|
|
||||||
|
|
||||||
if(state->stream == NULL) errorOk();
|
|
||||||
|
|
||||||
errorChain(audioStreamDispose(state->stream));
|
|
||||||
state->stream = NULL;
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerChannelFadeTo(
|
|
||||||
audiomixerchannelstate_t *state,
|
|
||||||
const float_t from,
|
|
||||||
const float_t to,
|
|
||||||
const float_t duration,
|
|
||||||
const easingtype_t easing
|
|
||||||
) {
|
|
||||||
assertNotNull(state, "State cannot be NULL.");
|
|
||||||
|
|
||||||
state->fade = from;
|
|
||||||
state->fadeFrom = from;
|
|
||||||
state->fadeTo = to;
|
|
||||||
state->fadeDuration = duration;
|
|
||||||
state->fadeEasing = easing;
|
|
||||||
// A non-positive duration finishes instantly - marked inactive right
|
|
||||||
// away (fadeTime < 0) rather than left at 0 to progress next frame,
|
|
||||||
// since there's nothing left to progress.
|
|
||||||
if(duration <= 0.0f) {
|
|
||||||
state->fade = to;
|
|
||||||
state->fadeTime = -1.0f;
|
|
||||||
} else {
|
|
||||||
state->fadeTime = 0.0f;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool_t audioMixerChannelIsFading(const audiomixerchannelstate_t *state) {
|
|
||||||
assertNotNull(state, "State cannot be NULL.");
|
|
||||||
|
|
||||||
return state->fadeTime >= 0.0f;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerChannelApplyVolume(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
audiomixerchannelstate_t *state
|
|
||||||
) {
|
|
||||||
assertNotNull(state, "State cannot be NULL.");
|
|
||||||
|
|
||||||
if(state->stream == NULL) return;
|
|
||||||
|
|
||||||
// Advances any in-progress fade before it's read below - see
|
|
||||||
// audioMixerChannelFadeTo()'s own comment on fadeTime's meaning.
|
|
||||||
if(state->fadeTime >= 0.0f) {
|
|
||||||
state->fadeTime += TIME.delta;
|
|
||||||
const float_t t = mathClamp(
|
|
||||||
state->fadeTime / state->fadeDuration, 0.0f, 1.0f
|
|
||||||
);
|
|
||||||
state->fade = state->fadeFrom +
|
|
||||||
(state->fadeTo - state->fadeFrom) * easingApply(state->fadeEasing, t);
|
|
||||||
if(state->fadeTime >= state->fadeDuration) {
|
|
||||||
state->fade = state->fadeTo;
|
|
||||||
state->fadeTime = -1.0f;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// state->fade and both SAVE.settings volumes have no setter - written
|
|
||||||
// directly by callers - so this is the only place any of them ever gets
|
|
||||||
// validated, rather than at the point they're set.
|
|
||||||
assertTrue(
|
|
||||||
state->fade >= 0.0f && state->fade <= 1.0f,
|
|
||||||
"Channel fade is out of range."
|
|
||||||
);
|
|
||||||
assertTrue(
|
|
||||||
SAVE.settings.audioChannelVolume[channel] >= 0.0f &&
|
|
||||||
SAVE.settings.audioChannelVolume[channel] <= 1.0f,
|
|
||||||
"Channel volume is out of range."
|
|
||||||
);
|
|
||||||
assertTrue(
|
|
||||||
SAVE.settings.audioMasterVolume >= 0.0f &&
|
|
||||||
SAVE.settings.audioMasterVolume <= 1.0f,
|
|
||||||
"Master volume is out of range."
|
|
||||||
);
|
|
||||||
|
|
||||||
// Final computed volume.
|
|
||||||
float_t volume = (
|
|
||||||
state->baseVolume *
|
|
||||||
state->fade *
|
|
||||||
SAVE.settings.audioChannelVolume[channel] *
|
|
||||||
SAVE.settings.audioMasterVolume
|
|
||||||
);
|
|
||||||
audioStreamSetVolume(state->stream, volume);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioMixerChannelUpdateEarly(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
audiomixerchannelstate_t *state
|
|
||||||
) {
|
|
||||||
assertNotNull(state, "State cannot be NULL.");
|
|
||||||
|
|
||||||
audiomixercommand_t *command = &state->pending;
|
|
||||||
|
|
||||||
if(command->command == AUDIO_MIXER_COMMAND_STOP) {
|
|
||||||
errorChain(audioMixerChannelStopStream(state));
|
|
||||||
command->command = AUDIO_MIXER_COMMAND_NONE;
|
|
||||||
audioMixerChannelApplyVolume(channel, state);
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(
|
|
||||||
command->command != AUDIO_MIXER_COMMAND_PLAY ||
|
|
||||||
command->loadingAsset == NULL
|
|
||||||
) {
|
|
||||||
// A PLAY command with no loadingAsset yet (command->loadingAsset ==
|
|
||||||
// NULL) was queued too late for the audioMixerChannelUpdateLate() that
|
|
||||||
// just ran immediately before this call to have locked it - the only
|
|
||||||
// way that happens is a command queued outside the normal per-frame
|
|
||||||
// cycle, e.g. during engine startup before any
|
|
||||||
// audioMixerChannelUpdateLate() has run yet. Left alone (still
|
|
||||||
// AUDIO_MIXER_COMMAND_PLAY) rather than treated as an error: the very
|
|
||||||
// next audioMixerChannelUpdateLate() will lock it, and the frame after
|
|
||||||
// that will reach here and apply it normally.
|
|
||||||
audioMixerChannelApplyVolume(channel, state);
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blocks here if audioMixerChannelUpdateLate()'s load (kicked off at the
|
|
||||||
// end of the previous frame) hasn't finished yet - see this function's
|
|
||||||
// own doc comment on why that's accepted for now.
|
|
||||||
errorret_t loadRet = assetRequireLoaded(command->loadingAsset);
|
|
||||||
if(errorIsNotOk(loadRet)) {
|
|
||||||
assetUnlockEntry(command->loadingAsset);
|
|
||||||
command->loadingAsset = NULL;
|
|
||||||
command->command = AUDIO_MIXER_COMMAND_NONE;
|
|
||||||
errorChain(loadRet);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorChain(audioMixerChannelStopStream(state));
|
|
||||||
|
|
||||||
audiostream_t *stream = audioAquireStream(command->loadingAsset);
|
|
||||||
assertNotNull(stream, "No free audio stream slots available.");
|
|
||||||
|
|
||||||
errorret_t initRet = audioStreamInit(stream, command->loadingAsset);
|
|
||||||
// The stream holds its own lock on the asset once initialized (or, on
|
|
||||||
// failure, audioStreamInit() has already released it itself) - either
|
|
||||||
// way this call's own lock is no longer needed.
|
|
||||||
assetUnlockEntry(command->loadingAsset);
|
|
||||||
command->loadingAsset = NULL;
|
|
||||||
command->command = AUDIO_MIXER_COMMAND_NONE;
|
|
||||||
errorChain(initRet);
|
|
||||||
|
|
||||||
// Forwards to this channel's own onLoop/onEnd (persistent across every
|
|
||||||
// play on this channel) rather than this one stream instance's own -
|
|
||||||
// see audiomixerchannelstate_t.onLoop's own comment.
|
|
||||||
stream->user = state;
|
|
||||||
stream->onLoop = audioMixerChannelOnStreamLoop;
|
|
||||||
stream->onEnd = audioMixerChannelOnStreamEnd;
|
|
||||||
|
|
||||||
audioStreamSetDirectionality(stream, command->pan);
|
|
||||||
if(command->looping) {
|
|
||||||
audioStreamSetLooping(stream, true);
|
|
||||||
audioStreamSetLoopPoints(stream, command->loopStart, command->loopTo);
|
|
||||||
audioStreamSetLoopLimit(stream, command->loopCount);
|
|
||||||
}
|
|
||||||
audioStreamPlay(stream);
|
|
||||||
|
|
||||||
state->stream = stream;
|
|
||||||
state->baseVolume = command->volume;
|
|
||||||
|
|
||||||
audioMixerChannelApplyVolume(channel, state);
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioMixerChannelUpdateLate(audiomixerchannelstate_t *state) {
|
|
||||||
assertNotNull(state, "State cannot be NULL.");
|
|
||||||
|
|
||||||
audiomixercommand_t *command = &state->pending;
|
|
||||||
|
|
||||||
if(command->command != AUDIO_MIXER_COMMAND_PLAY) errorOk();
|
|
||||||
|
|
||||||
assetloadertype_t assetType = audioStreamAssetTypeForPath(command->file);
|
|
||||||
assertTrue(
|
|
||||||
assetType != ASSET_LOADER_TYPE_NULL, "Unsupported audio file extension."
|
|
||||||
);
|
|
||||||
|
|
||||||
// Begins loading now - kicked off at the end of this frame so it has
|
|
||||||
// until the start of the next (audioMixerChannelUpdateEarly()) to finish
|
|
||||||
// before that has to block on it.
|
|
||||||
command->loadingAsset = assetLock(command->file, assetType, NULL);
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerChannelOnStreamLoop(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
audiomixerchannelstate_t *state = (audiomixerchannelstate_t *) stream->user;
|
|
||||||
if(state->onLoop != NULL) state->onLoop(state);
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioMixerChannelOnStreamEnd(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
audiomixerchannelstate_t *state = (audiomixerchannelstate_t *) stream->user;
|
|
||||||
if(state->onEnd != NULL) state->onEnd(state);
|
|
||||||
}
|
|
||||||
@@ -1,242 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "dusk.h"
|
|
||||||
#include "error/error.h"
|
|
||||||
#include "animation/easing.h"
|
|
||||||
|
|
||||||
// Forward-declared rather than including asset/asset.h - this header only
|
|
||||||
// ever needs a pointer to it, and pulling in the full asset module here
|
|
||||||
// creates a real include cycle for anything that reaches this header via
|
|
||||||
// asset/loader/cutscene/assetcutsceneloader.h (asset.h -> ... ->
|
|
||||||
// assetloader.h -> assetcutsceneloader.h -> cutscene.h -> cutsceneitem.h
|
|
||||||
// -> the audio cutscene items -> this header -> asset/asset.h again,
|
|
||||||
// mid-parse). audiomixerchannel.c itself still includes the full header.
|
|
||||||
typedef struct assetentry_s assetentry_t;
|
|
||||||
|
|
||||||
typedef struct audiostream_s audiostream_t;
|
|
||||||
|
|
||||||
#define AUDIO_PATH_MAX 256
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_MIXER_CHANNEL_BGM_0,
|
|
||||||
AUDIO_MIXER_CHANNEL_VOICE_0,
|
|
||||||
AUDIO_MIXER_CHANNEL_VOICE_1,
|
|
||||||
AUDIO_MIXER_CHANNEL_SFX_0,
|
|
||||||
AUDIO_MIXER_CHANNEL_SFX_1,
|
|
||||||
AUDIO_MIXER_CHANNEL_SFX_2,
|
|
||||||
AUDIO_MIXER_CHANNEL_SFX_3,
|
|
||||||
AUDIO_MIXER_CHANNEL_COUNT
|
|
||||||
} audiomixerchannel_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_MIXER_COMMAND_NONE,
|
|
||||||
AUDIO_MIXER_COMMAND_PLAY,
|
|
||||||
AUDIO_MIXER_COMMAND_STOP
|
|
||||||
} audiomixercommandtype_t;
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
// What audioMixerChannelUpdateEarly() should do to this channel at the
|
|
||||||
// start of the next frame - AUDIO_MIXER_COMMAND_NONE if nothing's
|
|
||||||
// queued. Set by audioMixerPlay()/audioMixerPlayLooped()/
|
|
||||||
// audioMixerStop(); queuing a new command on a channel replaces, rather
|
|
||||||
// than stacks on top of, whatever was already queued for it this frame -
|
|
||||||
// only the most recent survives.
|
|
||||||
audiomixercommandtype_t command;
|
|
||||||
|
|
||||||
// AUDIO_MIXER_COMMAND_PLAY only, below.
|
|
||||||
char_t file[AUDIO_PATH_MAX];
|
|
||||||
float_t volume;
|
|
||||||
float_t pan;
|
|
||||||
bool_t looping;
|
|
||||||
uint8_t loopCount;
|
|
||||||
float_t loopStart;
|
|
||||||
float_t loopTo;
|
|
||||||
|
|
||||||
// Set by audioMixerChannelUpdateLate() (the end of the frame this PLAY
|
|
||||||
// command was queued on), once it locks the requested file and kicks off
|
|
||||||
// its load. audioMixerChannelUpdateEarly() (the start of the next frame)
|
|
||||||
// blocks on this being fully loaded before actually starting playback -
|
|
||||||
// see its own comment. NULL except in that in-between window.
|
|
||||||
assetentry_t *loadingAsset;
|
|
||||||
} audiomixercommand_t;
|
|
||||||
|
|
||||||
typedef struct audiomixerchannelstate_s audiomixerchannelstate_t;
|
|
||||||
|
|
||||||
typedef struct audiomixerchannelstate_s {
|
|
||||||
// Queued action for the next audioMixerChannelUpdateEarly() to apply.
|
|
||||||
audiomixercommand_t pending;
|
|
||||||
|
|
||||||
// This channel's currently playing stream, or NULL if nothing is -
|
|
||||||
// acquired from AUDIO.streams by audioMixerChannelUpdateEarly() when it
|
|
||||||
// applies an AUDIO_MIXER_COMMAND_PLAY, disposed the same way on
|
|
||||||
// AUDIO_MIXER_COMMAND_STOP or before a new AUDIO_MIXER_COMMAND_PLAY
|
|
||||||
// replaces it.
|
|
||||||
audiostream_t *stream;
|
|
||||||
|
|
||||||
// The per-sound volume `stream` was last started with (the `volume`
|
|
||||||
// argument to whichever audioMixerPlay()/audioMixerPlayLooped() call
|
|
||||||
// started it) - combined with this channel's fade, its own volume
|
|
||||||
// (SAVE.settings.audioChannelVolume) and the mixer's master volume
|
|
||||||
// (SAVE.settings.audioMasterVolume), every frame, to get the volume
|
|
||||||
// actually passed to audioStreamSetVolume(). Meaningless while `stream`
|
|
||||||
// is NULL.
|
|
||||||
float_t baseVolume;
|
|
||||||
|
|
||||||
// This channel's own fade multiplier, from 0.0 (fully faded out) to 1.0
|
|
||||||
// (no fade applied, the default) - transient runtime state, unlike the
|
|
||||||
// channel/master volumes below (which are persisted user preferences).
|
|
||||||
// No setter - write it directly; audioMixerChannelApplyVolume() asserts
|
|
||||||
// it's in range the next time it reads it, rather than validating at the
|
|
||||||
// point it's set.
|
|
||||||
float_t fade;
|
|
||||||
|
|
||||||
// Fade transition state, set by audioMixerChannelFadeTo() and advanced
|
|
||||||
// every frame by audioMixerChannelApplyVolume(), before it reads `fade`
|
|
||||||
// to compute the mixed volume. fadeTime < 0 means no fade is in progress
|
|
||||||
// (audioMixerChannelIsFading() is just `fadeTime >= 0`) - audioMixerInit()
|
|
||||||
// explicitly sets this to -1.0f, since zero-initializing it would
|
|
||||||
// otherwise look like an active fade at time 0.
|
|
||||||
float_t fadeFrom;
|
|
||||||
float_t fadeTo;
|
|
||||||
float_t fadeDuration;
|
|
||||||
float_t fadeTime;
|
|
||||||
easingtype_t fadeEasing;
|
|
||||||
|
|
||||||
// Arbitrary caller data, handed back as-is to onLoop/onEnd below - never
|
|
||||||
// read or written by the mixer itself. NULL by default.
|
|
||||||
void *user;
|
|
||||||
|
|
||||||
// Fired (from the main thread - safe to do arbitrary work, same
|
|
||||||
// guarantee as audiostream_t's own onLoop/onEnd) whenever this channel's
|
|
||||||
// currently playing stream loops, or reaches its natural end (including
|
|
||||||
// hitting its loop limit - see audioStreamSetLoopLimit()) and stops.
|
|
||||||
// Wired onto every stream this channel starts via
|
|
||||||
// audioMixerChannelOnStreamLoop()/OnStreamEnd() - not called directly by
|
|
||||||
// anything else. No setter - write these fields directly; NULL (the
|
|
||||||
// default) means not notified. Unlike `stream`/`pending`, these persist
|
|
||||||
// across every play on this channel, not just one.
|
|
||||||
void (*onLoop)(audiomixerchannelstate_t *state);
|
|
||||||
void (*onEnd)(audiomixerchannelstate_t *state);
|
|
||||||
} audiomixerchannelstate_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stops and disposes the given channel's currently playing stream, if any -
|
|
||||||
* a safe no-op if the channel is already idle. Shared by
|
|
||||||
* audioMixerChannelUpdateEarly() (AUDIO_MIXER_COMMAND_STOP, and replacing a
|
|
||||||
* channel's stream before a new AUDIO_MIXER_COMMAND_PLAY starts) and
|
|
||||||
* audioMixerDispose().
|
|
||||||
*
|
|
||||||
* @param state The channel state to stop.
|
|
||||||
*/
|
|
||||||
errorret_t audioMixerChannelStopStream(audiomixerchannelstate_t *state);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Computes the given channel's actual playback volume - its currently
|
|
||||||
* playing sound's own volume (baseVolume), this channel's fade, this
|
|
||||||
* channel's own volume (SAVE.settings.audioChannelVolume[channel]) and the
|
|
||||||
* mixer's master volume (SAVE.settings.audioMasterVolume) - and applies it
|
|
||||||
* via audioStreamSetVolume(). Asserts fade and both save-settings volumes
|
|
||||||
* are each within [0.0, 1.0] - the only validation any of them ever gets,
|
|
||||||
* since none of them have a setter. A safe no-op if the channel isn't
|
|
||||||
* playing anything. Called every audioMixerChannelUpdateEarly(), not just
|
|
||||||
* when a PLAY command starts a new stream - see its own comment.
|
|
||||||
*
|
|
||||||
* @param channel Which channel `state` is, to index
|
|
||||||
* SAVE.settings.audioChannelVolume with.
|
|
||||||
* @param state The channel state to update.
|
|
||||||
*/
|
|
||||||
void audioMixerChannelApplyVolume(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
audiomixerchannelstate_t *state
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Starts fading the given channel's `fade` multiplier from `from` to `to`
|
|
||||||
* over `duration` seconds, eased by `easing` - snaps `fade` to `from`
|
|
||||||
* immediately, then audioMixerChannelApplyVolume() advances it every frame
|
|
||||||
* from here on. A `duration` of 0 or less snaps straight to `to` and marks
|
|
||||||
* the fade as already finished (audioMixerChannelIsFading() returns
|
|
||||||
* false on the very next call).
|
|
||||||
*
|
|
||||||
* @param state The channel state to fade.
|
|
||||||
* @param from Starting fade value, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
* @param to Ending fade value, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
* @param duration How long the fade takes, in seconds.
|
|
||||||
* @param easing Easing curve to apply to the fade's progress.
|
|
||||||
*/
|
|
||||||
void audioMixerChannelFadeTo(
|
|
||||||
audiomixerchannelstate_t *state,
|
|
||||||
const float_t from,
|
|
||||||
const float_t to,
|
|
||||||
const float_t duration,
|
|
||||||
const easingtype_t easing
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether the given channel currently has a fade in progress (started via
|
|
||||||
* audioMixerChannelFadeTo() and not yet finished).
|
|
||||||
*
|
|
||||||
* @param state The channel state to check.
|
|
||||||
* @return true if a fade is still in progress.
|
|
||||||
*/
|
|
||||||
bool_t audioMixerChannelIsFading(const audiomixerchannelstate_t *state);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates a single mixer channel, called before rendering (the start of
|
|
||||||
* the frame): applies whatever command (play, stop - including everything
|
|
||||||
* a play carries, pan/looping) audioMixerChannelUpdateLate() queued for
|
|
||||||
* loading at the end of the previous frame. If that load hasn't finished
|
|
||||||
* yet, this blocks (via assetRequireLoaded()) until it has - a deliberate
|
|
||||||
* stall for now rather than skipping a frame, since there's currently no
|
|
||||||
* way to only partially apply a channel's command. Also recomputes and
|
|
||||||
* reapplies this channel's mixed volume (see
|
|
||||||
* audioMixerChannelApplyVolume()) every time, regardless of whether a
|
|
||||||
* command was queued this frame, so a live change to this channel's fade,
|
|
||||||
* its own volume, or the master volume takes effect on whatever's already
|
|
||||||
* playing too.
|
|
||||||
*
|
|
||||||
* @param channel Which channel `state` is - see
|
|
||||||
* audioMixerChannelApplyVolume()'s own comment.
|
|
||||||
* @param state The channel state to update.
|
|
||||||
*/
|
|
||||||
errorret_t audioMixerChannelUpdateEarly(
|
|
||||||
const audiomixerchannel_t channel,
|
|
||||||
audiomixerchannelstate_t *state
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates a single mixer channel, called at the end of each frame, once
|
|
||||||
* every other system has had a chance to queue a command via
|
|
||||||
* audioMixerPlay()/audioMixerPlayLooped()/audioMixerStop(). For a queued
|
|
||||||
* AUDIO_MIXER_COMMAND_PLAY, locks its file and begins loading it (see
|
|
||||||
* assetLock()) - giving it from now until the next
|
|
||||||
* audioMixerChannelUpdateEarly() to finish before that has to block on it.
|
|
||||||
* Actually starting/stopping playback happens there, not here.
|
|
||||||
*
|
|
||||||
* @param state The channel state to update.
|
|
||||||
*/
|
|
||||||
errorret_t audioMixerChannelUpdateLate(audiomixerchannelstate_t *state);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Trampoline wired onto every stream a channel starts (as that stream's
|
|
||||||
* onLoop) - forwards to the channel's own onLoop (see
|
|
||||||
* audiomixerchannelstate_t.onLoop's own comment) via stream->user, which
|
|
||||||
* audioMixerChannelUpdateEarly() points at the channel's own state.
|
|
||||||
*
|
|
||||||
* @param stream The stream that looped.
|
|
||||||
*/
|
|
||||||
void audioMixerChannelOnStreamLoop(audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Same as audioMixerChannelOnStreamLoop() but wired onto onEnd, forwarding
|
|
||||||
* to the channel's own onEnd.
|
|
||||||
*
|
|
||||||
* @param stream The stream that ended.
|
|
||||||
*/
|
|
||||||
void audioMixerChannelOnStreamEnd(audiostream_t *stream);
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
# Copyright (c) 2026 Dominic Masters
|
|
||||||
#
|
|
||||||
# This software is released under the MIT License.
|
|
||||||
# https://opensource.org/licenses/MIT
|
|
||||||
|
|
||||||
# Sources
|
|
||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
|
||||||
PUBLIC
|
|
||||||
audiostream.c
|
|
||||||
audiostreampcm.c
|
|
||||||
audiostreammp3.c
|
|
||||||
audiostreamtype.c
|
|
||||||
)
|
|
||||||
@@ -1,312 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "audiostream.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "util/math.h"
|
|
||||||
|
|
||||||
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertNotNull(asset, "Asset cannot be NULL.");
|
|
||||||
assertTrue(
|
|
||||||
asset->state == ASSET_ENTRY_STATE_LOADED,
|
|
||||||
"Asset must be loaded before it can back an audio stream."
|
|
||||||
);
|
|
||||||
// A caller passing an asset type that can't back an audio stream is a
|
|
||||||
// programmer error, not something that can happen from untrusted data, so
|
|
||||||
// this is an assert rather than an errorThrow (see
|
|
||||||
// feedback_assert_vs_error convention).
|
|
||||||
assertTrue(
|
|
||||||
audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
|
|
||||||
"Unsupported asset type for an audio stream."
|
|
||||||
);
|
|
||||||
|
|
||||||
stream->state = 0;
|
|
||||||
stream->volume = 1.0f;
|
|
||||||
stream->directionality = AUDIO_STREAM_CENTER;
|
|
||||||
stream->loopStart = -1;
|
|
||||||
stream->loopTo = 0;
|
|
||||||
stream->duration = 0;
|
|
||||||
stream->startFrame = 0;
|
|
||||||
stream->seeking = false;
|
|
||||||
stream->user = NULL;
|
|
||||||
stream->onLoop = NULL;
|
|
||||||
stream->onEnd = NULL;
|
|
||||||
stream->loopCount = 0;
|
|
||||||
stream->lastLoopCount = 0;
|
|
||||||
stream->loopLimit = 0;
|
|
||||||
stream->loopRestartCount = 0;
|
|
||||||
|
|
||||||
// Locked for as long as the stream is in use (see audiostream_t.asset's
|
|
||||||
// own comment) - released in audioStreamDispose().
|
|
||||||
stream->asset = asset;
|
|
||||||
assetEntryLock(asset);
|
|
||||||
|
|
||||||
// Type-specific setup (audioStreamPcmInit() / audioStreamMp3Init())
|
|
||||||
// determines stream->type, sets stream->sampleRate/channels, and asks
|
|
||||||
// the platform implementation to set up its state.
|
|
||||||
errorret_t ret = asset->type == ASSET_LOADER_TYPE_MP3
|
|
||||||
? audioStreamMp3Init(stream)
|
|
||||||
: audioStreamPcmInit(stream);
|
|
||||||
if(errorIsNotOk(ret)) {
|
|
||||||
assetEntryUnlock(asset);
|
|
||||||
stream->asset = NULL;
|
|
||||||
errorChain(ret);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t audioStreamGetTotalFrames(const audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
return stream->type == AUDIO_STREAM_TYPE_MP3
|
|
||||||
? audioStreamMp3GetTotalFrames(stream)
|
|
||||||
: audioStreamPcmGetTotalFrames(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamSeek(audiostream_t *stream, const size_t frame) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
errorChain(
|
|
||||||
stream->type == AUDIO_STREAM_TYPE_MP3
|
|
||||||
? audioStreamMp3Seek(stream, frame)
|
|
||||||
: audioStreamPcmSeek(stream, frame)
|
|
||||||
);
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamRead(
|
|
||||||
audiostream_t *stream,
|
|
||||||
int16_t *buffer,
|
|
||||||
const size_t frameCount,
|
|
||||||
size_t *outFramesRead
|
|
||||||
) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
errorChain(
|
|
||||||
stream->type == AUDIO_STREAM_TYPE_MP3
|
|
||||||
? audioStreamMp3Read(stream, buffer, frameCount, outFramesRead)
|
|
||||||
: audioStreamPcmRead(stream, buffer, frameCount, outFramesRead)
|
|
||||||
);
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamPlay(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
stream->state |= AUDIO_STREAM_STATE_PLAYING;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamPause(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
stream->state &= ~AUDIO_STREAM_STATE_PLAYING;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamSetPosition(audiostream_t *stream, const float_t position) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
// Wrap into [0, duration).
|
|
||||||
float_t t = position;
|
|
||||||
while(t < 0) t += stream->duration;
|
|
||||||
while(t >= stream->duration) t -= stream->duration;
|
|
||||||
|
|
||||||
stream->startFrame = (size_t) (t * stream->sampleRate);
|
|
||||||
stream->seeking = true;
|
|
||||||
|
|
||||||
// Force the next audioStreamUpdate() to re-buffer from startFrame instead
|
|
||||||
// of continuing whatever was already buffered - see the platform Buffer()
|
|
||||||
// implementations for how each one applies startFrame; PSP is the one
|
|
||||||
// exception (see audioStreamSetPosition's own doc comment).
|
|
||||||
stream->state &= ~AUDIO_STREAM_STATE_BUFFERED;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamSetLoopPoints(
|
|
||||||
audiostream_t *stream,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(
|
|
||||||
loopStart < 0 || loopTo < loopStart,
|
|
||||||
"loopTo must be before loopStart."
|
|
||||||
);
|
|
||||||
|
|
||||||
stream->loopStart = loopStart;
|
|
||||||
stream->loopTo = loopTo;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamGetPanFactors(
|
|
||||||
const audiostream_t *stream,
|
|
||||||
float_t *outLeft,
|
|
||||||
float_t *outRight
|
|
||||||
) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertNotNull(outLeft, "outLeft cannot be NULL.");
|
|
||||||
assertNotNull(outRight, "outRight cannot be NULL.");
|
|
||||||
|
|
||||||
// directionality is already a pan factor in AUDIO_STREAM_LEFT..RIGHT
|
|
||||||
// (-1.0..1.0) - assertTrue'd here rather than clamped, since a caller
|
|
||||||
// passing something outside that range is a programmer error (see
|
|
||||||
// audioStreamSetDirectionality()'s own assert).
|
|
||||||
const float_t pan = stream->directionality;
|
|
||||||
|
|
||||||
*outLeft = pan > 0 ? (1.0f - pan) : 1.0f;
|
|
||||||
*outRight = pan < 0 ? (1.0f + pan) : 1.0f;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t audioStreamComputeEndFrame(
|
|
||||||
const audiostream_t *stream,
|
|
||||||
const size_t startFrame,
|
|
||||||
const size_t totalFrames
|
|
||||||
) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
size_t endFrame = totalFrames;
|
|
||||||
if((stream->state & AUDIO_STREAM_STATE_LOOPING) && stream->loopStart >= 0) {
|
|
||||||
endFrame = mathMin(
|
|
||||||
(size_t) (stream->loopStart * stream->sampleRate), totalFrames
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if(startFrame >= endFrame) endFrame = totalFrames;
|
|
||||||
|
|
||||||
return endFrame;
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamSetVolume(audiostream_t *stream, const float_t volume) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(volume >= 0.0f && volume <= 1.0f, "Volume is out of range.");
|
|
||||||
stream->volume = volume;
|
|
||||||
// TODO: Do I need to update the device output? PSP may require this
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamSetDirectionality(
|
|
||||||
audiostream_t *stream,
|
|
||||||
const float_t directionality
|
|
||||||
) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(
|
|
||||||
directionality >= AUDIO_STREAM_LEFT && directionality <= AUDIO_STREAM_RIGHT,
|
|
||||||
"Directionality is out of range."
|
|
||||||
);
|
|
||||||
stream->directionality = directionality;
|
|
||||||
// TODO: Need to update internal decoder?
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamSetLooping(audiostream_t *stream, const bool_t looping) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
if(looping) {
|
|
||||||
stream->state |= AUDIO_STREAM_STATE_LOOPING;
|
|
||||||
} else {
|
|
||||||
stream->state &= ~AUDIO_STREAM_STATE_LOOPING;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void audioStreamSetLoopLimit(audiostream_t *stream, const uint32_t loopLimit) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
stream->loopLimit = loopLimit;
|
|
||||||
stream->loopRestartCount = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamUpdate(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
if(stream->type == AUDIO_STREAM_TYPE_NULL) {
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Some platforms (PSP) loop entirely on their own background thread for
|
|
||||||
// gaplessness and can only safely notify onLoop by incrementing this
|
|
||||||
// counter from there, rather than calling onLoop directly off the main
|
|
||||||
// thread - see loopCount's own comment. Firing it here, unconditionally,
|
|
||||||
// catches up to the latest count in one call even if multiple loops
|
|
||||||
// happened between two Update() calls.
|
|
||||||
if(stream->loopCount != stream->lastLoopCount) {
|
|
||||||
stream->lastLoopCount = stream->loopCount;
|
|
||||||
|
|
||||||
if(stream->onLoop != NULL) {
|
|
||||||
stream->onLoop(stream);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Once streamed (rather than fully in-memory) sources exist, this is
|
|
||||||
// where new data would be decoded/read in and re-buffered as playback
|
|
||||||
// consumes it.
|
|
||||||
// Checked in this order (finished-check before needs-buffering) so that a
|
|
||||||
// loop restart falls straight through into re-buffering within this same
|
|
||||||
// call, instead of leaving BUFFERED cleared for the caller to notice and
|
|
||||||
// act on next frame - that extra frame of latency was audible as a gap
|
|
||||||
// at every loop boundary.
|
|
||||||
if(
|
|
||||||
(stream->state & AUDIO_STREAM_STATE_PLAYING) &&
|
|
||||||
(stream->state & AUDIO_STREAM_STATE_BUFFERED) &&
|
|
||||||
audioStreamPlatformIsFinished(stream)
|
|
||||||
) {
|
|
||||||
// A limit of 0 means unlimited; otherwise this pass's restart only goes
|
|
||||||
// ahead while fewer than loopLimit restarts have already happened -
|
|
||||||
// once it's reached, fall through to the same stop/onEnd path as a
|
|
||||||
// non-looping stream instead of restarting again.
|
|
||||||
const bool_t loopLimitReached = stream->loopLimit > 0 &&
|
|
||||||
stream->loopRestartCount >= stream->loopLimit;
|
|
||||||
|
|
||||||
if((stream->state & AUDIO_STREAM_STATE_LOOPING) && !loopLimitReached) {
|
|
||||||
stream->state &= ~AUDIO_STREAM_STATE_BUFFERED;
|
|
||||||
stream->loopRestartCount++;
|
|
||||||
|
|
||||||
// Resume from loopTo rather than the very start of the buffer - only
|
|
||||||
// matters for platforms that reach this generic restart path at all
|
|
||||||
// (Linux and Dolphin, both of which re-buffer per pass and report
|
|
||||||
// "finished" at every loop boundary); PSP loops entirely on its own
|
|
||||||
// read-ahead ring instead (see loopRestartCount's own comment).
|
|
||||||
stream->startFrame = (size_t) (stream->loopTo * stream->sampleRate);
|
|
||||||
|
|
||||||
if(stream->onLoop != NULL) {
|
|
||||||
stream->onLoop(stream);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
stream->state &=
|
|
||||||
~(AUDIO_STREAM_STATE_PLAYING | AUDIO_STREAM_STATE_BUFFERED);
|
|
||||||
|
|
||||||
if(stream->onEnd != NULL) {
|
|
||||||
stream->onEnd(stream);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if(
|
|
||||||
(stream->state & AUDIO_STREAM_STATE_PLAYING) &&
|
|
||||||
!(stream->state & AUDIO_STREAM_STATE_BUFFERED)
|
|
||||||
) {
|
|
||||||
errorChain(audioStreamPlatformBuffer(stream));
|
|
||||||
stream->state |= AUDIO_STREAM_STATE_BUFFERED;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamDispose(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
|
|
||||||
if(stream->type != AUDIO_STREAM_TYPE_NULL) {
|
|
||||||
errorChain(audioStreamPlatformDispose(stream));
|
|
||||||
}
|
|
||||||
|
|
||||||
if(stream->type == AUDIO_STREAM_TYPE_PCM) {
|
|
||||||
errorChain(audioStreamPcmDispose(stream));
|
|
||||||
} else if(stream->type == AUDIO_STREAM_TYPE_MP3) {
|
|
||||||
errorChain(audioStreamMp3Dispose(stream));
|
|
||||||
}
|
|
||||||
|
|
||||||
if(stream->asset != NULL) {
|
|
||||||
assetEntryUnlock(stream->asset);
|
|
||||||
stream->asset = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
stream->type = AUDIO_STREAM_TYPE_NULL;
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,360 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "audio/stream/audiostreamtype.h"
|
|
||||||
#include "audio/stream/audiostreampcm.h"
|
|
||||||
#include "audio/stream/audiostreammp3.h"
|
|
||||||
#include "audio/audiostreamplatform.h"
|
|
||||||
#include "asset/loader/assetentry.h"
|
|
||||||
|
|
||||||
#ifndef audioStreamPlatformInit
|
|
||||||
#error "audioStreamPlatformInit is not defined"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef audioStreamPlatformDispose
|
|
||||||
#error "audioStreamPlatformDispose is not defined"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef audioStreamPlatformBuffer
|
|
||||||
#error "audioStreamPlatformBuffer is not defined"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef audioStreamPlatformIsFinished
|
|
||||||
#error "audioStreamPlatformIsFinished is not defined"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define AUDIO_STREAMS_MAX 8
|
|
||||||
#define AUDIO_STREAM_STATE_PLAYING (1 << 0)
|
|
||||||
#define AUDIO_STREAM_STATE_LOOPING (1 << 1)
|
|
||||||
#define AUDIO_STREAM_STATE_BUFFERED (1 << 2)
|
|
||||||
#define AUDIO_STREAM_CENTER 0.0f
|
|
||||||
#define AUDIO_STREAM_LEFT -1.0f
|
|
||||||
#define AUDIO_STREAM_RIGHT 1.0f
|
|
||||||
|
|
||||||
typedef struct audiostream_s audiostream_t;
|
|
||||||
|
|
||||||
typedef struct audiostream_s {
|
|
||||||
// Used for aquiring new data.
|
|
||||||
audistreamtype_t type;
|
|
||||||
|
|
||||||
// What state the stream is in. volatile: PSP's output thread reads
|
|
||||||
// AUDIO_STREAM_STATE_PLAYING directly to honor a pause promptly instead
|
|
||||||
// of only reacting once the main thread's own per-frame gate notices -
|
|
||||||
// see audioStreamPSPThreadFeed()'s own comment.
|
|
||||||
volatile uint8_t state;
|
|
||||||
|
|
||||||
// The asset backing this stream's data (e.g. a WAV file) - determines
|
|
||||||
// `type` (see audioStreamInit()) and is read from on demand by the
|
|
||||||
// type-specific module (e.g. audiostreampcm.h) rather than ever being
|
|
||||||
// fully decoded into memory up front. The stream holds its own lock on
|
|
||||||
// this entry (assetEntryLock()/assetEntryUnlock()) for as long as it's
|
|
||||||
// in use, independent of whatever lock(s) the caller that requested
|
|
||||||
// playback may also be holding.
|
|
||||||
assetentry_t *asset;
|
|
||||||
|
|
||||||
// Loudness, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
float_t volume;
|
|
||||||
|
|
||||||
// In stereo space, where do we send the audio - from AUDIO_STREAM_LEFT
|
|
||||||
// (-1.0) to AUDIO_STREAM_RIGHT (1.0), AUDIO_STREAM_CENTER (0.0) by
|
|
||||||
// default.
|
|
||||||
// TODO: Can we use a 3D vector + Pro Logic II?
|
|
||||||
float_t directionality;
|
|
||||||
|
|
||||||
// In seconds, where the loop segment ends and playback jumps back to
|
|
||||||
// loopTo - -1 (the default) means "at the end of the stream", i.e. loop
|
|
||||||
// the whole buffer. Set via audioStreamSetLoopPoints().
|
|
||||||
float_t loopStart;
|
|
||||||
|
|
||||||
// In seconds, where a loop jumps back to once it reaches loopStart.
|
|
||||||
// Defaults to 0 (start of stream). Set via audioStreamSetLoopPoints().
|
|
||||||
float_t loopTo;
|
|
||||||
|
|
||||||
// Cached duration of the stream in seconds.
|
|
||||||
float_t duration;
|
|
||||||
|
|
||||||
// Frame offset the next platform Buffer() call should start playback
|
|
||||||
// from - set by audioStreamSetPosition() (an explicit seek) and by
|
|
||||||
// audioStreamUpdate() itself (to loopTo's frame offset, for platforms
|
|
||||||
// that re-enter Buffer() on every loop restart rather than looping
|
|
||||||
// natively). Each platform's Buffer()-invoking entry point must read and
|
|
||||||
// reset this to 0 synchronously, in the same call that decided to
|
|
||||||
// (re)buffer - not later/asynchronously (e.g. from a feeder thread),
|
|
||||||
// since audioStreamUpdate() may already have moved on to something else
|
|
||||||
// that touches this field by the time an async reader gets to it.
|
|
||||||
size_t startFrame;
|
|
||||||
|
|
||||||
// True when startFrame came from an explicit audioStreamSetPosition()
|
|
||||||
// seek rather than a natural loop restart. Platforms whose Buffer() call
|
|
||||||
// can leave previously-queued audio still playing underneath the new
|
|
||||||
// pass (currently just Linux's SDL queue, kept deliberately overlapping
|
|
||||||
// across a loop restart to avoid a gap) need this to tell "jump now,
|
|
||||||
// discarding whatever's still playing" (seek) apart from "let the old
|
|
||||||
// tail keep playing while the new pass queues underneath it" (loop
|
|
||||||
// restart) - both look identical as just "a pending startFrame"
|
|
||||||
// otherwise. Consumed (reset to false) the same way as startFrame.
|
|
||||||
bool_t seeking;
|
|
||||||
|
|
||||||
// Callbacks
|
|
||||||
void *user;
|
|
||||||
void (*onLoop)(audiostream_t *stream);
|
|
||||||
void (*onEnd)(audiostream_t *stream);
|
|
||||||
|
|
||||||
// Incremented by platform code (from whatever thread/context it runs in)
|
|
||||||
// each time a loop happens, instead of calling onLoop directly - onLoop
|
|
||||||
// may do arbitrary, possibly-slow work (console printing, game logic),
|
|
||||||
// which is only safe to run from the main thread inside audioStreamUpdate().
|
|
||||||
// Calling it straight from a real-time audio thread risks starving the
|
|
||||||
// hardware buffer if it takes too long - confirmed as the real cause of
|
|
||||||
// a loud crackle on PSP once its feeder thread called onLoop inline.
|
|
||||||
volatile uint32_t loopCount;
|
|
||||||
|
|
||||||
// audioStreamUpdate()'s own record of the last loopCount it fired
|
|
||||||
// onLoop for - only ever touched from the main thread.
|
|
||||||
uint32_t lastLoopCount;
|
|
||||||
|
|
||||||
// Maximum number of times this stream is allowed to loop before stopping
|
|
||||||
// (firing onEnd) instead of restarting again - 0 (the default) means loop
|
|
||||||
// forever. Has no effect unless looping is also enabled via
|
|
||||||
// audioStreamSetLooping(). Set via audioStreamSetLoopLimit().
|
|
||||||
uint32_t loopLimit;
|
|
||||||
|
|
||||||
// How many loop restarts this stream has already committed to - compared
|
|
||||||
// against loopLimit each time a restart is considered, then incremented
|
|
||||||
// if it goes ahead; reset to 0 by audioStreamSetLoopLimit(). Distinct
|
|
||||||
// from loopCount (which tracks when a loop becomes audible, purely for
|
|
||||||
// onLoop notification, and is PSP-only) - this counts decided restarts,
|
|
||||||
// main-thread-only on every platform (PSP decides whether to loop from
|
|
||||||
// its own read-ahead ring, itself driven from the main thread via
|
|
||||||
// audioStreamPSPIsFinished() - see its own comment).
|
|
||||||
uint32_t loopRestartCount;
|
|
||||||
|
|
||||||
// PCM format of the stream's decoded output - read identically by every
|
|
||||||
// platform backend regardless of stream type (PCM decodes straight
|
|
||||||
// through; MP3 decodes to this same format), so it lives here rather
|
|
||||||
// than duplicated in both audiostreampcm_t and audiostreammp3_t. Set by
|
|
||||||
// whichever type-specific Init function runs (audioStreamPcmInit() /
|
|
||||||
// audioStreamMp3Init()).
|
|
||||||
uint32_t sampleRate;
|
|
||||||
uint8_t channels;
|
|
||||||
|
|
||||||
// Stream type specific data.
|
|
||||||
union {
|
|
||||||
audiostreampcm_t pcm;
|
|
||||||
audiostreammp3_t mp3;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Platform-specific playback state (e.g. SDL2 device, PSP channel, ASND
|
|
||||||
// voice). Defined by each platform's audiostreamplatform.h.
|
|
||||||
audiostreamplatform_t platform;
|
|
||||||
} audiostream_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes an audio stream to play the given asset, determining the
|
|
||||||
* stream's type from the asset's loader type (e.g. a WAV asset becomes an
|
|
||||||
* AUDIO_STREAM_TYPE_PCM stream) and dispatching to that type's own setup
|
|
||||||
* (e.g. audioStreamPcmInit()). Does not begin playback; call
|
|
||||||
* audioStreamPlay() once this returns.
|
|
||||||
*
|
|
||||||
* The stream takes its own lock on `asset` (see audiostream_t.asset's own
|
|
||||||
* comment), released by audioStreamDispose() - the asset must already be
|
|
||||||
* loaded (ASSET_ENTRY_STATE_LOADED) when this is called.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to initialize.
|
|
||||||
* @param asset The loaded asset to play - its type must be one this
|
|
||||||
* function supports (ASSET_LOADER_TYPE_WAV or
|
|
||||||
* ASSET_LOADER_TYPE_MP3).
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the total number of decoded PCM frames (one sample per channel)
|
|
||||||
* available in the stream's underlying data, regardless of its type -
|
|
||||||
* dispatches to audioStreamPcmGetTotalFrames() or
|
|
||||||
* audioStreamMp3GetTotalFrames(). Platform backends should use this rather
|
|
||||||
* than a type-specific function directly, so they don't need to know or
|
|
||||||
* care which type they're driving.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to query.
|
|
||||||
* @return The total number of frames available.
|
|
||||||
*/
|
|
||||||
size_t audioStreamGetTotalFrames(const audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Seeks the stream's decode position to the given frame offset, regardless
|
|
||||||
* of its type - dispatches to audioStreamPcmSeek() or audioStreamMp3Seek().
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to seek.
|
|
||||||
* @param frame Frame offset to seek to, relative to the start of the
|
|
||||||
* stream's decoded data.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamSeek(audiostream_t *stream, const size_t frame);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads up to frameCount frames of decoded PCM sample data from the
|
|
||||||
* stream's current position, regardless of its type - dispatches to
|
|
||||||
* audioStreamPcmRead() or audioStreamMp3Read(). See either for the exact
|
|
||||||
* short-read-at-end-of-stream contract, which is identical for both.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to read from.
|
|
||||||
* @param buffer Destination buffer, sized for at least frameCount frames.
|
|
||||||
* @param frameCount Maximum number of frames to read.
|
|
||||||
* @param outFramesRead Set to the number of frames actually read.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamRead(
|
|
||||||
audiostream_t *stream,
|
|
||||||
int16_t *buffer,
|
|
||||||
const size_t frameCount,
|
|
||||||
size_t *outFramesRead
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Begins or resumes playback of the given audio stream.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to play.
|
|
||||||
*/
|
|
||||||
void audioStreamPlay(audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pauses playback of the given audio stream. Playback position is retained,
|
|
||||||
* so audioStreamPlay() resumes from the same point.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to pause.
|
|
||||||
*/
|
|
||||||
void audioStreamPause(audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Seeks the given audio stream to the given position, in seconds, wrapping
|
|
||||||
* into range if the position is outside [0, duration). Takes effect on the
|
|
||||||
* next audioStreamUpdate() call for platforms that re-buffer per frame
|
|
||||||
* (e.g. Linux); on PSP, which manages an entire playback pass on its own
|
|
||||||
* feeder thread once started, a seek only takes effect the next time the
|
|
||||||
* stream begins playing from a stopped state, not instantaneously mid-pass.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to seek.
|
|
||||||
* @param position The new playback position, in seconds.
|
|
||||||
*/
|
|
||||||
void audioStreamSetPosition(audiostream_t *stream, const float_t position);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the loop region for the given audio stream: once playback reaches
|
|
||||||
* loopStart, it jumps back to loopTo instead of continuing (or stopping,
|
|
||||||
* if not looping). Has no effect unless looping is also enabled via
|
|
||||||
* audioStreamSetLooping().
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to update.
|
|
||||||
* @param loopStart Where the loop segment ends, in seconds, or -1 to loop
|
|
||||||
* the whole stream (the default).
|
|
||||||
* @param loopTo Where the loop segment starts, in seconds.
|
|
||||||
*/
|
|
||||||
void audioStreamSetLoopPoints(
|
|
||||||
audiostream_t *stream,
|
|
||||||
const float_t loopStart,
|
|
||||||
const float_t loopTo
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Computes normalized left/right pan factors (0..1) for the given audio
|
|
||||||
* stream's directionality. Callers multiply these by their own
|
|
||||||
* platform-specific base volume representation.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to read directionality from.
|
|
||||||
* @param outLeft Set to the left channel's pan factor.
|
|
||||||
* @param outRight Set to the right channel's pan factor.
|
|
||||||
*/
|
|
||||||
void audioStreamGetPanFactors(
|
|
||||||
const audiostream_t *stream,
|
|
||||||
float_t *outLeft,
|
|
||||||
float_t *outRight
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Computes the stop frame for a playback pass starting at startFrame: the
|
|
||||||
* current loop segment's end (stream->loopStart, converted to frames and
|
|
||||||
* clamped to totalFrames) if looping is enabled and a loop start is set,
|
|
||||||
* or totalFrames itself otherwise - including when startFrame has already
|
|
||||||
* reached or passed the computed loop end (e.g. a seek landing in an
|
|
||||||
* outro past the loop point), in which case this pass plays out to the
|
|
||||||
* true end of the stream once instead of only the loop segment.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to compute this for.
|
|
||||||
* @param startFrame This pass's starting frame offset.
|
|
||||||
* @param totalFrames The stream's total decoded frame count
|
|
||||||
* (audioStreamGetTotalFrames()).
|
|
||||||
* @return This pass's stop frame offset.
|
|
||||||
*/
|
|
||||||
size_t audioStreamComputeEndFrame(
|
|
||||||
const audiostream_t *stream,
|
|
||||||
const size_t startFrame,
|
|
||||||
const size_t totalFrames
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the playback volume of the given audio stream.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to update.
|
|
||||||
* @param volume The new volume, from 0.0 (silent) to 1.0 (loudest).
|
|
||||||
*/
|
|
||||||
void audioStreamSetVolume(audiostream_t *stream, const float_t volume);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the stereo directionality (panning) of the given audio stream.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to update.
|
|
||||||
* @param directionality The new panning value, from AUDIO_STREAM_LEFT to
|
|
||||||
* AUDIO_STREAM_RIGHT.
|
|
||||||
*/
|
|
||||||
void audioStreamSetDirectionality(
|
|
||||||
audiostream_t *stream,
|
|
||||||
const float_t directionality
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets whether the given audio stream loops back to loopTo (or the start
|
|
||||||
* of the buffer, by default - see audioStreamSetLoopPoints()) when it
|
|
||||||
* reaches loopStart (or the end of the buffer), rather than stopping and
|
|
||||||
* firing onEnd.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to update.
|
|
||||||
* @param looping Whether the stream should loop.
|
|
||||||
*/
|
|
||||||
void audioStreamSetLooping(audiostream_t *stream, const bool_t looping);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the maximum number of times the given audio stream is allowed to
|
|
||||||
* loop before stopping (firing onEnd) instead of restarting again. Has no
|
|
||||||
* effect unless looping is also enabled via audioStreamSetLooping(). Resets
|
|
||||||
* the stream's current loop-restart progress back to 0, so the stream gets
|
|
||||||
* the full count from this call onward.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to update.
|
|
||||||
* @param loopLimit Maximum number of loop restarts, or 0 (the default) to
|
|
||||||
* loop forever.
|
|
||||||
*/
|
|
||||||
void audioStreamSetLoopLimit(audiostream_t *stream, const uint32_t loopLimit);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the given audio stream, decoding new data and advancing playback
|
|
||||||
* as needed. Should be called every frame for every active stream.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to update.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamUpdate(audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disposes the audio stream, stopping playback and releasing any resources
|
|
||||||
* associated with it.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to dispose.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamDispose(audiostream_t *stream);
|
|
||||||
@@ -1,167 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "audiostreammp3.h"
|
|
||||||
#include "audiostream.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "util/math.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
|
|
||||||
errorret_t audioStreamMp3Init(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertNotNull(stream->asset, "Stream must have an asset assigned.");
|
|
||||||
assertTrue(
|
|
||||||
stream->asset->type == ASSET_LOADER_TYPE_MP3,
|
|
||||||
"Asset is not an MP3 file."
|
|
||||||
);
|
|
||||||
|
|
||||||
const assetmp3file_t *mp3 = &stream->asset->data.mp3;
|
|
||||||
|
|
||||||
stream->type = AUDIO_STREAM_TYPE_MP3;
|
|
||||||
stream->sampleRate = mp3->sampleRate;
|
|
||||||
stream->channels = mp3->channels;
|
|
||||||
stream->duration = (float_t) mp3->totalFrames / (float_t) mp3->sampleRate;
|
|
||||||
|
|
||||||
stream->mp3.pendingFrames = 0;
|
|
||||||
stream->mp3.pendingPosition = 0;
|
|
||||||
stream->mp3.position = 0;
|
|
||||||
stream->mp3.totalFrames = mp3->totalFrames;
|
|
||||||
|
|
||||||
// Each stream opens its own independent handle to the same underlying
|
|
||||||
// asset file - see audiostreampcm.c's audioStreamPcmInit() for why.
|
|
||||||
errorChain(assetFileInit(
|
|
||||||
&stream->mp3.file, stream->asset->name, NULL, NULL
|
|
||||||
));
|
|
||||||
errorChain(assetFileOpen(&stream->mp3.file));
|
|
||||||
errorChain(assetFileRead(&stream->mp3.file, NULL, mp3->dataOffset));
|
|
||||||
|
|
||||||
errorChain(audioStreamMp3DecoderInit(stream));
|
|
||||||
|
|
||||||
errorChain(audioStreamPlatformInit(stream));
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamMp3Dispose(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
|
||||||
|
|
||||||
errorChain(audioStreamMp3DecoderDispose(stream));
|
|
||||||
errorChain(assetFileClose(&stream->mp3.file));
|
|
||||||
errorChain(assetFileDispose(&stream->mp3.file));
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t audioStreamMp3GetTotalFrames(const audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
|
||||||
|
|
||||||
return stream->mp3.totalFrames;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamMp3Seek(audiostream_t *stream, const size_t frame) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
|
||||||
|
|
||||||
if(frame == stream->mp3.position) {
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Every seek - forward or backward - restarts decoding from the very
|
|
||||||
// start of the compressed stream and discards frames until reaching the
|
|
||||||
// target; see this file's own header comment for why MP3 has no cheaper
|
|
||||||
// option, unlike audioStreamPcmSeek()'s direct byte-offset seek.
|
|
||||||
errorChain(audioStreamMp3DecoderRewind(stream));
|
|
||||||
stream->mp3.position = 0;
|
|
||||||
stream->mp3.pendingFrames = 0;
|
|
||||||
stream->mp3.pendingPosition = 0;
|
|
||||||
|
|
||||||
const size_t channels = stream->channels;
|
|
||||||
int16_t discard[AUDIO_MP3_MAX_SAMPLES_PER_FRAME];
|
|
||||||
|
|
||||||
while(stream->mp3.position < frame) {
|
|
||||||
size_t decodedFrames = 0;
|
|
||||||
errorChain(
|
|
||||||
audioStreamMp3DecoderDecodeFrame(stream, discard, &decodedFrames)
|
|
||||||
);
|
|
||||||
if(decodedFrames == 0) {
|
|
||||||
// Ran out of stream before reaching the target - clamp rather than
|
|
||||||
// erroring, same tolerance audioStreamPcmRead() has for a
|
|
||||||
// shorter-than-declared asset.
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t framesNeeded = frame - stream->mp3.position;
|
|
||||||
if(decodedFrames <= framesNeeded) {
|
|
||||||
stream->mp3.position += decodedFrames;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This frame overshoots the target - keep the excess as pending so
|
|
||||||
// the next Read() starts exactly at `frame` instead of skipping past
|
|
||||||
// it.
|
|
||||||
const size_t keepFrames = decodedFrames - framesNeeded;
|
|
||||||
memoryMove(
|
|
||||||
discard, discard + (framesNeeded * channels),
|
|
||||||
keepFrames * channels * sizeof(int16_t)
|
|
||||||
);
|
|
||||||
memoryCopy(
|
|
||||||
stream->mp3.pending, discard, keepFrames * channels * sizeof(int16_t)
|
|
||||||
);
|
|
||||||
stream->mp3.pendingFrames = keepFrames;
|
|
||||||
stream->mp3.pendingPosition = 0;
|
|
||||||
stream->mp3.position = frame;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamMp3Read(
|
|
||||||
audiostream_t *stream,
|
|
||||||
int16_t *buffer,
|
|
||||||
const size_t frameCount,
|
|
||||||
size_t *outFramesRead
|
|
||||||
) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertNotNull(buffer, "Buffer cannot be NULL.");
|
|
||||||
assertNotNull(outFramesRead, "outFramesRead cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_MP3, "Stream is not MP3.");
|
|
||||||
|
|
||||||
const size_t channels = stream->channels;
|
|
||||||
size_t framesWritten = 0;
|
|
||||||
|
|
||||||
while(framesWritten < frameCount) {
|
|
||||||
if(stream->mp3.pendingPosition >= stream->mp3.pendingFrames) {
|
|
||||||
size_t decodedFrames = 0;
|
|
||||||
errorChain(audioStreamMp3DecoderDecodeFrame(
|
|
||||||
stream, stream->mp3.pending, &decodedFrames
|
|
||||||
));
|
|
||||||
stream->mp3.pendingFrames = decodedFrames;
|
|
||||||
stream->mp3.pendingPosition = 0;
|
|
||||||
if(decodedFrames == 0) break; // Genuine end of stream.
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t framesAvailable =
|
|
||||||
stream->mp3.pendingFrames - stream->mp3.pendingPosition;
|
|
||||||
const size_t framesToCopy =
|
|
||||||
mathMin(frameCount - framesWritten, framesAvailable);
|
|
||||||
|
|
||||||
memoryCopy(
|
|
||||||
buffer + (framesWritten * channels),
|
|
||||||
stream->mp3.pending + (stream->mp3.pendingPosition * channels),
|
|
||||||
framesToCopy * channels * sizeof(int16_t)
|
|
||||||
);
|
|
||||||
|
|
||||||
stream->mp3.pendingPosition += framesToCopy;
|
|
||||||
framesWritten += framesToCopy;
|
|
||||||
}
|
|
||||||
|
|
||||||
stream->mp3.position += framesWritten;
|
|
||||||
*outFramesRead = framesWritten;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
@@ -1,140 +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"
|
|
||||||
#include "asset/assetfile.h"
|
|
||||||
#include "audio/audiostreammp3decoder.h"
|
|
||||||
|
|
||||||
typedef struct audiostream_s audiostream_t;
|
|
||||||
|
|
||||||
// How many interleaved PCM samples (not frames - samples, i.e. frames *
|
|
||||||
// channels) a single audioStreamMp3DecoderDecodeFrame() call is ever
|
|
||||||
// allowed to produce. Sizes the pending-sample buffer below, which every
|
|
||||||
// decoder backend writes directly into - this must be sized to the
|
|
||||||
// largest of them, not just "one MPEG frame":
|
|
||||||
// - libmad (software, Linux/Dolphin): always exactly one frame, 1152
|
|
||||||
// samples/channel for MPEG-1 Layer III, doubled here for stereo.
|
|
||||||
// - sceMp3 (hardware, PSP): its own pcmBuf is provisioned at double that
|
|
||||||
// (see AUDIO_MP3_PSP_PCM_BUF_SIZE) - i.e. sceMp3Decode() can
|
|
||||||
// legitimately hand back more than one frame's worth in a single call.
|
|
||||||
// Sizing this for only one frame silently overflowed stream->mp3.pending
|
|
||||||
// on real hardware whenever that happened - confirmed as the cause of
|
|
||||||
// very intermittent audio corruption/clicking, since it only bit when
|
|
||||||
// sceMp3 actually returned the larger amount.
|
|
||||||
// So this covers the larger (PSP) case; libmad's decode is safely well
|
|
||||||
// within it.
|
|
||||||
#define AUDIO_MP3_MAX_SAMPLES_PER_FRAME (1152 * 2 * 2)
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
// This stream's own private handle into its asset's underlying file -
|
|
||||||
// see audiostreampcm_t.file's own comment for why this isn't shared
|
|
||||||
// across streams playing the same asset. Holds compressed MP3 bytes;
|
|
||||||
// the decoder backend (audiostreammp3decoder.h) reads from it directly.
|
|
||||||
assetfile_t file;
|
|
||||||
|
|
||||||
// Opaque per-platform decoder state - a reserved sceMp3 handle plus its
|
|
||||||
// buffers on PSP, or libmad's mad_stream/mad_frame/mad_synth state plus a
|
|
||||||
// sliding compressed-byte window on the libmad-based software backend
|
|
||||||
// (Linux/Dolphin). Defined by whichever audiostreammp3decoder.h is
|
|
||||||
// actually visible when this file is compiled - see that header's own
|
|
||||||
// comment.
|
|
||||||
audiostreammp3decoder_t decoder;
|
|
||||||
|
|
||||||
// One decoded MPEG frame's worth of PCM, held here across Read() calls
|
|
||||||
// since a frame (576 or 1152 samples/channel) rarely lines up exactly
|
|
||||||
// with whatever frameCount a caller asks for. pendingPosition marks how
|
|
||||||
// many of the first pendingFrames frames have already been consumed.
|
|
||||||
int16_t pending[AUDIO_MP3_MAX_SAMPLES_PER_FRAME];
|
|
||||||
size_t pendingFrames;
|
|
||||||
size_t pendingPosition;
|
|
||||||
|
|
||||||
// Current logical PCM frame position, relative to the start of the
|
|
||||||
// decoded stream - decoding is push-forward-only (see
|
|
||||||
// audioStreamMp3Seek()'s own comment on why a backward seek re-decodes
|
|
||||||
// from the start rather than truly random-accessing).
|
|
||||||
size_t position;
|
|
||||||
|
|
||||||
// Total decoded PCM frame count for the whole clip - copied from the
|
|
||||||
// asset's parsed metadata at Init (see assetmp3file_t.totalFrames),
|
|
||||||
// exact if a Xing/Info header was present, otherwise an estimate.
|
|
||||||
size_t totalFrames;
|
|
||||||
} audiostreammp3_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Configures the given MP3 audio stream from its already-assigned asset
|
|
||||||
* (see audiostream_t.asset - set by audioStreamInit(), which is what
|
|
||||||
* should be calling this, not application code directly): opens this
|
|
||||||
* stream's own private file handle onto the asset's compressed MPEG data,
|
|
||||||
* and initializes the platform decoder backend
|
|
||||||
* (audioStreamMp3DecoderInit()).
|
|
||||||
*
|
|
||||||
* Must be called after stream->asset is set and before audioStreamPlay().
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to configure.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamMp3Init(audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disposes the given MP3 audio stream's decoder backend and private file
|
|
||||||
* handle.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to dispose.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamMp3Dispose(audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the total number of frames (one sample per channel) available in
|
|
||||||
* the stream's underlying MP3 data - see assetmp3file_t.totalFrames's own
|
|
||||||
* comment on why this is sometimes an estimate rather than an exact count,
|
|
||||||
* unlike audioStreamPcmGetTotalFrames().
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to query. Must be AUDIO_STREAM_TYPE_MP3.
|
|
||||||
* @return The total number of frames available.
|
|
||||||
*/
|
|
||||||
size_t audioStreamMp3GetTotalFrames(const audiostream_t *stream);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Seeks the stream's decode position to the given frame offset. Unlike
|
|
||||||
* audioStreamPcmSeek(), this is never cheap: MPEG frames aren't
|
|
||||||
* independently decodable (each one's bit reservoir can depend on data
|
|
||||||
* carried over from prior frames), so there's no equivalent of PCM's
|
|
||||||
* direct byte-offset seek - every call, forward or backward, rewinds the
|
|
||||||
* decoder to the very start of the compressed stream and decodes (and
|
|
||||||
* discards) frames until reaching the target. Acceptable for this engine's
|
|
||||||
* actual use (looping background music, where loopTo is typically near
|
|
||||||
* the start anyway), but a real, non-constant cost for a seek deep into a
|
|
||||||
* long track.
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to seek. Must be AUDIO_STREAM_TYPE_MP3.
|
|
||||||
* @param frame Frame offset to seek to, relative to the start of the
|
|
||||||
* decoded stream.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamMp3Seek(audiostream_t *stream, const size_t frame);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads up to frameCount frames of PCM sample data from the stream's
|
|
||||||
* current position, advancing it by however many frames were actually
|
|
||||||
* read. Reads fewer than frameCount (down to zero) once the underlying
|
|
||||||
* MP3 data is exhausted, rather than erroring - same contract as
|
|
||||||
* audioStreamPcmRead().
|
|
||||||
*
|
|
||||||
* @param stream The audio stream to read from. Must be AUDIO_STREAM_TYPE_MP3.
|
|
||||||
* @param buffer Destination buffer, sized for at least frameCount frames.
|
|
||||||
* @param frameCount Maximum number of frames to read.
|
|
||||||
* @param outFramesRead Set to the number of frames actually read.
|
|
||||||
* @return Error indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t audioStreamMp3Read(
|
|
||||||
audiostream_t *stream,
|
|
||||||
int16_t *buffer,
|
|
||||||
const size_t frameCount,
|
|
||||||
size_t *outFramesRead
|
|
||||||
);
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "audiostreampcm.h"
|
|
||||||
#include "audiostream.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
#include "util/math.h"
|
|
||||||
#include "util/memory.h"
|
|
||||||
#include "util/endian.h"
|
|
||||||
|
|
||||||
errorret_t audioStreamPcmInit(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertNotNull(stream->asset, "Stream must have an asset assigned.");
|
|
||||||
assertTrue(
|
|
||||||
stream->asset->type == ASSET_LOADER_TYPE_WAV,
|
|
||||||
"Asset is not a WAV file."
|
|
||||||
);
|
|
||||||
|
|
||||||
assetwavfile_t *wav = &stream->asset->data.wav;
|
|
||||||
|
|
||||||
stream->type = AUDIO_STREAM_TYPE_PCM;
|
|
||||||
stream->sampleRate = wav->sampleRate;
|
|
||||||
stream->channels = wav->channels;
|
|
||||||
stream->duration = (
|
|
||||||
(float_t) audioStreamPcmGetTotalFrames(stream) /
|
|
||||||
(float_t) wav->sampleRate
|
|
||||||
);
|
|
||||||
|
|
||||||
// Each stream opens its own independent handle to the same underlying
|
|
||||||
// asset file, rather than sharing a single handle on the asset entry -
|
|
||||||
// multiple streams playing the same asset concurrently (e.g. two
|
|
||||||
// simultaneous plays of the same sound effect) would otherwise fight
|
|
||||||
// over one shared read position. This isn't the final answer for that
|
|
||||||
// (a shared decode/cache layer would scale better than N independent
|
|
||||||
// decompression streams of the same data), but it's a correct one for
|
|
||||||
// now - a problem to revisit once it actually matters.
|
|
||||||
errorChain(assetFileInit(
|
|
||||||
&stream->pcm.file, stream->asset->name, NULL, NULL
|
|
||||||
));
|
|
||||||
errorChain(assetFileOpen(&stream->pcm.file));
|
|
||||||
errorChain(assetFileRead(&stream->pcm.file, NULL, wav->dataOffset));
|
|
||||||
|
|
||||||
errorChain(audioStreamPlatformInit(stream));
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamPcmDispose(audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
|
||||||
|
|
||||||
errorChain(assetFileClose(&stream->pcm.file));
|
|
||||||
errorChain(assetFileDispose(&stream->pcm.file));
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t audioStreamPcmGetTotalFrames(const audiostream_t *stream) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
|
||||||
|
|
||||||
const assetwavfile_t *wav = &stream->asset->data.wav;
|
|
||||||
const size_t sourceFrameSize = (
|
|
||||||
stream->channels * (wav->bitsPerSample / 8)
|
|
||||||
);
|
|
||||||
return wav->dataSize / sourceFrameSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamPcmSeek(audiostream_t *stream, const size_t frame) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
|
||||||
|
|
||||||
assetwavfile_t *wav = &stream->asset->data.wav;
|
|
||||||
const size_t sourceFrameSize = (
|
|
||||||
stream->channels * (wav->bitsPerSample / 8)
|
|
||||||
);
|
|
||||||
const size_t targetByte = wav->dataOffset + (frame * sourceFrameSize);
|
|
||||||
|
|
||||||
assertTrue(
|
|
||||||
frame * sourceFrameSize <= wav->dataSize,
|
|
||||||
"Seek frame is beyond the end of the PCM data."
|
|
||||||
);
|
|
||||||
|
|
||||||
const size_t currentByte = (size_t) stream->pcm.file.position;
|
|
||||||
if(targetByte < currentByte) {
|
|
||||||
// Only a full rewind can move a read cursor earlier once it's already
|
|
||||||
// advanced past a point - a compressed archive entry can't be decoded
|
|
||||||
// backward. See this function's own doc comment for the performance
|
|
||||||
// implications of a deep loopTo.
|
|
||||||
errorChain(assetFileRewind(&stream->pcm.file));
|
|
||||||
errorChain(assetFileRead(&stream->pcm.file, NULL, targetByte));
|
|
||||||
} else if(targetByte > currentByte) {
|
|
||||||
errorChain(assetFileRead(
|
|
||||||
&stream->pcm.file, NULL, targetByte - currentByte
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t audioStreamPcmRead(
|
|
||||||
audiostream_t *stream,
|
|
||||||
int16_t *buffer,
|
|
||||||
const size_t frameCount,
|
|
||||||
size_t *outFramesRead
|
|
||||||
) {
|
|
||||||
assertNotNull(stream, "Stream cannot be NULL.");
|
|
||||||
assertNotNull(buffer, "Buffer cannot be NULL.");
|
|
||||||
assertNotNull(outFramesRead, "outFramesRead cannot be NULL.");
|
|
||||||
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
|
|
||||||
|
|
||||||
assetwavfile_t *wav = &stream->asset->data.wav;
|
|
||||||
const size_t channels = stream->channels;
|
|
||||||
const size_t sourceSampleBytes = wav->bitsPerSample / 8;
|
|
||||||
const size_t sourceFrameSize = channels * sourceSampleBytes;
|
|
||||||
const size_t dataEndByte = wav->dataOffset + wav->dataSize;
|
|
||||||
const size_t currentByte = (size_t) stream->pcm.file.position;
|
|
||||||
|
|
||||||
const size_t bytesAvailable = (
|
|
||||||
currentByte < dataEndByte ? dataEndByte - currentByte : 0
|
|
||||||
);
|
|
||||||
const size_t framesAvailable = bytesAvailable / sourceFrameSize;
|
|
||||||
const size_t framesToRead = mathMin(frameCount, framesAvailable);
|
|
||||||
|
|
||||||
if(framesToRead == 0) {
|
|
||||||
*outFramesRead = 0;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
if(sourceSampleBytes == sizeof(int16_t)) {
|
|
||||||
// Output format already matches the source in width, but WAV samples
|
|
||||||
// are always little-endian per the format spec regardless of host -
|
|
||||||
// read straight through, then fix up byte order in place. A no-op on
|
|
||||||
// every little-endian platform (endianLittleToHost16() compiles down
|
|
||||||
// to returning its argument unchanged there) - only actually swaps
|
|
||||||
// anything on a big-endian host (Dolphin/GameCube/Wii).
|
|
||||||
errorChain(assetFileRead(
|
|
||||||
&stream->pcm.file, buffer, framesToRead * sourceFrameSize
|
|
||||||
));
|
|
||||||
const size_t sampleCount = framesToRead * channels;
|
|
||||||
for(size_t i = 0; i < sampleCount; i++) {
|
|
||||||
buffer[i] = (int16_t) endianLittleToHost16((uint16_t) buffer[i]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 24-bit source (the only other width assetWavParseHeader() accepts) -
|
|
||||||
// read the raw 3-byte samples into a scratch buffer, then truncate
|
|
||||||
// each down to 16-bit, since none of PSP/Dolphin's audio hardware (or
|
|
||||||
// SDL2 on Linux) accepts anything wider - see assetwavfile_t's own
|
|
||||||
// comment on bitsPerSample.
|
|
||||||
assertTrue(sourceSampleBytes == 3, "Unsupported PCM sample width.");
|
|
||||||
|
|
||||||
const size_t rawBytes = framesToRead * sourceFrameSize;
|
|
||||||
uint8_t *raw = memoryAllocate(rawBytes);
|
|
||||||
errorret_t ret = assetFileRead(&stream->pcm.file, raw, rawBytes);
|
|
||||||
if(errorIsNotOk(ret)) {
|
|
||||||
memoryFree(raw);
|
|
||||||
errorChain(ret);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 24-bit PCM samples are little-endian two's complement - the top two
|
|
||||||
// bytes of each (indices 1 and 2) already form that same value
|
|
||||||
// truncated to 16-bit (equivalent to an arithmetic right-shift by 8
|
|
||||||
// bits, which preserves the sign correctly since byte 2 carries it).
|
|
||||||
const size_t sampleCount = framesToRead * channels;
|
|
||||||
for(size_t i = 0; i < sampleCount; i++) {
|
|
||||||
const uint8_t *sample = raw + (i * 3);
|
|
||||||
buffer[i] = (int16_t) (sample[1] | (sample[2] << 8));
|
|
||||||
}
|
|
||||||
|
|
||||||
memoryFree(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
*outFramesRead = framesToRead;
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
Loaded 100 of 956 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user