Author SHA1 Message Date
YourWishesandClaude Opus 5 5cf81aa238 Normalize code style to match established conventions
An assistant-written stretch of code had drifted from the conventions the
older hand-written files establish. Sweeps the whole of src/ back into line.

Systematic:
- @returns -> @return (163 occurrences, 84 files). Concentrated in ui/ and
  rpg/cutscene/; the rest of the tree already used @return 646 times.
- Lowercase "null" -> "NULL" in assert/error message strings (170
  occurrences, 28 files), matching the dominant 441-use spelling. Covers
  "cannot be null", "must not be null" and adjectival uses.

Localized:
- sort.c: drop a stray #include <stdlib.h> that sat *above* the copyright
  header, leaving it the only file in the repo without a leading header
  block. Also drops the same redundant include from random.c and npcturn.c
  (dusk.h already pulls in stdlib.h).
- Convert 7 files' license headers from // lines to the /** */ block form.
- cutscenesystem.c: memset -> memoryZero, matching the identical call ~20
  lines further down and the rest of the codebase.
- Struct tags suffixed _t -> _s: threadlock_t -> threadmutex_s (which also
  makes the tag match its typedef) and chunkpos_t -> chunkpos_s.
- Convert 20 inline /* */ block comments to // across the mesh builders,
  assetfile.c and assetlocaleloader.c.
- Pointer truthiness if(!ptr) -> if(ptr == NULL) in 16 places, matching the
  267 existing explicit comparisons. Boolean !x checks are left alone.
- entityanim.h: drop a JSDoc-style type annotation from an @return.
- Document easing.h's 16 undeclared easing functions and
  assetjsonloader.h's 3 loader callbacks.

No behavioral change. Builds clean with no new warnings; ctest shows the
same 6 pre-existing failures as HEAD, verified against a pristine worktree.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-07 17:10:32 -05:00
YourWishesandClaude Sonnet 5 b3623c84a5 Fix entity chunk-tracking leaks, add saveCanSave, use chunkindex_t
Entities weren't being detached from their chunk's entities[] slot in
two despawn paths (CUTSCENE_ENTITY_REMOVE, item pickup collection) - the
slot leaked forever until the whole chunk unloaded. Both now call
entitySetChunk(entity, CHUNK_INDEX_INVALID) before nulling the type.

entity_t.chunkIndex and entitySetChunk/mapGetChunk now use chunkindex_t
instead of uint8_t, matching mapGetChunkIndexAt's own -1-is-invalid
convention - added CHUNK_INDEX_INVALID next to the typedef in
worldpos.h rather than reusing the old 0xFF/uint8_t sentinel, which
would silently mean +255 on a signed 16-bit field instead of -1.

mapPositionSet now also recomputes every live entity's cached
chunkIndex after mapRebuildChunkOrder() reshuffles which chunk_t sits
at each chunkOrder slot - done as a direct field recompute rather than
through entitySetChunk, which would've looked up each entity's now-stale
old index, failed to find/clear its real registration, and inserted a
duplicate entry into the correct chunk on every map position change.

Also adds saveCanSave() (false while a cutscene is running) and shows
the player's live chunkIndex in the ui/debug/uiplayerpos overlay.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-07 10:12:37 -05:00
YourWishesandClaude Sonnet 5 45c1f9004b Load the chosen save slot on selection, fix transition finished re-firing
Picking a save slot now sets SAVE.slotCurrent and calls saveLoadSlot()
before entering the overworld, same slotCurrent/saveSlotInit/saveLoadSlot
sequence saveLoadAllSlots uses per-slot; a load failure shows the fatal
error overlay instead of proceeding with stale/garbage slot data.

Also fixes uiTransitionUpdate firing its "finished" callback every frame
after a transition completes instead of once - latent since the generic
transition system had no real caller yet.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-06 12:13:51 -05:00
YourWishesandClaude Sonnet 5 845a395ff1 Fix New Game falling through into the Quit confirm dialog
The SAVE_DEVICE_FOUND/SAVE_LOAD_ALL_SLOTS block had been moved to the
end of the file (after QUIT/QUIT_GAME) without moving the LOADED
marker with it. MARKER items always auto-advance to whatever follows
them in the array, so reaching LOADED after a successful save-load fell
straight through into the QUIT block's confirm dialog instead of
completing the cutscene. LOADED now sits after SAVE_LOAD_ALL_SLOTS as
the true last item, so it falls off the end and fires
uiMainMenuOpenSelectSave again as intended.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-06 11:52:48 -05:00
YourWishesandClaude Sonnet 5 f63653c307 Wire main menu Options/Quit through the cutscene, fix locale crashes
Options and Quit now route through main_menu.jsonc markers the same
way New Game does, with a new QUIT_GAME cutscene item type ending the
process directly once quit is confirmed via MODAL_OPTIONS_MARKERS
(whose "message" field is now optional, defaulting to "" like "title").

Fixes two crashes surfaced along the way:
- uiModalLocalize asserted on an empty locale key instead of treating
  it as "nothing to show" - hit as soon as a modal omitted a title or
  message.
- assetLocaleGetString's new empty-message-ID guard broke the PO
  format's own header-read convention (messageId "") used internally
  by assetLocaleLoaderAsync, crashing on every boot. Extracted the
  shared lookup into assetLocaleGetStringLookup and added a dedicated
  assetLocaleGetHeader for that internal read, leaving
  assetLocaleGetString's validation untouched for every real caller.

Also replaced every raw assetLocaleGetString/WithVA call across the UI
with the locale/localemanager.h helpers (adding localeManagerGetString
for the plain, non-formatting case), so app code no longer bypasses
them.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-06 11:47:34 -05:00
YourWishesandClaude Sonnet 5 5b523c68a7 Add cutsceneSystemLoad, a debug cutscene overlay, and NULL-safe fatal error
cutsceneSystemLoad(file) centralizes the lock/assetRequireLoaded/start
sequence previously duplicated in sceneInitialInit, and falls back to
the fatal error overlay instead of asserting when the asset fails to
load. uiFatalErrorOpen now accepts a NULL message, showing a generic
"contact support" message for callers with no specific error text.
Also adds a ui/debug/uicutscene overlay showing the running cutscene's
item count and current item type, and wires main_menu's post-save-picker
flow through cutsceneSystemLoad.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-06 11:18:48 -05:00
YourWishesandClaude Sonnet 5 03efbe0681 Move cutscene item JSON parsing into per-item Load callbacks
Each cutscene item type now owns its own JSON parsing (a Load callback
alongside its existing runtime callbacks), instead of one monolithic
switch in assetcutsceneloader.c. Shared JSON field/enum decoding helpers
move into a new rpg/cutscene/item/json/ module so per-type parsers stay
small and colocated with the behavior they configure.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-06 09:32:10 -05:00
YourWishesandClaude Sonnet 5 cebd3d81e7 Wrap long lines to fit within 80 columns across the codebase
Pure whitespace/line-break reformatting (braces, newlines, and line
continuations matching this codebase's existing wrap conventions) - no
logic, string content, or identifiers changed anywhere. Confirmed via
diff against the pre-change tree and by rebuilding + re-running the
affected test suites, which produce identical pass/fail results.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-05 13:13:10 -05:00
YourWishesandClaude Sonnet 5 de53bebeb8 Remove the main menu scene now that it's just a persistent cutscene
The main menu no longer needs its own scene lifecycle - it's started
directly by the initial cutscene's CUTSCENE item chaining into
main_menu.jsonc. Fold scenemainmenu.c's logic into uimainmenu.c (its
only real caller) and drop SCENE_TYPE_MAIN_MENU entirely. Also arm the
cutscene's onComplete callback unconditionally in uiMainMenuStartGame
so the save-picker still opens on a fresh boot, not just on restart.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-05 12:18:02 -05:00
YourWishesandClaude Sonnet 5 6ccaedd48f Load cutscenes directly from JSONC at runtime, fix asset bundling staleness
Cutscenes now parse their authored .jsonc straight into the runtime
cutsceneitem_t/pool representation via yyjson, instead of going through a
separate Python-compiled DCTS binary format - removes the whole
build/compile step and the byte-format contract between the Python
encoder and the C decoder, at the cost of a (still tiny, one-time)
parse per cutscene load.

Also fixes dusk.dsk going stale after a build: the old custom_command
depended on a CMake-configure-time file glob, which only re-detects
added/removed assets on the next configure and could miss edits
entirely. tools.asset.pack now always runs and decides for itself
(via a small manifest) whether anything actually needs repacking, so
asset changes are never missed regardless of add/edit/remove.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-05 12:05:23 -05:00
YourWishesandClaude Sonnet 5 707856fcf2 Run one persistent cutscene for the whole main menu, not just start-game
Previously the main menu UI opened directly with no cutscene, and only
pressing "Start Game" spun up a brand new cutscene
(main_menu_start_game.jsonc) for the save-device check/load-slots flow.
Now a single cutscene (main_menu.jsonc) starts the moment the main menu
scene becomes active, sitting idle (new CUTSCENE_ITEM_TYPE_IDLE item -
no existing item type blocked forever with no side effect) while the
menu is shown, so it can own menu-wide state going forward.

Pressing "Start Game" now jumps the already-running cutscene to a
NEW_GAME marker via cutsceneGoTo instead of starting a second cutscene -
this already-existing mechanism needed no engine changes. Both retry
options (no device / load error) also now jump straight back to
NEW_GAME instead of RESTARTing the whole cutscene, since RESTART would
otherwise strand the player on the idle block. sceneMainMenuStartGame
also handles the case where the cutscene already ran to completion once
(e.g. backing out of the save picker and pressing Start Game again) by
restarting it landing straight on NEW_GAME, avoiding a crash from
jumping a marker with no cutscene running.

Built and verified on Linux (boots/idles without crashing, cutscene
tests pass), PSP, GameCube and Wii (Docker).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-04 18:18:49 -05:00
YourWishesandClaude Sonnet 5 3c3dc35e1d Default Wii saves to SD card, store saves next to dusk.dsk/EBOOT.PBP
Wii NAND save storage is blocked by Dolphin's IOS ticket-rights check for
homebrew (documented earlier this session as a known, non-code limitation),
so Wii now defaults DUSK_SAVE_WII_METHOD to SD instead of NAND.

Also: asset_t gains ASSET.baseDirectory, populated by each platform's asset
loader with the real directory dusk.dsk was opened from (or, on PSP, the
directory EBOOT.PBP itself lives in, since dusk.dsk is embedded inside it).
Wii SD and PSP now write their single combined save file directly into
that directory instead of a separate hardcoded path, and no longer need to
create it (it's already known to exist). Linux now uses a `saves/`
subdirectory of that same directory instead of ~/.dusk/saves, since it
keeps multiple files (settings + one per slot). Wii NAND and GameCube/Wii
memory-card storage are unaffected - neither has a real filesystem-path
concept this applies to.

Built and verified on Linux, PSP (Docker), GameCube (Docker) and Wii
(Docker) - confirmed via the compiler invocation that Wii now compiles
with DUSK_SAVE_WII_METHOD_SD.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-04 09:43:00 -05:00
YourWishesandClaude Sonnet 5 f9820bd226 Fix crash when continuing without a save device
saveLoadSlot() and uiSelectSaveNameEntered() both asserted
SAVE.deviceCurrent != 0xFF unconditionally, crashing as soon as a player
dismissed the "no save device found" prompt and tried to start a game or
name a new save. Both now fall back to an in-memory-only slot (no device
to persist to) instead of asserting, matching the "continue without a
save device" flow the main menu cutscene already offers.

Verified fixed on Dolphin/GameCube; built clean on Linux and GameCube
(Docker).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-04 08:46:43 -05:00
YourWishes fe2ef92ef3 Testing audio cutscene controls 2026-09-02 18:49:12 -05:00
YourWishesandClaude Sonnet 5 9364768397 Add cutscene controls for the audio mixer, fix PSP pause latency
- Fixed PSP pause taking up to ~1.1s to actually go silent: its output
  thread ran independently of stream->state, draining its whole software
  ring regardless. audiostream_t.state is now volatile and the output
  thread checks AUDIO_STREAM_STATE_PLAYING before each hardware chunk,
  skipping output (without consuming the ring) while paused - pause now
  goes silent within about one chunk (~23ms) and resume has no gap.
- Added audioMixerPause/Resume/SetPan/SetLoop/FadeTo/IsFading to the
  mixer - immediate, channel-indexed primitives for cutscenes to drive.
  Fade transitions (fadeFrom/To/Duration/Time/Easing) live on
  audiomixerchannelstate_t and advance every frame in
  audioMixerChannelApplyVolume(), reusing the same easingApply()
  interpolation uifullbox_t already uses for screen fades.
- New src/dusk/rpg/cutscene/item/audio/ with 9 cutscene item types:
  AUDIO_PLAY (+ AUDIO_PLAY_SIMPLE/AUDIO_PLAY_LOOPED shorthands),
  AUDIO_STOP, AUDIO_PAUSE, AUDIO_RESUME, AUDIO_FADE (+ FADE_OUT/FADE_IN
  shorthands), AUDIO_FADE_WAIT, AUDIO_SET_PAN, AUDIO_SET_LOOP, and the
  combined AUDIO_SET - registered through the same enum/union/callback
  table/macro mechanism every other item type uses.
- Wired the same 9 types into the JSON-based (offline JSONC -> binary
  .cts) cutscene asset pipeline: tools/asset/cutscene/__main__.py's
  encoder and assetcutsceneloader.c's decoder. Verified round-trip by
  hand-encoding/decoding a test file covering all 9 types, and confirmed
  the two existing real cutscene files re-encode byte-identical.

Built and verified on Linux, PSP (Docker), GameCube (Docker) and Wii
(Docker).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 17:44:06 -05:00
YourWishesandClaude Sonnet 5 9c28d5a3b7 Split mixer channel logic into its own module, persist volume settings, add channel callbacks
- Extracted src/dusk/audio/mixer/audiomixerchannel.{h,c}: the channel enum,
  command/state structs, and all per-channel logic (StopStream,
  ApplyVolume, ChannelUpdateEarly/Late) now live there; audiomixer.{h,c}
  just holds the channel array and the public Play/PlayLooped/Stop API.
- Removed audioMixerSetChannelVolume()/audioMixerSetMasterVolume() - volume
  is written directly (SAVE.settings.audioChannelVolume[channel] = 0.3f,
  SAVE.settings.audioMasterVolume = 0.3f) and only ever validated where
  it's read, in audioMixerChannelApplyVolume().
- Moved master/channel volume into savesettings_t (new writeFloatArray/
  readFloatArray save-JSON macros) so they persist as user preferences;
  `fade` moved from an unused mixer-wide array to a real per-channel
  multiplier that's now actually folded into the volume calculation.
- audioMixerUpdateEarly()/Late() now catch and log a single channel's
  error instead of letting it abort every other channel's update for that
  frame (and cascade into skipping the rest of that frame's engine
  update), matching the existing per-stream error-isolation pattern.
- Added persistent per-channel onLoop/onEnd callbacks + a user pointer
  (audiomixerchannelstate_t), wired onto every stream a channel starts via
  a trampoline (audioMixerChannelOnStreamLoop/OnStreamEnd) so they survive
  across multiple plays on the same channel, unlike the underlying stream
  instance itself.
- General cleanup: for loops -> while loops, if/else cascades -> guard
  clauses, dropped unnecessary const on locals, wrapped to 80 columns.

Built and verified on Linux, PSP (Docker), GameCube (Docker) and Wii
(Docker).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 16:07:42 -05:00
YourWishesandClaude Sonnet 5 d5078b978c Cache PSP volume/pan computation, mix channel + master volume into mixer playback, wire boa.mp3 as looping BGM
- PSP output thread now caches the last computed leftVolume/rightVolume and
  only recomputes them when stream->volume/directionality actually changed
  since the previous chunk, instead of recomputing every ~23ms chunk
  unconditionally.
- Mixer channels and the mixer itself now carry their own volume
  (audioMixerSetChannelVolume()/audioMixerSetMasterVolume()), multiplied
  with each sound's own volume every audioMixerUpdateEarly() and applied via
  audioStreamSetVolume() - so changing a channel's or the master volume
  affects whatever's already playing, not just future sounds. Also fixed
  audioMixerUpdateEarly() to tolerate a PLAY command queued outside the
  normal per-frame cycle (no loadingAsset yet from a preceding
  audioMixerUpdateLate(), e.g. during engine startup) by leaving it queued
  for the following frame instead of asserting.
- engine.c now plays boa.mp3 on AUDIO_MIXER_CHANNEL_BGM_0 on loop through
  the mixer instead of driving a raw audiostream_t directly, exercising the
  new mixer pipeline end to end.

Built and verified on Linux, PSP (Docker) and GameCube (Docker).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 15:10:09 -05:00
YourWishesandClaude Sonnet 5 d49594d3fb Redesign audio mixer around a two-phase command queue instead of synchronous main-thread calls
audioMixerPlay()/audioMixerPlayLooped()/audioMixerStop() now just queue a
command per channel instead of taking effect immediately:
- audioMixerUpdateLate() (end of frame) locks and begins loading any newly
  queued PLAY command's asset, giving it until the start of the next frame
  to finish.
- audioMixerUpdateEarly() (start of the next frame) applies the queued
  command - blocking (assetRequireLoaded()) if that load hasn't finished
  yet - actually starting/stopping playback and setting volume,
  directionality and looping (reusing this session's new
  audioStreamSetLoopLimit()) on a real audiostream_t acquired from the
  shared stream pool.

Previously this was an unwired stub (never initialized/updated/disposed
from audio.c, and audioMixerUpdateLate() only printf'd). Built and verified
on Linux, PSP (Docker) and GameCube (Docker).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 14:48:14 -05:00
YourWishesandClaude Sonnet 5 619ce932f9 Split audio update into early/late phases, add asset<->stream type map, switch volume/pan to float, add stream loop limit
- audioUpdate()/audioMixerUpdate() split into Early (before rendering, per-stream buffering) and Late (end of frame, starts newly-queued mixer sounds) phases, wired into engineUpdate() around displayUpdate(); mixer is now actually initialized/disposed/updated from audio.c.
- New src/dusk/audio/stream/audiostreamtype.{h,c}: asset-loader-type <-> audio-stream-type map (with file extension), plus audioStreamAssetTypeForPath()/audioStreamTypeForAssetType()/audioStreamAssetTypeForStreamType() lookups.
- audiostream_t/audiomixerchanneldata_t volume and directionality/pan switched from integer (0-0xFF / -128..127) to float (0.0-1.0 / -1.0..1.0), removing the manual scaling each platform backend had to do.
- audiostream_t gains loopLimit/loopRestartCount so a stream can be told to stop (fire onEnd) after a fixed number of loop restarts instead of looping forever; wired into the shared restart path (Linux/Dolphin) and PSP's own read-ahead loop decision.

Built and verified on Linux, PSP (Docker) and GameCube (Docker).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 14:39:27 -05:00
YourWishesandClaude Sonnet 5 b564d0b1c1 Add Dolphin MP3 decode-thread ring, share it with Linux, dedupe common code
Fixes the main-thread hitch reported on Dolphin (and, less severely,
elsewhere) whenever the MP3 decode buffer needed refilling:
audioStreamMp3Read() -> audioStreamMp3DecoderDecodeFrame() does real work
synchronously (asset I/O + libmad decode), previously called directly from
each platform's once-per-frame Feed(), blocking rendering for a frame on
every refill.

Adds a background decode-ahead ring (src/duskmad/audiostreammp3ring.c):
a one-shot-per-pass thread reads via the existing audioStreamRead() into a
ring buffer ahead of need; Feed() becomes a cheap, lock-protected drain
instead of a decode call. Reuses this project's own thread_t/threadmutex_t
(mutex+condvar) primitives, mirroring PSP's own background-thread-plus-ring
precedent. Fixes a real (if narrow) race in thread.c along the way:
threadHandler() reset thread->threadId outside the mutex it also used to
signal STOPPED, which a stop-then-immediately-restart pattern (needed once
per pass: play/seek/loop-restart) could hit as a stale-threadId assertion.

Initially built Dolphin-only, then generalized: the ring doesn't touch
ASND at all, so it was straightforward to share with Linux too, moving
both it and the libmad decoder into a new top-level src/duskmad/ - a
shared-capability directory in the same vein as src/duskgl or
src/dusknetwork, pulled in by whichever DUSK_TARGET_SYSTEM values need it
(linux/knulli, wii/gamecube) rather than PSP, which keeps its own
hardware sceMp3 decoder and ring untouched.

With both platforms now sharing real code, deduped what was left:
audioStreamComputeEndFrame() (loop-segment math, byte-identical between
Linux/Dolphin) moved to the generic audio/stream/audiostream.c, and
audioStreamMp3Ring*IfNeeded()/audioStreamReadForPlayback() wrappers (in
duskmad) collapse each platform's own `if(stream->type ==
AUDIO_STREAM_TYPE_MP3)` branches at every Init/Dispose/Buffer/Feed call
site into one check each, living in the ring module itself.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 14:10:36 -05:00
YourWishesandClaude Sonnet 5 fc1fc9f170 Rewrite Dolphin audio to use libogc's standard ASND API
Replaces the ansnd-based backend (a third-party library with a custom
DSP ucode Dolphin's HLE audio emulation doesn't recognize, requiring
-a LLE as a workaround) with libogc's own asndlib - the standard,
HLE-supported audio API most GC/Wii homebrew already uses.

Also fixes three real bugs found while getting a large (41MB) WAV
asset actually playing on Dolphin:

- audiostreamdolphin.c previously buffered a stream's entire loop
  segment into one allocation up front (inherited from the ansnd
  design) - fine for a short test tone, but an out-of-memory crash for
  a real multi-minute track on GameCube's 24MB (or even Wii's 88MB)
  total RAM. Rewritten to stream bounded windows via ASND's real
  double-buffer primitives (ASND_SetVoice + ASND_AddVoice, polled from
  the main thread - never from an interrupt callback), matching how
  Linux/PSP already work.

- ASND_TestVoiceBufferReady() returns SND_OK (0) when ready and
  SND_BUSY (1) when not, in the actual toolchain fork
  (extremscorner/libogc2) this project builds against - opposite of a
  plain boolean. Treating the raw result as one meant a genuinely
  ready voice's SND_OK read as false, silently skipping every
  ASND_AddVoice() call forever after a stream's first buffered window.

- audioStreamPcmRead()'s 16-bit fast path read WAV's little-endian
  sample bytes straight into the output buffer with no byte-swap -
  correct by coincidence on every little-endian platform this engine
  targets (Linux, PSP), but reversed every sample's bytes on
  Dolphin/GameCube/Wii's big-endian PowerPC.

libmad is GPL-licensed (see audiostreammp3decodersw.h's own note from
the prior MP3 change); libogc's asndlib is under a permissive
BSD-style license, so this doesn't add another such dependency.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 12:49:53 -05:00
YourWishesandClaude Sonnet 5 fd5bcfae90 Switch Linux/Dolphin MP3 decode from minimp3 to libmad
minimp3's sliding-window frame confirmation could spuriously discard real
frames near the tail of a not-yet-full window, losing ~5.5% of a real
VBR file's content even at a tuned 256KB window (~0.3% residual) -
audible as the whole track finishing early with stutters at each drop.

libmad's mad_stream/mad_frame/mad_synth API reports "need more data"
(MAD_ERROR_BUFLEN) and "genuinely bad data" separately rather than
overloading one return value, which was the actual ambiguity minimp3
couldn't resolve. Verified against the same real file with a 32KB window
(vs minimp3's 256KB): frame count and duration match the Xing header
exactly. Confirmed building for Linux, GameCube, and Wii (the latter two
via the project's real devkitPPC/libogc Docker toolchain) - libmad ships
inside libogc itself on Dolphin, no separate fetch needed there.

libmad is GPL-licensed, unlike the rest of this MIT project - a
deliberate tradeoff, noted at each site that pulls it in.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 09:47:15 -05:00
YourWishesandClaude Sonnet 5 3ee0a53688 Split audio into stream/ and mixer/ subdirs, fix resulting build breaks
Reorganizes src/dusk/audio/: individual stream implementations
(audiostream, audiostreampcm, audiostreammp3, audiostreammp3decodersw)
move into audio/stream/, and a new audio/mixer/ holds a channel-based
playback queue (audiomixer.c/.h) for future use - not yet wired into
the engine.

Fixes needed to keep the tree buildable after the move:
 - A stray duplicate of audiostreammp3decodersw.c/.h was left at the old
   flat path; removed in favor of the canonical copy in stream/.
 - Updated every #include "audio/audiostream*.h" and the two platform
   CMakeLists.txt (dusklinux, duskdolphin) that still pointed at the old
   flat location.
 - audiomixer.c/.h didn't compile: audiomixerqueue_t was referenced but
   never defined (audiomixerchanneldata_t has the matching fields), a
   trailing comma in audioMixerPlayLooped's parameter list is illegal in
   C, and `file` was declared as an array of pointers instead of a char
   buffer.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-02 09:32:41 -05:00
YourWishesandClaude Sonnet 5 62c081ecf2 Fix minimp3 sliding-window decoder silently dropping frames near tail
audioStreamMp3DecoderDecodeFrame was treating minimp3's "can't confirm
a frame here" verdict as genuine garbage even when the window simply
hadn't been topped up yet - discarding real frames whenever one landed
near the tail of a not-yet-full window, since minimp3 needs to also
validate the *next* frame's header to confirm a decode. On a real ~236s
VBR file this silently dropped ~5.5% of frames, heard as the stream
finishing early ("racing") with a stutter at each drop.

Now refills before ever trusting a "not found" verdict as confirmed
garbage, and grows the window from 16KB to 256KB (past the point of
diminishing returns, ~0.3% residual loss). PSP is unaffected - it uses
the hardware sceMp3 decoder, not this file.

Also removes now-unneeded debug instrumentation from the Linux feed
path.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-01 09:43:19 -05:00
YourWishesandClaude Sonnet 5 d9beb647c1 Fix PSP MP3 TopUp trusting requested frame count over actual on short reads
audioStreamPSPTopUp() advanced readPosition/ringFilled/framesEnqueued by
the requested framesToRead regardless of how many frames a short read
actually produced - a leftover assumption from the WAV/PCM design, where
a short read only ever means "truly corrupt file, at the real end."
That doesn't hold for MP3: a hardware decoder backend can plausibly
report "nothing ready this instant" without that meaning no more content
exists. Every such short read silently inflated readPosition ahead of
real decode progress, triggering the loop-segment-end check far too
early - restarting the pass again and again well short of the real
runtime, heard as the clip racing through its own content.

Now only ever advances by the actual frames produced (matching
dusklinux's audioStreamLinuxFeed(), which already did this correctly),
and bases the loop/end decision on real position instead of the
originally-requested read size.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-01 09:16:42 -05:00
YourWishesandClaude Sonnet 5 f8f8a80a21 Add MP3 audio stream support with hardware/software decoder backends
New ASSET_LOADER_TYPE_MP3 (hand-rolled MPEG-1/2/2.5 Layer III header
parser - no third-party dependency needed just for metadata, since PSP's
hardware path doesn't need one at all) plus a shared audiostreammp3.c
stream layer mirroring audiostreampcm.c's shape. Generalized the stream
dispatch (hoisted sampleRate/channels onto audiostream_t, added
audioStreamGetTotalFrames()/Seek()/Read()) so all three platform audio
backends keep working unchanged, just calling the generic names instead
of PCM-specific ones.

Two decoder backends behind one interface: PSP uses the real sceMp3
hardware decoder (firmware-offloaded, lazily initialized on first use);
Linux and Dolphin share one minimp3-based software decoder (public
domain, vendored via CMake FetchContent) - libogc's own MP3Player wraps
libmad (GPL) and drives its own output pipeline, not a fit for the
ansnd-based architecture already in place, so skipped in favor of the
shared minimp3 path.

Fixed three real bugs found via hardware/runtime testing along the way:
- LAME's Xing header counts its own placeholder frame in the declared
  total, which made playback stall permanently one frame short of the
  declared end (looked like "never loops") - fixed by subtracting it.
- sceMp3Decode() can return more PCM than one MPEG frame's worth in a
  single call (PSP's pcmBuf is provisioned for 2x), overflowing the
  shared per-frame decode buffer with no bound check - very intermittent
  corruption/clicking on real hardware. Widened the buffer to the real
  worst case and added an assertion.
- sceMp3ResetPlayPosition()'s exact internal reset semantics aren't
  documented precisely enough to trust for looping - occasionally
  disagreed with the fresh stream position fed right after, clicking at
  the loop boundary about 1 in 3-4 loops. Rewind now fully tears down and
  recreates the decoder instead, the same path already proven correct at
  first Init. Also widened the PSP ring buffer to absorb that now-heavier
  operation, capping each top-up call's own work so the bigger buffer
  doesn't turn into one long blocking decode burst instead.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-01 08:21:30 -05:00
352 changed files with 10222 additions and 2656 deletions

No files matched your search

+2 -1
View File
@@ -106,4 +106,5 @@ yarn.lock
/build* /build*
/assets/test /assets/test
/tools_old /tools_old
/assets/test.png /assets/test.png
/assets/audio/boa.mp3
+29 -13
View File
@@ -8,7 +8,10 @@ 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 ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules) set(CMAKE_MODULE_PATH
${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)
@@ -18,7 +21,9 @@ 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 "No description yet." CACHE STRING "Full description") set(DUSK_GAME_LONG_DESCRIPTION
"No description yet." CACHE STRING "Full description"
)
# Prep cache # Prep cache
set(DUSK_CACHE_TARGET "dusk-target") set(DUSK_CACHE_TARGET "dusk-target")
@@ -32,13 +37,19 @@ 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" CACHE INTERNAL ${DUSK_CACHE_TARGET}) set(DUSK_BUILT_ASSETS_DIR "${DUSK_BUILD_DIR}/built_assets"
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 CACHE INTERNAL ${DUSK_CACHE_TARGET}) set(DUSK_BUILD_BINARY ${DUSK_BUILD_DIR}/Dusk
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" CACHE INTERNAL ${DUSK_CACHE_TARGET}) set(DUSK_ASSETS_ZIP "${DUSK_BUILD_DIR}/dusk.dsk"
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")
@@ -73,7 +84,9 @@ if(DUSK_BUILD_TESTS)
${DUSK_LIBRARY_TARGET_NAME} ${DUSK_LIBRARY_TARGET_NAME}
) )
else() else()
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET}) set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}"
CACHE INTERNAL ${DUSK_CACHE_TARGET}
)
endif() endif()
if(NOT DEFINED DUSK_VERSION) if(NOT DEFINED DUSK_VERSION)
@@ -122,18 +135,21 @@ if(DUSK_BUILD_TESTS)
add_subdirectory(test) add_subdirectory(test)
endif() endif()
# Build assets # Build assets. Runs unconditionally on every build (rather than being
file(GLOB_RECURSE DUSK_ASSET_FILES CONFIGURE_DEPENDS "${DUSK_ASSETS_DIR}/*") # gated behind a custom_command's file-level DEPENDS list) because
add_custom_command( # CONFIGURE_DEPENDS globs only pick up added/removed files on the next
OUTPUT "${DUSK_ASSETS_ZIP}" # CMake configure, so that approach could miss/lag a rebuild behind an
# 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 ${CMAKE_COMMAND} -E rm -f "${DUSK_ASSETS_ZIP}"
COMMAND ${Python3_EXECUTABLE} -m tools.asset.pack COMMAND ${Python3_EXECUTABLE} -m tools.asset.pack
--input "${DUSK_ASSETS_DIR}" --input "${DUSK_ASSETS_DIR}"
--output "${DUSK_ASSETS_ZIP}" --output "${DUSK_ASSETS_ZIP}"
WORKING_DIRECTORY "${DUSK_ROOT_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)
+6 -3
View File
@@ -9,15 +9,18 @@ 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 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
``` ```
`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 sudo apt-get install git build-essential gcc python python-polib python3-pillow python3-dotenv python3-numpy python3-pyqt5 python3-opengl libmad0-dev
``` ```
Arch Linux; Arch Linux;
``` ```
sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl sudo pacman -S git base-devel gcc python python-polib python-pillow python-dotenv python-numpy python-pyqt5 python-opengl libmad
``` ```
Binary file not shown.
Binary file not shown.
@@ -1,7 +1,6 @@
{ {
"items": [ "items": [
// Boot check: make sure a save device is available before handing off // First thing, try and find a save device, used for settings and what not.
// to the main menu.
{ {
"type": "MODAL", "type": "MODAL",
"title": "initial.checking_save.title", "title": "initial.checking_save.title",
@@ -14,13 +13,13 @@
{ {
"type": "SAVE_DEVICE_CHECK", "type": "SAVE_DEVICE_CHECK",
"successMarker": "CONTINUE", "successMarker": "CONTINUE",
"failureMarker": "NO_DEVICE" "failureMarker": "SAVE_DEVICE_NOT_FOUND"
}, },
// No save device found - offer to retry or continue without saving. // No save device found
{ {
"type": "MARKER", "type": "MARKER",
"name": "NO_DEVICE" "name": "SAVE_DEVICE_NOT_FOUND"
}, },
{ {
"type": "MODAL_CLOSE" "type": "MODAL_CLOSE"
@@ -32,7 +31,7 @@
"options": [ "options": [
{ {
"text": "initial.no_device.retry", "text": "initial.no_device.retry",
"marker": "RETRY" "marker": "SAVE_DEVICE_RETRY"
}, },
{ {
"text": "initial.no_device.continue", "text": "initial.no_device.continue",
@@ -41,9 +40,10 @@
] ]
}, },
// Save device not found, user to retry, just close modal and loop
{ {
"type": "MARKER", "type": "MARKER",
"name": "RETRY" "name": "SAVE_DEVICE_RETRY"
}, },
{ {
"type": "MODAL_CLOSE" "type": "MODAL_CLOSE"
@@ -52,8 +52,7 @@
"type": "RESTART" "type": "RESTART"
}, },
// Save device found (or continuing without one) - hand off to the // Save device found (or continuing without one)
// main menu scene.
{ {
"type": "MARKER", "type": "MARKER",
"name": "CONTINUE" "name": "CONTINUE"
@@ -62,8 +61,8 @@
"type": "MODAL_CLOSE" "type": "MODAL_CLOSE"
}, },
{ {
"type": "SCENE", "type": "CUTSCENE",
"sceneType": "MAIN_MENU" "name": "main_menu"
} }
] ]
} }
+140
View File
@@ -0,0 +1,140 @@
{
"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"
}
]
}
Binary file not shown.
@@ -1,92 +0,0 @@
{
"items": [
{
"type": "MODAL",
"title": "main_menu.checking_save.title",
"message": "main_menu.checking_save.message"
},
{
"type": "WAIT",
"seconds": 0.2
},
{
"type": "SAVE_DEVICE_CHECK",
"successMarker": "CONTINUE",
"failureMarker": "NO_DEVICE"
},
// No save device found - offer to retry or continue without saving.
{
"type": "MARKER",
"name": "NO_DEVICE"
},
{
"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": "RETRY"
},
{
"text": "main_menu.no_device.continue",
"marker": "CONTINUE"
}
]
},
// Retry
{
"type": "MARKER",
"name": "RETRY"
},
{
"type": "MODAL_CLOSE"
},
{
"type": "RESTART"
},
// Save device found - attempt to load all save slots.
{
"type": "MARKER",
"name": "CONTINUE"
},
{
"type": "MODAL_CLOSE"
},
{
"type": "SAVE_LOAD_ALL_SLOTS",
"successMarker": "LOADED",
"failureMarker": "LOAD_ERROR"
},
// 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": "RETRY"
}
]
},
{
"type": "MARKER",
"name": "LOADED"
}
]
}
+32
View File
@@ -0,0 +1,32 @@
# 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()
+2 -1
View File
@@ -61,7 +61,8 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
zstd zstd
z z
lzma lzma
ansnd asnd
mad
) )
if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO") if(DUSK_DOLPHIN_BUILD_TYPE STREQUAL "ISO")
+1
View File
@@ -30,6 +30,7 @@ target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
pspgu pspgu
pspaudio pspaudio
pspaudiolib pspaudiolib
pspmp3
psputility psputility
pspvfpu pspvfpu
pspvram pspvram
+1 -1
View File
@@ -5,7 +5,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
) )
# Wii save storage method - see src/duskdolphin/save/savedeviceplatform.h. # Wii save storage method - see src/duskdolphin/save/savedeviceplatform.h.
set(DUSK_SAVE_WII_METHOD "NAND" CACHE STRING set(DUSK_SAVE_WII_METHOD "SD" CACHE STRING
"Wii save storage: NAND (internal storage via ISFS), CARD (GameCube-\ "Wii save storage: NAND (internal storage via ISFS), CARD (GameCube-\
compatible memory card emulation), or SD (SD card via libfat)" compatible memory card emulation), or SD (SD card via libfat)"
) )
+7 -2
View File
@@ -13,6 +13,7 @@ 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)
@@ -24,7 +25,11 @@ elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
add_subdirectory(dusksdl2) add_subdirectory(dusksdl2)
add_subdirectory(duskgl) add_subdirectory(duskgl)
elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube") elseif(
DUSK_TARGET_SYSTEM STREQUAL "wii" OR
DUSK_TARGET_SYSTEM STREQUAL "gamecube"
)
add_subdirectory(duskdolphin) add_subdirectory(duskdolphin)
add_subdirectory(duskmad)
endif() endif()
+6 -2
View File
@@ -26,7 +26,9 @@ if(NOT stb_image_FOUND)
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 "stb_image not found. Please ensure stb is correctly fetched.") message(FATAL_ERROR
"stb_image not found. Please ensure stb is correctly fetched."
)
endif() endif()
endif() endif()
@@ -35,7 +37,9 @@ 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 "yyjson not found. Please ensure yyjson is correctly fetched.") message(FATAL_ERROR
"yyjson not found. Please ensure yyjson is correctly fetched."
)
endif() endif()
endif() endif()
+11 -9
View File
@@ -1,7 +1,9 @@
// Copyright (c) 2026 Dominic Masters /**
// * Copyright (c) 2026 Dominic Masters
// This software is released under the MIT License. *
// https://opensource.org/licenses/MIT * This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "animation.h" #include "animation.h"
#include "assert/assert.h" #include "assert/assert.h"
@@ -14,9 +16,9 @@ void animationInit(
uint16_t *keyframeCounts, uint16_t *keyframeCounts,
const uint16_t layerCount const uint16_t layerCount
) { ) {
assertNotNull(anim, "Animation pointer cannot be null."); assertNotNull(anim, "Animation pointer cannot be NULL.");
assertNotNull(keyframes, "Keyframes pointer cannot be null."); assertNotNull(keyframes, "Keyframes pointer cannot be NULL.");
assertNotNull(keyframeCounts, "Keyframe counts pointer cannot be null."); assertNotNull(keyframeCounts, "Keyframe counts pointer cannot be NULL.");
assertTrue(layerCount > 0, "Layer count must be greater than zero."); assertTrue(layerCount > 0, "Layer count must be greater than zero.");
memoryZero(anim, sizeof(animation_t)); memoryZero(anim, sizeof(animation_t));
@@ -49,7 +51,7 @@ void animationInit(
} }
float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer) { float_t animationGetLayerValue(const animation_t *anim, const uint16_t layer) {
assertNotNull(anim, "Animation pointer cannot be null."); assertNotNull(anim, "Animation pointer cannot be NULL.");
assertTrue(layer < anim->layerCount, "Layer index out of bounds."); assertTrue(layer < anim->layerCount, "Layer index out of bounds.");
uint16_t keyframeCount = anim->keyframeCounts[layer]; uint16_t keyframeCount = anim->keyframeCounts[layer];
@@ -61,7 +63,7 @@ void animationUpdate(
animation_t *anim, animation_t *anim,
const float_t deltaTime const float_t deltaTime
) { ) {
assertNotNull(anim, "Animation pointer cannot be null."); assertNotNull(anim, "Animation pointer cannot be NULL.");
assertTrue(deltaTime >= 0, "Delta time must be non-negative."); assertTrue(deltaTime >= 0, "Delta time must be non-negative.");
bool_t justCompleted = false; bool_t justCompleted = false;
+6 -4
View File
@@ -1,7 +1,9 @@
// Copyright (c) 2026 Dominic Masters /**
// * Copyright (c) 2026 Dominic Masters
// This software is released under the MIT License. *
// https://opensource.org/licenses/MIT * This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once #pragma once
#include "keyframe.h" #include "keyframe.h"
+6 -4
View File
@@ -1,7 +1,9 @@
// Copyright (c) 2026 Dominic Masters /**
// * Copyright (c) 2026 Dominic Masters
// This software is released under the MIT License. *
// https://opensource.org/licenses/MIT * This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "easing.h" #include "easing.h"
#include "assert/assert.h" #include "assert/assert.h"
+123 -4
View File
@@ -1,7 +1,9 @@
// Copyright (c) 2026 Dominic Masters /**
// * Copyright (c) 2026 Dominic Masters
// This software is released under the MIT License. *
// https://opensource.org/licenses/MIT * This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once #pragma once
#include "dusk.h" #include "dusk.h"
@@ -45,19 +47,136 @@ 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 -1
View File
@@ -14,7 +14,7 @@ float_t keyframeGetValue(
const uint32_t keyframeCount, const uint32_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 #ifdef DUSK_ASSERTIONS
+6 -4
View File
@@ -1,7 +1,9 @@
// Copyright (c) 2026 Dominic Masters /**
// * Copyright (c) 2026 Dominic Masters
// This software is released under the MIT License. *
// https://opensource.org/licenses/MIT * This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once #pragma once
#include "easing.h" #include "easing.h"
+5 -3
View File
@@ -28,8 +28,8 @@ errorret_t assetInit(void) {
// assetInitPlatform must either define both ASSET.zip/ASSET.zipStored or // assetInitPlatform must either define both ASSET.zip/ASSET.zipStored 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."); assertNotNull(ASSET.zipStored, "Asset stored zip NULL without error.");
threadInit(&ASSET.loadThread, assetUpdateAsync); threadInit(&ASSET.loadThread, assetUpdateAsync);
threadStart(&ASSET.loadThread); threadStart(&ASSET.loadThread);
@@ -364,7 +364,9 @@ 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) errEntry->onError(errEntry, errEntry->onErrorUser); if(errEntry->onError) {
errEntry->onError(errEntry, errEntry->onErrorUser);
}
loading++; loading++;
break; break;
} }
+13
View File
@@ -26,6 +26,8 @@
#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 // Compressed (DEFLATE) archive - expected to hold the bulk of a game's
// binary assets. Looked up first by assetFileInit(). // binary assets. Looked up first by assetFileInit().
@@ -37,6 +39,17 @@ typedef struct asset_s {
// assetFileInit() only if the name isn't found in `zip`. // assetFileInit() only if the name isn't found in `zip`.
zip_t *zipStored; 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, // Guards every libzip call against ASSET.zip/ASSET.zipStored (zip_fopen,
+31 -14
View File
@@ -114,15 +114,18 @@ errorret_t assetDskOpenFromPathRange(
); );
if(compressedSource == NULL) { if(compressedSource == NULL) {
errorThrow( errorThrow(
"Failed to create compressed dusk.dsk source: %s", zip_error_strerror(&zipError) "Failed to create compressed dusk.dsk source: %s",
zip_error_strerror(&zipError)
); );
} }
*outCompressed = zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError); *outCompressed =
zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError);
if(*outCompressed == NULL) { if(*outCompressed == NULL) {
zip_source_free(compressedSource); zip_source_free(compressedSource);
errorThrow( errorThrow(
"Failed to open compressed dusk.dsk archive: %s", zip_error_strerror(&zipError) "Failed to open compressed dusk.dsk archive: %s",
zip_error_strerror(&zipError)
); );
} }
@@ -136,7 +139,8 @@ errorret_t assetDskOpenFromPathRange(
zip_close(*outCompressed); zip_close(*outCompressed);
*outCompressed = NULL; *outCompressed = NULL;
errorThrow( errorThrow(
"Failed to create stored dusk.dsk source: %s", zip_error_strerror(&zipError) "Failed to create stored dusk.dsk source: %s",
zip_error_strerror(&zipError)
); );
} }
@@ -146,7 +150,8 @@ errorret_t assetDskOpenFromPathRange(
zip_close(*outCompressed); zip_close(*outCompressed);
*outCompressed = NULL; *outCompressed = NULL;
errorThrow( errorThrow(
"Failed to open stored dusk.dsk archive: %s", zip_error_strerror(&zipError) "Failed to open stored dusk.dsk archive: %s",
zip_error_strerror(&zipError)
); );
} }
@@ -161,7 +166,9 @@ errorret_t assetDskOpenFromPathRange(
zip_close(*outCompressed); zip_close(*outCompressed);
*outStored = NULL; *outStored = NULL;
*outCompressed = NULL; *outCompressed = NULL;
errorThrow("Failed to re-open dusk.dsk to verify stored checksum: %s", path); errorThrow(
"Failed to re-open dusk.dsk to verify stored checksum: %s", path
);
} }
fseek(storedFile, (long) (baseOffset + header.storedOffset), SEEK_SET); fseek(storedFile, (long) (baseOffset + header.storedOffset), SEEK_SET);
size_t storedRead = fread(storedBytes, 1, header.storedSize, storedFile); size_t storedRead = fread(storedBytes, 1, header.storedSize, storedFile);
@@ -172,17 +179,22 @@ errorret_t assetDskOpenFromPathRange(
zip_close(*outCompressed); zip_close(*outCompressed);
*outStored = NULL; *outStored = NULL;
*outCompressed = NULL; *outCompressed = NULL;
errorThrow("Failed to read dusk.dsk stored archive to verify checksum: %s", path); errorThrow(
"Failed to read dusk.dsk stored archive to verify checksum: %s", path
);
} }
uint32_t checksum = (uint32_t) crc32(0L, storedBytes, (uInt) header.storedSize); uint32_t checksum =
(uint32_t) crc32(0L, storedBytes, (uInt) header.storedSize);
memoryFree(storedBytes); memoryFree(storedBytes);
if(checksum != header.storedChecksum) { if(checksum != header.storedChecksum) {
zip_close(*outStored); zip_close(*outStored);
zip_close(*outCompressed); zip_close(*outCompressed);
*outStored = NULL; *outStored = NULL;
*outCompressed = NULL; *outCompressed = NULL;
errorThrow("dusk.dsk stored archive failed checksum verification: %s", path); errorThrow(
"dusk.dsk stored archive failed checksum verification: %s", path
);
} }
errorOk(); errorOk();
@@ -235,15 +247,18 @@ errorret_t assetDskOpenFromBuffer(
); );
if(compressedSource == NULL) { if(compressedSource == NULL) {
errorThrow( errorThrow(
"Failed to create compressed dusk.dsk source: %s", zip_error_strerror(&zipError) "Failed to create compressed dusk.dsk source: %s",
zip_error_strerror(&zipError)
); );
} }
*outCompressed = zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError); *outCompressed =
zip_open_from_source(compressedSource, ZIP_RDONLY, &zipError);
if(*outCompressed == NULL) { if(*outCompressed == NULL) {
zip_source_free(compressedSource); zip_source_free(compressedSource);
errorThrow( errorThrow(
"Failed to open compressed dusk.dsk archive: %s", zip_error_strerror(&zipError) "Failed to open compressed dusk.dsk archive: %s",
zip_error_strerror(&zipError)
); );
} }
@@ -254,7 +269,8 @@ errorret_t assetDskOpenFromBuffer(
zip_close(*outCompressed); zip_close(*outCompressed);
*outCompressed = NULL; *outCompressed = NULL;
errorThrow( errorThrow(
"Failed to create stored dusk.dsk source: %s", zip_error_strerror(&zipError) "Failed to create stored dusk.dsk source: %s",
zip_error_strerror(&zipError)
); );
} }
@@ -264,7 +280,8 @@ errorret_t assetDskOpenFromBuffer(
zip_close(*outCompressed); zip_close(*outCompressed);
*outCompressed = NULL; *outCompressed = NULL;
errorThrow( errorThrow(
"Failed to open stored dusk.dsk archive: %s", zip_error_strerror(&zipError) "Failed to open stored dusk.dsk archive: %s",
zip_error_strerror(&zipError)
); );
} }
+9 -13
View File
@@ -279,7 +279,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.");
} }
@@ -328,7 +328,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,18 +349,14 @@ errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader) {
errorOk(); errorOk();
} }
/* // There are unread bytes left but no newline in them.
* There are unread bytes left but no newline in them. // If bufferStart > 0, slide unread bytes to front so we can read more.
* If bufferStart > 0, slide unread bytes to front so we can read more. // This only happens when necessary to make space.
* 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.
* Entire read buffer is unread and contains no newline. // Caller must have a large enough outBuffer to accumulate across fills,
* Caller must have a large enough outBuffer to accumulate across fills, // so we consume these bytes into outBuffer before refilling.
* so we consume these bytes into outBuffer before refilling.
*/
errorOk(); errorOk();
} }
@@ -403,7 +399,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'
+2 -1
View File
@@ -18,4 +18,5 @@ add_subdirectory(json)
add_subdirectory(chunk) add_subdirectory(chunk)
add_subdirectory(dmf) add_subdirectory(dmf)
add_subdirectory(cutscene) add_subdirectory(cutscene)
add_subdirectory(wav) add_subdirectory(wav)
add_subdirectory(mp3)
+6
View File
@@ -63,4 +63,10 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
.loadAsync = assetWavLoaderAsync, .loadAsync = assetWavLoaderAsync,
.dispose = assetWavDispose .dispose = assetWavDispose
}, },
[ASSET_LOADER_TYPE_MP3] = {
.loadSync = assetMp3LoaderSync,
.loadAsync = assetMp3LoaderAsync,
.dispose = assetMp3Dispose
},
}; };
+5
View File
@@ -15,6 +15,7 @@
#include "asset/loader/chunk/assetchunkloader.h" #include "asset/loader/chunk/assetchunkloader.h"
#include "asset/loader/cutscene/assetcutsceneloader.h" #include "asset/loader/cutscene/assetcutsceneloader.h"
#include "asset/loader/wav/assetwavloader.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,
@@ -28,6 +29,7 @@ typedef enum {
ASSET_LOADER_TYPE_CHUNK, ASSET_LOADER_TYPE_CHUNK,
ASSET_LOADER_TYPE_CUTSCENE, ASSET_LOADER_TYPE_CUTSCENE,
ASSET_LOADER_TYPE_WAV, ASSET_LOADER_TYPE_WAV,
ASSET_LOADER_TYPE_MP3,
ASSET_LOADER_TYPE_COUNT ASSET_LOADER_TYPE_COUNT
} assetloadertype_t; } assetloadertype_t;
@@ -42,6 +44,7 @@ typedef union {
assetchunkloaderloading_t chunk; assetchunkloaderloading_t chunk;
assetcutsceneloaderloading_t cutscene; assetcutsceneloaderloading_t cutscene;
assetwavloaderloading_t wav; assetwavloaderloading_t wav;
assetmp3loaderloading_t mp3;
} assetloaderloading_t; } assetloaderloading_t;
typedef union { typedef union {
@@ -54,6 +57,7 @@ typedef union {
assetchunkoutput_t chunk; assetchunkoutput_t chunk;
assetcutsceneoutput_t cutscene; assetcutsceneoutput_t cutscene;
assetwavoutput_t wav; assetwavoutput_t wav;
assetmp3output_t mp3;
} assetloaderoutput_t; } assetloaderoutput_t;
typedef union { typedef union {
@@ -64,6 +68,7 @@ typedef union {
assetchunkloaderinput_t chunk; assetchunkloaderinput_t chunk;
assetcutsceneloaderinput_t cutscene; assetcutsceneloaderinput_t cutscene;
assetwavloaderinput_t wav; assetwavloaderinput_t wav;
assetmp3loaderinput_t mp3;
} assetloaderinput_t; } assetloaderinput_t;
typedef struct assetloading_s assetloading_t; typedef struct assetloading_s assetloading_t;
@@ -8,103 +8,125 @@
#include "assetcutsceneloader.h" #include "assetcutsceneloader.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/endian.h" #include "util/string.h"
#include "asset/loader/assetloading.h" #include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h" #include "asset/loader/assetentry.h"
#include "asset/loader/assetloader.h" #include "asset/loader/assetloader.h"
#include "asset/asset.h" #include "asset/asset.h"
#include "rpg/overworld/worldpos.h" #include "rpg/cutscene/item/json/cutscenejsonpauseflags.h"
// DCTS header: magic "DCTS" (4), version u32 LE (4), pauseType u8 (1), errorret_t assetCutsceneParseItem(
// itemCount u8 (1), poolSize u16 LE (2) = 12 bytes. assetloading_t *loading,
#define ASSET_CUTSCENE_HEADER_SIZE 12 yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t assetCutsceneReadU8(const uint8_t *data, size_t *offset) { uint8_t *pool,
uint8_t value = data[*offset]; size_t *poolOffset,
*offset += sizeof(uint8_t); const uint8_t index
return value;
}
uint16_t assetCutsceneReadU16(const uint8_t *data, size_t *offset) {
uint16_t value;
memoryCopy(&value, data + *offset, sizeof(uint16_t));
*offset += sizeof(uint16_t);
return endianLittleToHost16(value);
}
uint32_t assetCutsceneReadU32(const uint8_t *data, size_t *offset) {
uint32_t value;
memoryCopy(&value, data + *offset, sizeof(uint32_t));
*offset += sizeof(uint32_t);
return endianLittleToHost32(value);
}
float_t assetCutsceneReadFloat(const uint8_t *data, size_t *offset) {
float_t value;
memoryCopy(&value, data + *offset, sizeof(float_t));
*offset += sizeof(float_t);
return endianLittleToHostFloat(value);
}
// Copies a length-prefixed string directly into an item's own embedded
// char_t[destCapacity] field (CUTSCENE_TEXT_MAX_CHARS and friends) - these
// are never pool references, see the item-field inventory in the runtime
// cutscene file design.
void assetCutsceneReadEmbeddedString(
const uint8_t *data,
size_t *offset,
char_t *dest,
const size_t destCapacity
) { ) {
uint8_t len = assetCutsceneReadU8(data, offset); if(!yyjson_is_obj(itemObj)) {
assertTrue(len < destCapacity, "Cutscene string exceeds field capacity"); assetLoaderErrorThrow(
memoryCopy(dest, data + *offset, len); loading,
dest[len] = '\0'; "Cutscene item %u is not an object",
*offset += len; (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();
} }
// Resolves a u16 pool offset (read from the item stream) to a real pointer size_t assetCutsceneComputePoolSize(yyjson_val *itemsArr) {
// into the entry's own persistent pool allocation. size_t size = 0;
const char_t * assetCutsceneReadPoolString( yyjson_arr_iter iter = yyjson_arr_iter_with(itemsArr);
const uint8_t *data, yyjson_val *itemVal;
size_t *offset, while((itemVal = yyjson_arr_iter_next(&iter)) != NULL) {
const char_t *pool const char_t *typeName = yyjson_get_str(yyjson_obj_get(itemVal, "type"));
) { cutsceneitemtype_t type;
uint16_t poolOffset = assetCutsceneReadU16(data, offset); if(!cutsceneItemLookupType(typeName, &type)) continue;
return pool + poolOffset;
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) { errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread."); assertNotMainThread("Should be called from an async thread.");
if(loading->loading.cutscene.state != ASSET_CUTSCENE_LOADING_STATE_READ_FILE) { if(
loading->loading.cutscene.state != ASSET_CUTSCENE_LOADING_STATE_READ_FILE
) {
errorOk(); errorOk();
} }
assertNull(loading->loading.cutscene.data, "Data already defined?"); assertNull(loading->loading.cutscene.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.cutscene.file; assetfile_t *file = &loading->loading.cutscene.file;
assetLoaderErrorChain(loading, assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL) assetFileInit(file, loading->entry->name, NULL, NULL)
); );
uint8_t *data = memoryAllocate(file->size); 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, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size)); assetLoaderErrorChain(loading, assetFileRead(file, buffer, fileSize));
assertTrue( assertTrue(
file->lastRead == file->size, file->lastRead == file->size,
"Failed to read entire cutscene file." "Failed to read entire cutscene file."
); );
// Saved before assetFileDispose zeroes the whole assetfile_t struct
// (including .size) - the sync phase needs the file's total length to
// locate the pool region, which starts poolSize bytes before the end.
loading->loading.cutscene.dataSize = (size_t)file->size;
assetLoaderErrorChain(loading, assetFileClose(file)); assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file)); assetLoaderErrorChain(loading, assetFileDispose(file));
loading->loading.cutscene.data = data; loading->loading.cutscene.buffer = buffer;
loading->loading.cutscene.size = fileSize;
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE; loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC; loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk(); errorOk();
@@ -122,306 +144,70 @@ errorret_t assetCutsceneLoaderSync(assetloading_t *loading) {
} }
assetcutsceneoutput_t *out = &loading->entry->data.cutscene; assetcutsceneoutput_t *out = &loading->entry->data.cutscene;
uint8_t *data = loading->loading.cutscene.data; uint8_t *buffer = loading->loading.cutscene.buffer;
assertNotNull(data, "Cutscene data should have been loaded by now."); assertNotNull(buffer, "Cutscene data should have been loaded by now.");
size_t bufferSize = loading->loading.cutscene.size;
size_t fileSize = loading->loading.cutscene.dataSize; 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(data[0] != 'D' || data[1] != 'C' || data[2] != 'T' || data[3] != 'S') { if(doc == NULL) {
memoryFree(data); assetLoaderErrorThrow(loading, "Failed to parse cutscene JSON");
assetLoaderErrorThrow(loading, "Invalid cutscene file header"); }
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 offset = 4; size_t itemCount = yyjson_arr_size(itemsArr);
uint32_t version = assetCutsceneReadU32(data, &offset); if(itemCount > UINT8_MAX) {
if(version != ASSET_CUTSCENE_FILE_VERSION) { assetCutsceneFreeParsed(out);
memoryFree(data); assetLoaderErrorThrow(loading, "Cutscene has more than 255 items");
assetLoaderErrorThrow(
loading, "Unsupported cutscene file version %u", version
);
} }
cutscenepause_t pauseType = (cutscenepause_t)assetCutsceneReadU8(data, &offset); cutscenepause_t pause = CUTSCENE_PAUSE_DEFAULT;
uint8_t itemCount = assetCutsceneReadU8(data, &offset); yyjson_val *pauseArr = yyjson_obj_get(root, "pause");
uint16_t poolSize = assetCutsceneReadU16(data, &offset); if(yyjson_is_arr(pauseArr)) {
assertTrue(offset == ASSET_CUTSCENE_HEADER_SIZE, "Cutscene header size mismatch"); if(!cutsceneJsonParsePauseFlags(pauseArr, &pause)) {
assetCutsceneFreeParsed(out);
out->pool = poolSize > 0 ? memoryAllocate(poolSize) : NULL; assetLoaderErrorThrow(
if(poolSize > 0) { loading, "Cutscene JSON has an invalid 'pause' flag"
size_t poolStart = fileSize - (size_t)poolSize; );
memoryCopy(out->pool, data + poolStart, poolSize); }
} }
const char_t *pool = out->pool;
out->items = memoryAllocate(itemCount * sizeof(cutsceneitem_t)); out->items = memoryAllocate(itemCount * sizeof(cutsceneitem_t));
memoryZero(out->items, itemCount * sizeof(cutsceneitem_t)); memoryZero(out->items, itemCount * sizeof(cutsceneitem_t));
for(uint8_t i = 0; i < itemCount; i++) { size_t poolSize = assetCutsceneComputePoolSize(itemsArr);
cutsceneitem_t *item = &out->items[i]; out->pool = poolSize > 0 ? memoryAllocate(poolSize) : NULL;
item->type = (cutsceneitemtype_t)assetCutsceneReadU8(data, &offset);
switch(item->type) { size_t poolOffset = 0;
case CUTSCENE_ITEM_TYPE_TEXT: yyjson_arr_iter itemIter = yyjson_arr_iter_with(itemsArr);
assetCutsceneReadEmbeddedString( yyjson_val *itemVal;
data, &offset, item->text.text, CUTSCENE_TEXT_MAX_CHARS uint8_t index = 0;
); while((itemVal = yyjson_arr_iter_next(&itemIter)) != NULL) {
break; errorret_t itemResult = assetCutsceneParseItem(
loading, itemVal, &out->items[index], out->pool, &poolOffset, index
case CUTSCENE_ITEM_TYPE_TEXT_MINI: );
assetCutsceneReadEmbeddedString( if(errorIsNotOk(itemResult)) {
data, &offset, item->textMini.text, CUTSCENE_TEXT_MINI_MAX_CHARS assetCutsceneFreeParsed(out);
); errorChain(itemResult);
item->textMini.position[0] = assetCutsceneReadFloat(data, &offset);
item->textMini.position[1] = assetCutsceneReadFloat(data, &offset);
item->textMini.position[2] = assetCutsceneReadFloat(data, &offset);
item->textMini.duration = assetCutsceneReadFloat(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE:
item->textMiniHide.index = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_WAIT:
item->wait = assetCutsceneReadFloat(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT:
item->entityTeleport.entityIndex = assetCutsceneReadU8(data, &offset);
item->entityTeleport.target = worldPosReadLE(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO: {
item->entityWalkTo.entityIndex = assetCutsceneReadU8(data, &offset);
item->entityWalkTo.walkAround = assetCutsceneReadU8(data, &offset) != 0;
uint8_t count = assetCutsceneReadU8(data, &offset);
uint16_t poolOffset = assetCutsceneReadU16(data, &offset);
item->entityWalkTo.count = count;
item->entityWalkTo.positions = (const worldpos_t *)(pool + poolOffset);
break;
}
case CUTSCENE_ITEM_TYPE_FADE:
item->fade.from.r = assetCutsceneReadU8(data, &offset);
item->fade.from.g = assetCutsceneReadU8(data, &offset);
item->fade.from.b = assetCutsceneReadU8(data, &offset);
item->fade.from.a = assetCutsceneReadU8(data, &offset);
item->fade.to.r = assetCutsceneReadU8(data, &offset);
item->fade.to.g = assetCutsceneReadU8(data, &offset);
item->fade.to.b = assetCutsceneReadU8(data, &offset);
item->fade.to.a = assetCutsceneReadU8(data, &offset);
item->fade.duration = assetCutsceneReadFloat(data, &offset);
item->fade.easing = (easingtype_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_SET_PAUSE:
item->setPause = (cutscenepause_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ITEM_GIVE:
item->itemGive.item = (itemid_t)assetCutsceneReadU16(data, &offset);
item->itemGive.quantity = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_REMOVE:
item->entityRemove.entityIndex = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_ADD:
item->entityAdd.entityType = assetCutsceneReadU8(data, &offset);
item->entityAdd.position = worldPosReadLE(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_TURN:
item->entityTurn.entityIndex = assetCutsceneReadU8(data, &offset);
item->entityTurn.direction =
(entitydir_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY:
item->entityWalkToEntity.entityIndex =
assetCutsceneReadU8(data, &offset);
item->entityWalkToEntity.targetEntityIndex =
assetCutsceneReadU8(data, &offset);
item->entityWalkToEntity.offsetX =
worldUnitReadLE(data, &offset);
item->entityWalkToEntity.offsetY =
worldUnitReadLE(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE:
item->mapAreaRemove.areaId = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT: {
uint8_t count = assetCutsceneReadU8(data, &offset);
uint16_t poolOffset = assetCutsceneReadU16(data, &offset);
assertTrue(
count <= CUTSCENE_MAP_AREA_WAIT_MAX,
"Cutscene map area wait count exceeds maximum"
);
item->mapAreaWait.count = count;
item->mapAreaWait.areaIds = (const uint8_t *)(pool + poolOffset);
break;
}
case CUTSCENE_ITEM_TYPE_START_BATTLE: {
item->startBattle.encounterType =
(battleencountertype_t)assetCutsceneReadU8(data, &offset);
item->startBattle.fleeAvailable =
assetCutsceneReadU8(data, &offset) != 0;
uint8_t enemyCount = assetCutsceneReadU8(data, &offset);
assertTrue(
enemyCount <= CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX,
"Cutscene battle enemy count exceeds maximum"
);
item->startBattle.enemyCount = enemyCount;
for(uint8_t e = 0; e < enemyCount; e++) {
cutscenestartbattleenemy_t *enemy = &item->startBattle.enemies[e];
enemy->stats.attack = assetCutsceneReadU16(data, &offset);
enemy->stats.defense = assetCutsceneReadU16(data, &offset);
enemy->stats.magic = assetCutsceneReadU16(data, &offset);
enemy->stats.speed = assetCutsceneReadU16(data, &offset);
enemy->stats.luck = assetCutsceneReadU16(data, &offset);
enemy->healthMax = assetCutsceneReadU16(data, &offset);
enemy->mpMax = assetCutsceneReadU16(data, &offset);
}
break;
}
case CUTSCENE_ITEM_TYPE_EMOJI:
item->emoji.entityIndex = assetCutsceneReadU8(data, &offset);
item->emoji.duration = assetCutsceneReadFloat(data, &offset);
item->emoji.emojiType = (uiemojitype_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_SHAKE:
item->shake.amount = assetCutsceneReadU8(data, &offset);
item->shake.duration = assetCutsceneReadFloat(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE:
item->battleWaitState.state =
(battlestate_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION:
item->battleForceAction.fighterIndex = assetCutsceneReadU8(data, &offset);
item->battleForceAction.targetIndex = assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_MODAL: {
assetCutsceneReadEmbeddedString(
data, &offset, item->modal.title, CUTSCENE_MODAL_TITLE_MAX_CHARS
);
assetCutsceneReadEmbeddedString(
data, &offset, item->modal.message, CUTSCENE_MODAL_MESSAGE_MAX_CHARS
);
// v1 only supports the message-only form: MODAL and MODAL_OPTIONS
// share this same tag with no separate discriminator, and there is
// no native-callback registry yet to resolve an options callback.
// Read into a local first (not inline in the check below) - on a
// release build with DUSK_ASSERTIONS_FAKED, an assert's condition
// is never evaluated at all, so a byte-consuming call inside one
// would silently desync every item after it. This is untrusted
// file content anyway, so it gets a real error, not an assert.
uint8_t optionCount = assetCutsceneReadU8(data, &offset);
if(optionCount != 0) {
memoryFree(data);
memoryFree(out->items);
out->items = NULL;
if(out->pool != NULL) {
memoryFree(out->pool);
out->pool = NULL;
}
assetLoaderErrorThrow(
loading,
"Cutscene MODAL item with options is not supported in "
"file-based cutscenes yet - use MODAL_OPTIONS_MARKERS instead"
);
}
break;
}
case CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS: {
assetCutsceneReadEmbeddedString(
data, &offset, item->modalOptionsMarkers.title,
CUTSCENE_MODAL_TITLE_MAX_CHARS
);
assetCutsceneReadEmbeddedString(
data, &offset, item->modalOptionsMarkers.message,
CUTSCENE_MODAL_MESSAGE_MAX_CHARS
);
uint8_t optionCount = assetCutsceneReadU8(data, &offset);
assertTrue(
optionCount <= CUTSCENE_MODAL_OPTIONS_MARKERS_MAX,
"Cutscene modal option count exceeds maximum"
);
item->modalOptionsMarkers.optionCount = optionCount;
for(uint8_t o = 0; o < optionCount; o++) {
item->modalOptionsMarkers.options[o] =
assetCutsceneReadPoolString(data, &offset, pool);
item->modalOptionsMarkers.markers[o] =
assetCutsceneReadPoolString(data, &offset, pool);
}
break;
}
case CUTSCENE_ITEM_TYPE_MODAL_CLOSE:
case CUTSCENE_ITEM_TYPE_RESTART:
break;
case CUTSCENE_ITEM_TYPE_PRINT:
assetCutsceneReadEmbeddedString(
data, &offset, item->print.text, CUTSCENE_PRINT_MAX_CHARS
);
break;
case CUTSCENE_ITEM_TYPE_MARKER:
item->marker.name = assetCutsceneReadPoolString(data, &offset, pool);
break;
case CUTSCENE_ITEM_TYPE_SCENE:
item->sceneChange.type = (scenetype_t)assetCutsceneReadU8(data, &offset);
break;
case CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK:
item->saveDeviceCheck.successMarker =
assetCutsceneReadPoolString(data, &offset, pool);
item->saveDeviceCheck.failureMarker =
assetCutsceneReadPoolString(data, &offset, pool);
break;
case CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS:
item->saveLoadAllSlots.successMarker =
assetCutsceneReadPoolString(data, &offset, pool);
item->saveLoadAllSlots.failureMarker =
assetCutsceneReadPoolString(data, &offset, pool);
break;
default:
memoryFree(data);
memoryFree(out->items);
out->items = NULL;
if(out->pool != NULL) {
memoryFree(out->pool);
out->pool = NULL;
}
assetLoaderErrorThrow(
loading,
"Cutscene item type %u is not supported in file-based cutscenes "
"(item %u/%u, offset %u/%u, poolSize %u)",
(uint32_t)item->type, (uint32_t)i, (uint32_t)itemCount,
(uint32_t)offset, (uint32_t)fileSize, (uint32_t)poolSize
);
} }
index++;
} }
memoryFree(data);
loading->loading.cutscene.data = NULL;
out->cutscene.items = out->items; out->cutscene.items = out->items;
out->cutscene.itemCount = itemCount; out->cutscene.itemCount = (uint8_t)itemCount;
out->cutscene.pause = pauseType; out->cutscene.pause = pause;
out->cutscene.dataSize = 0; out->cutscene.dataSize = 0;
loading->entry->state = ASSET_ENTRY_STATE_LOADED; loading->entry->state = ASSET_ENTRY_STATE_LOADED;
@@ -433,17 +219,7 @@ errorret_t assetCutsceneDispose(assetentry_t *entry) {
assertTrue(entry->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type."); assertTrue(entry->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
assertIsMainThread("Must be called from the main thread."); assertIsMainThread("Must be called from the main thread.");
assetcutsceneoutput_t *out = &entry->data.cutscene; assetCutsceneFreeParsed(&entry->data.cutscene);
if(out->items != NULL) {
memoryFree(out->items);
out->items = NULL;
}
if(out->pool != NULL) {
memoryFree(out->pool);
out->pool = NULL;
}
errorOk(); errorOk();
} }
@@ -9,8 +9,10 @@
#include "asset/assetfile.h" #include "asset/assetfile.h"
#include "rpg/cutscene/cutscene.h" #include "rpg/cutscene/cutscene.h"
#include "rpg/cutscene/item/cutsceneitem.h" #include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/item/json/cutscenejsonpool.h"
#include "yyjson.h"
#define ASSET_CUTSCENE_FILE_VERSION 1 #define ASSET_CUTSCENE_FILE_SIZE_MAX (1024 * 64)
typedef struct assetloading_s assetloading_t; typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t; typedef struct assetentry_s assetentry_t;
@@ -28,94 +30,56 @@ typedef enum {
typedef struct { typedef struct {
assetfile_t file; assetfile_t file;
assetcutsceneloadingstate_t state; assetcutsceneloadingstate_t state;
uint8_t *data; uint8_t *buffer;
size_t dataSize;// Saved before assetFileDispose zeroes file.size. size_t size;
} assetcutsceneloaderloading_t; } assetcutsceneloaderloading_t;
// Runtime-loaded cutscene: items/pool are heap-allocated to the file's
// actual declared sizes (not fixed-capacity), so an entry that never holds
// a cutscene costs nothing extra in the shared assetloaderoutput_t union -
// see assetchunkoutput_t.tiles for the same pattern.
typedef struct { typedef struct {
cutscene_t cutscene; // .items points at the items array below cutscene_t cutscene;
cutsceneitem_t *items; cutsceneitem_t *items;
char_t *pool; uint8_t *pool;
yyjson_doc *doc;
} assetcutsceneoutput_t; } assetcutsceneoutput_t;
/** /**
* Reads a uint8_t from the current offset, advancing *offset past it. * 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 data The buffer to read from. * @param loading Loading information for the asset being loaded.
* @param offset In/out cursor into data, advanced past the value read. * @param itemObj The item's JSON object.
* @return The decoded uint8_t. * @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.
*/ */
uint8_t assetCutsceneReadU8(const uint8_t *data, size_t *offset); errorret_t assetCutsceneParseItem(
assetloading_t *loading,
/** yyjson_val *itemObj,
* Reads a little-endian uint16_t from a potentially-unaligned offset, cutsceneitem_t *item,
* advancing *offset past it. uint8_t *pool,
* size_t *poolOffset,
* @param data The buffer to read from. const uint8_t index
* @param offset In/out cursor into data, advanced past the value read.
* @return The decoded uint16_t.
*/
uint16_t assetCutsceneReadU16(const uint8_t *data, size_t *offset);
/**
* Reads a little-endian uint32_t from a potentially-unaligned offset,
* advancing *offset past it.
*
* @param data The buffer to read from.
* @param offset In/out cursor into data, advanced past the value read.
* @return The decoded uint32_t.
*/
uint32_t assetCutsceneReadU32(const uint8_t *data, size_t *offset);
/**
* Reads a little-endian float_t from a potentially-unaligned offset,
* advancing *offset past it.
*
* @param data The buffer to read from.
* @param offset In/out cursor into data, advanced past the value read.
* @return The decoded float_t.
*/
float_t assetCutsceneReadFloat(const uint8_t *data, size_t *offset);
/**
* Copies a length-prefixed string directly into an item's own embedded
* char_t[destCapacity] field (CUTSCENE_TEXT_MAX_CHARS and friends) - these
* are never pool references, see the item-field inventory in the runtime
* cutscene file design.
*
* @param data The buffer to read from.
* @param offset In/out cursor into data, advanced past the string read.
* @param dest Destination buffer to copy the string into.
* @param destCapacity Capacity of dest, including the null terminator.
*/
void assetCutsceneReadEmbeddedString(
const uint8_t *data,
size_t *offset,
char_t *dest,
const size_t destCapacity
); );
/** /**
* Resolves a u16 pool offset (read from the item stream) to a real pointer * Frees whatever of out->items/out->pool/out->doc is currently non-NULL
* into the entry's own persistent pool allocation. * and clears them - shared by both the normal disposer and every parse
* failure path's cleanup.
* *
* @param data The buffer to read the pool offset from. * @param out The output to free.
* @param offset In/out cursor into data, advanced past the pool offset.
* @param pool The base pointer of the entry's persistent pool allocation.
* @return Pointer to the string within pool.
*/ */
const char_t * assetCutsceneReadPoolString( void assetCutsceneFreeParsed(assetcutsceneoutput_t *out);
const uint8_t *data,
size_t *offset,
const char_t *pool
);
/** /**
* Asynchronous loader for cutscene assets. Reads the raw DCTS file bytes * Asynchronous loader for cutscene assets. Reads the raw JSONC file bytes
* into the loading buffer so the sync phase can parse without blocking the * into the loading buffer so the sync phase can parse without blocking the
* main thread on I/O. * main thread on I/O.
* *
@@ -125,9 +89,8 @@ const char_t * assetCutsceneReadPoolString(
errorret_t assetCutsceneLoaderAsync(assetloading_t *loading); errorret_t assetCutsceneLoaderAsync(assetloading_t *loading);
/** /**
* Synchronous loader for cutscene assets. Validates the DCTS binary * Synchronous loader for cutscene assets. Parses the JSONC previously read
* previously read by the async phase and decodes it into a heap-allocated * by the async phase into a heap-allocated cutsceneitem_t array + pool.
* cutsceneitem_t array + string/data pool.
* *
* @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 of the load operation. * @return Error code indicating success or failure of the load operation.
+3 -2
View File
@@ -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 || !yyjson_is_str(meshVal)) { if(meshVal == NULL || !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,7 +115,8 @@ 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 = assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL); assetentry_t *meshEntry =
assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
ret = assetRequireLoaded(meshEntry); ret = assetRequireLoaded(meshEntry);
if(errorIsNotOk(ret)) { if(errorIsNotOk(ret)) {
assetUnlockEntry(meshEntry); assetUnlockEntry(meshEntry);
+3 -3
View File
@@ -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.
* @returns Always success. * @return 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.
* @returns Error code indicating success or failure. * @return 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.
* @returns Error code indicating success or failure. * @return Error code indicating success or failure.
*/ */
errorret_t assetModelDispose(assetentry_t *entry); errorret_t assetModelDispose(assetentry_t *entry);
+1 -1
View File
@@ -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) { if(loading->entry->data.json == NULL) {
assetLoaderErrorThrow(loading, "Failed to parse JSON"); assetLoaderErrorThrow(loading, "Failed to parse JSON");
} }
@@ -41,6 +41,32 @@ 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, assetLocaleGetString( assetLoaderErrorChain(loading, assetLocaleGetHeader(
localeFile, "", 0, buffer, sizeof(buffer) localeFile, buffer, sizeof(buffer)
)); ));
assetLoaderErrorChain(loading, assetLocaleParseHeader( assetLoaderErrorChain(loading, assetLocaleParseHeader(
localeFile, buffer, sizeof(buffer) localeFile, buffer, sizeof(buffer)
@@ -93,7 +93,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) { if(pluralFormsLine == NULL) {
errorOk(); errorOk();
} }
@@ -101,7 +101,7 @@ errorret_t assetLocaleParseHeader(
// Expect nplurals // Expect nplurals
char_t *npluralsStr = strstr(pluralFormsLine, "nplurals="); char_t *npluralsStr = strstr(pluralFormsLine, "nplurals=");
if(!npluralsStr) { if(npluralsStr == NULL) {
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 +120,7 @@ errorret_t assetLocaleParseHeader(
// Expect plural= // Expect plural=
char_t *pluralStr = strstr(pluralFormsLine, "plural="); char_t *pluralStr = strstr(pluralFormsLine, "plural=");
if(!pluralStr) { if(pluralStr == NULL) {
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 +128,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 || !closeParen || closeParen < openParen) { if(openParen == NULL || closeParen == NULL || closeParen < openParen) {
errorThrow("Failed to find plural expression in Plural-Forms header."); errorThrow("Failed to find plural expression in Plural-Forms header.");
} }
@@ -399,12 +399,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) { if(start == NULL) {
errorThrow("Expected open (0) \""); errorThrow("Expected open (0) \"");
} }
char *end = strchr(start + 1, '"'); char *end = strchr(start + 1, '"');
if(!end) { if(end == NULL) {
errorThrow("Expected close (0) \""); errorThrow("Expected close (0) \"");
} }
*end = '\0'; *end = '\0';
@@ -487,6 +487,7 @@ errorret_t assetLocaleCacheFind(
assertNotNull(file, "Asset file cannot be NULL."); assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(messageId, "Message ID cannot be NULL."); assertNotNull(messageId, "Message ID cannot be NULL.");
assertNotNull(outHit, "outHit cannot be NULL."); assertNotNull(outHit, "outHit cannot be NULL.");
assertStrLenMin(messageId, 1, "Message ID cannot be empty.");
*outHit = false; *outHit = false;
if(file->cache == NULL) errorOk(); if(file->cache == NULL) errorOk();
@@ -502,7 +503,8 @@ errorret_t assetLocaleCacheFind(
if(i > 0) { if(i > 0) {
assetlocalecacheentry_t hit = *entry; assetlocalecacheentry_t hit = *entry;
memoryMove( memoryMove(
&cache->entries[1], &cache->entries[0], i * sizeof(assetlocalecacheentry_t) &cache->entries[1], &cache->entries[0],
i * sizeof(assetlocalecacheentry_t)
); );
cache->entries[0] = hit; cache->entries[0] = hit;
} }
@@ -526,6 +528,7 @@ void assetLocaleCacheInsert(
assertNotNull(file, "Asset file cannot be NULL."); assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(messageId, "Message ID cannot be NULL."); assertNotNull(messageId, "Message ID cannot be NULL.");
assertNotNull(value, "Value 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 // Caching is a pure optimization - a message ID or value too long for a
// fixed cache slot is just never cached, not an error. // fixed cache slot is just never cached, not an error.
@@ -533,7 +536,8 @@ void assetLocaleCacheInsert(
if(strlen(value) >= ASSET_LOCALE_CACHE_VALUE_MAX) return; if(strlen(value) >= ASSET_LOCALE_CACHE_VALUE_MAX) return;
if(file->cache == NULL) { if(file->cache == NULL) {
file->cache = (assetlocalecache_t *)memoryAllocate(sizeof(assetlocalecache_t)); file->cache =
(assetlocalecache_t *)memoryAllocate(sizeof(assetlocalecache_t));
memoryZero(file->cache, sizeof(assetlocalecache_t)); memoryZero(file->cache, sizeof(assetlocalecache_t));
} }
@@ -553,7 +557,13 @@ void assetLocaleCacheInsert(
stringCopy(entry->value, value, ASSET_LOCALE_CACHE_VALUE_MAX); stringCopy(entry->value, value, ASSET_LOCALE_CACHE_VALUE_MAX);
} }
errorret_t assetLocaleGetString( // 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,
@@ -567,10 +577,12 @@ errorret_t assetLocaleGetString(
assertTrue(stringBufferSize > 0, "String buffer size must be > 0"); assertTrue(stringBufferSize > 0, "String buffer size must be > 0");
bool_t cacheHit = false; bool_t cacheHit = false;
errorChain(assetLocaleCacheFind( if(messageId[0] != '\0') {
file, messageId, pluralCount, stringBuffer, stringBufferSize, &cacheHit errorChain(assetLocaleCacheFind(
)); file, messageId, pluralCount, stringBuffer, stringBufferSize, &cacheHit
if(cacheHit) errorOk(); ));
if(cacheHit) errorOk();
}
assetfilelinereader_t reader; assetfilelinereader_t reader;
@@ -678,7 +690,7 @@ errorret_t assetLocaleGetString(
// Parse until ] // Parse until ]
char *end = strchr(ptr, ']'); char *end = strchr(ptr, ']');
if(!end) { if(end == NULL) {
errorThrow("Expected ] for plural form, found: %s", lineBuffer); errorThrow("Expected ] for plural form, found: %s", lineBuffer);
} }
*end = '\0'; *end = '\0';
@@ -715,11 +727,38 @@ errorret_t assetLocaleGetString(
errorThrow("Failed to find msgstr for message ID: %s", messageId); errorThrow("Failed to find msgstr for message ID: %s", messageId);
} }
assetLocaleCacheInsert(file, messageId, pluralCount, stringBuffer); 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,
@@ -815,7 +854,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);
@@ -841,7 +880,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];
@@ -299,16 +299,42 @@ void assetLocaleCacheInsert(
); );
/** /**
* Looks up a translated string by message ID from the open locale file. * 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.
* *
* Checks the file's cache first (see @ref assetLocaleCacheFind); on a miss, * Unlike assetLocaleGetString, messageId may be `""` here (see
* rewinds the file and scans from the beginning, then caches the result * assetLocaleGetHeader) - this is the shared implementation both of
* (see @ref assetLocaleCacheInsert) before returning. For plural entries * them delegate to, not a public entry point of its own in practice.
* (`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 (`""` retrieves the header entry). * @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.
* See @ref assetLocaleGetStringLookup for the lookup/caching mechanics.
*
* @param file Locale file to search. Must be open.
* @param messageId PO message ID to find. Must be non-empty - use
* @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.
@@ -323,6 +349,27 @@ 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.
@@ -5,5 +5,5 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
scenemainmenu.c assetmp3loader.c
) )
+255
View File
@@ -0,0 +1,255 @@
/**
* 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();
}
+113
View File
@@ -0,0 +1,113 @@
/**
* 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);
+5 -4
View File
@@ -7,7 +7,8 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
audio.c audio.c
audiostream.c )
audiostreampcm.c
audiostreammp3.c # Subdirs
) add_subdirectory(mixer)
add_subdirectory(stream)
+12 -2
View File
@@ -6,6 +6,7 @@
*/ */
#include "audio.h" #include "audio.h"
#include "audio/mixer/audiomixer.h"
#include "util/memory.h" #include "util/memory.h"
#include "assert/assert.h" #include "assert/assert.h"
@@ -15,6 +16,7 @@ errorret_t audioInit() {
memoryZero(&AUDIO, sizeof(audio_t)); memoryZero(&AUDIO, sizeof(audio_t));
errorChain(audioPlatformInit()); errorChain(audioPlatformInit());
errorChain(audioMixerInit());
errorOk(); errorOk();
} }
@@ -26,7 +28,7 @@ audiostream_t * audioAquireStream(assetentry_t *asset) {
// too catches the mistake as early as possible, before any stream slot // too catches the mistake as early as possible, before any stream slot
// is handed out for it. // is handed out for it.
assertTrue( assertTrue(
asset->type == ASSET_LOADER_TYPE_WAV, audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
"Unsupported asset type for an audio stream." "Unsupported asset type for an audio stream."
); );
@@ -40,8 +42,9 @@ audiostream_t * audioAquireStream(assetentry_t *asset) {
return NULL; return NULL;
} }
errorret_t audioUpdate() { errorret_t audioUpdateEarly() {
errorChain(audioPlatformUpdate()); errorChain(audioPlatformUpdate());
errorChain(audioMixerUpdateEarly());
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) { for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
audiostream_t *stream = &AUDIO.streams[i]; audiostream_t *stream = &AUDIO.streams[i];
@@ -51,12 +54,19 @@ errorret_t audioUpdate() {
errorOk(); errorOk();
} }
errorret_t audioUpdateLate() {
errorChain(audioMixerUpdateLate());
errorOk();
}
errorret_t audioDispose() { errorret_t audioDispose() {
for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) { for(uint8_t i = 0; i < AUDIO_STREAMS_MAX; i++) {
audiostream_t *stream = &AUDIO.streams[i]; audiostream_t *stream = &AUDIO.streams[i];
errorChain(audioStreamDispose(stream)); errorChain(audioStreamDispose(stream));
} }
errorChain(audioMixerDispose());
errorChain(audioPlatformDispose()); errorChain(audioPlatformDispose());
errorOk(); errorOk();
+15 -3
View File
@@ -7,7 +7,7 @@
#pragma once #pragma once
#include "dusk.h" #include "dusk.h"
#include "audio/audiostream.h" #include "audio/stream/audiostream.h"
#include "audio/audioplatform.h" #include "audio/audioplatform.h"
#ifndef audioPlatformInit #ifndef audioPlatformInit
@@ -51,11 +51,23 @@ audiostream_t * audioAquireStream(assetentry_t *asset);
/** /**
* Updates the audio subsystem, updating every active stream. Should be * Updates the audio subsystem, updating every active stream. Should be
* called once per frame. * 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. * @return Error indicating success or failure of the operation.
*/ */
errorret_t audioUpdate(); 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. * Disposes the audio subsystem, stopping and disposing every active stream.
-8
View File
@@ -1,8 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiostreammp3.h"
+11
View File
@@ -0,0 +1,11 @@
# 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
)
+199
View File
@@ -0,0 +1,199 @@
/**
* 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();
}
+204
View File
@@ -0,0 +1,204 @@
/**
* 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();
+223
View File
@@ -0,0 +1,223 @@
/**
* 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);
}
+242
View File
@@ -0,0 +1,242 @@
/**
* 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);
+13
View File
@@ -0,0 +1,13 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
audiostream.c
audiostreampcm.c
audiostreammp3.c
audiostreamtype.c
)
@@ -7,6 +7,7 @@
#include "audiostream.h" #include "audiostream.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/math.h"
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) { errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) {
assertNotNull(stream, "Stream cannot be NULL."); assertNotNull(stream, "Stream cannot be NULL.");
@@ -15,17 +16,17 @@ errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) {
asset->state == ASSET_ENTRY_STATE_LOADED, asset->state == ASSET_ENTRY_STATE_LOADED,
"Asset must be loaded before it can back an audio stream." "Asset must be loaded before it can back an audio stream."
); );
// Only WAV (-> PCM) assets can back an audio stream today - a caller // A caller passing an asset type that can't back an audio stream is a
// passing the wrong kind of asset entry is a programmer error, not // programmer error, not something that can happen from untrusted data, so
// something that can happen from untrusted data, so this is an assert // this is an assert rather than an errorThrow (see
// rather than an errorThrow (see feedback_assert_vs_error convention). // feedback_assert_vs_error convention).
assertTrue( assertTrue(
asset->type == ASSET_LOADER_TYPE_WAV, audioStreamTypeForAssetType(asset->type) != AUDIO_STREAM_TYPE_NULL,
"Unsupported asset type for an audio stream." "Unsupported asset type for an audio stream."
); );
stream->state = 0; stream->state = 0;
stream->volume = 0xFF; stream->volume = 1.0f;
stream->directionality = AUDIO_STREAM_CENTER; stream->directionality = AUDIO_STREAM_CENTER;
stream->loopStart = -1; stream->loopStart = -1;
stream->loopTo = 0; stream->loopTo = 0;
@@ -37,16 +38,20 @@ errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) {
stream->onEnd = NULL; stream->onEnd = NULL;
stream->loopCount = 0; stream->loopCount = 0;
stream->lastLoopCount = 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 // Locked for as long as the stream is in use (see audiostream_t.asset's
// own comment) - released in audioStreamDispose(). // own comment) - released in audioStreamDispose().
stream->asset = asset; stream->asset = asset;
assetEntryLock(asset); assetEntryLock(asset);
// Type-specific setup (audioStreamPcmInit() / audioStreamMp3Init(), once // Type-specific setup (audioStreamPcmInit() / audioStreamMp3Init())
// MP3 exists) determines stream->type and asks the platform // determines stream->type, sets stream->sampleRate/channels, and asks
// implementation to set up its state. // the platform implementation to set up its state.
errorret_t ret = audioStreamPcmInit(stream); errorret_t ret = asset->type == ASSET_LOADER_TYPE_MP3
? audioStreamMp3Init(stream)
: audioStreamPcmInit(stream);
if(errorIsNotOk(ret)) { if(errorIsNotOk(ret)) {
assetEntryUnlock(asset); assetEntryUnlock(asset);
stream->asset = NULL; stream->asset = NULL;
@@ -56,6 +61,41 @@ errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset) {
errorOk(); 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) { void audioStreamPlay(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL."); assertNotNull(stream, "Stream cannot be NULL.");
stream->state |= AUDIO_STREAM_STATE_PLAYING; stream->state |= AUDIO_STREAM_STATE_PLAYING;
@@ -74,7 +114,7 @@ void audioStreamSetPosition(audiostream_t *stream, const float_t position) {
while(t < 0) t += stream->duration; while(t < 0) t += stream->duration;
while(t >= stream->duration) t -= stream->duration; while(t >= stream->duration) t -= stream->duration;
stream->startFrame = (size_t) (t * stream->pcm.sampleRate); stream->startFrame = (size_t) (t * stream->sampleRate);
stream->seeking = true; stream->seeking = true;
// Force the next audioStreamUpdate() to re-buffer from startFrame instead // Force the next audioStreamUpdate() to re-buffer from startFrame instead
@@ -108,26 +148,50 @@ void audioStreamGetPanFactors(
assertNotNull(outLeft, "outLeft cannot be NULL."); assertNotNull(outLeft, "outLeft cannot be NULL.");
assertNotNull(outRight, "outRight cannot be NULL."); assertNotNull(outRight, "outRight cannot be NULL.");
// directionality is an int8_t clamped to AUDIO_STREAM_LEFT..RIGHT // directionality is already a pan factor in AUDIO_STREAM_LEFT..RIGHT
// (-128..127) by its own type, so pan is always within [-1.0, 0.992] - // (-1.0..1.0) - assertTrue'd here rather than clamped, since a caller
// no further clamping needed. // passing something outside that range is a programmer error (see
const float_t pan = (float_t) stream->directionality / 128.0f; // audioStreamSetDirectionality()'s own assert).
const float_t pan = stream->directionality;
*outLeft = pan > 0 ? (1.0f - pan) : 1.0f; *outLeft = pan > 0 ? (1.0f - pan) : 1.0f;
*outRight = pan < 0 ? (1.0f + pan) : 1.0f; *outRight = pan < 0 ? (1.0f + pan) : 1.0f;
} }
void audioStreamSetVolume(audiostream_t *stream, const uint8_t volume) { size_t audioStreamComputeEndFrame(
const audiostream_t *stream,
const size_t startFrame,
const size_t totalFrames
) {
assertNotNull(stream, "Stream cannot be NULL."); 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; stream->volume = volume;
// TODO: Do I need to update the device output? PSP may require this // TODO: Do I need to update the device output? PSP may require this
} }
void audioStreamSetDirectionality( void audioStreamSetDirectionality(
audiostream_t *stream, audiostream_t *stream,
const int8_t directionality const float_t directionality
) { ) {
assertNotNull(stream, "Stream cannot be NULL."); assertNotNull(stream, "Stream cannot be NULL.");
assertTrue(
directionality >= AUDIO_STREAM_LEFT && directionality <= AUDIO_STREAM_RIGHT,
"Directionality is out of range."
);
stream->directionality = directionality; stream->directionality = directionality;
// TODO: Need to update internal decoder? // TODO: Need to update internal decoder?
} }
@@ -142,6 +206,12 @@ void audioStreamSetLooping(audiostream_t *stream, const bool_t 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) { errorret_t audioStreamUpdate(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL."); assertNotNull(stream, "Stream cannot be NULL.");
@@ -176,20 +246,30 @@ errorret_t audioStreamUpdate(audiostream_t *stream) {
(stream->state & AUDIO_STREAM_STATE_BUFFERED) && (stream->state & AUDIO_STREAM_STATE_BUFFERED) &&
audioStreamPlatformIsFinished(stream) audioStreamPlatformIsFinished(stream)
) { ) {
if(stream->state & AUDIO_STREAM_STATE_LOOPING) { // 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->state &= ~AUDIO_STREAM_STATE_BUFFERED;
stream->loopRestartCount++;
// Resume from loopTo rather than the very start of the buffer - only // Resume from loopTo rather than the very start of the buffer - only
// matters for platforms that reach this generic restart path at all; // matters for platforms that reach this generic restart path at all
// PSP/Dolphin loop entirely on their own (thread/hardware) and never // (Linux and Dolphin, both of which re-buffer per pass and report
// report "finished" while looping, so in practice this is Linux-only. // "finished" at every loop boundary); PSP loops entirely on its own
stream->startFrame = (size_t) (stream->loopTo * stream->pcm.sampleRate); // read-ahead ring instead (see loopRestartCount's own comment).
stream->startFrame = (size_t) (stream->loopTo * stream->sampleRate);
if(stream->onLoop != NULL) { if(stream->onLoop != NULL) {
stream->onLoop(stream); stream->onLoop(stream);
} }
} else { } else {
stream->state &= ~(AUDIO_STREAM_STATE_PLAYING | AUDIO_STREAM_STATE_BUFFERED); stream->state &=
~(AUDIO_STREAM_STATE_PLAYING | AUDIO_STREAM_STATE_BUFFERED);
if(stream->onEnd != NULL) { if(stream->onEnd != NULL) {
stream->onEnd(stream); stream->onEnd(stream);
@@ -217,6 +297,8 @@ errorret_t audioStreamDispose(audiostream_t *stream) {
if(stream->type == AUDIO_STREAM_TYPE_PCM) { if(stream->type == AUDIO_STREAM_TYPE_PCM) {
errorChain(audioStreamPcmDispose(stream)); errorChain(audioStreamPcmDispose(stream));
} else if(stream->type == AUDIO_STREAM_TYPE_MP3) {
errorChain(audioStreamMp3Dispose(stream));
} }
if(stream->asset != NULL) { if(stream->asset != NULL) {
@@ -6,8 +6,9 @@
*/ */
#pragma once #pragma once
#include "audio/audiostreampcm.h" #include "audio/stream/audiostreamtype.h"
#include "audio/audiostreammp3.h" #include "audio/stream/audiostreampcm.h"
#include "audio/stream/audiostreammp3.h"
#include "audio/audiostreamplatform.h" #include "audio/audiostreamplatform.h"
#include "asset/loader/assetentry.h" #include "asset/loader/assetentry.h"
@@ -31,16 +32,9 @@
#define AUDIO_STREAM_STATE_PLAYING (1 << 0) #define AUDIO_STREAM_STATE_PLAYING (1 << 0)
#define AUDIO_STREAM_STATE_LOOPING (1 << 1) #define AUDIO_STREAM_STATE_LOOPING (1 << 1)
#define AUDIO_STREAM_STATE_BUFFERED (1 << 2) #define AUDIO_STREAM_STATE_BUFFERED (1 << 2)
#define AUDIO_STREAM_CENTER 0 #define AUDIO_STREAM_CENTER 0.0f
#define AUDIO_STREAM_LEFT -128 #define AUDIO_STREAM_LEFT -1.0f
#define AUDIO_STREAM_RIGHT 127 #define AUDIO_STREAM_RIGHT 1.0f
typedef enum {
AUDIO_STREAM_TYPE_NULL,
AUDIO_STREAM_TYPE_PCM,
AUDIO_STREAM_TYPE_MP3,
AUDIO_STREAM_TYPE_COUNT
} audistreamtype_t;
typedef struct audiostream_s audiostream_t; typedef struct audiostream_s audiostream_t;
@@ -48,8 +42,11 @@ typedef struct audiostream_s {
// Used for aquiring new data. // Used for aquiring new data.
audistreamtype_t type; audistreamtype_t type;
// What state the stream is in. // What state the stream is in. volatile: PSP's output thread reads
uint8_t state; // 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 // 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` (see audioStreamInit()) and is read from on demand by the
@@ -60,12 +57,14 @@ typedef struct audiostream_s {
// playback may also be holding. // playback may also be holding.
assetentry_t *asset; assetentry_t *asset;
// Loudness. Can only be 0 to 0xFF // Loudness, from 0.0 (silent) to 1.0 (loudest).
uint8_t volume; float_t volume;
// In stereo space, where do we send the audio. // 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? // TODO: Can we use a 3D vector + Pro Logic II?
int8_t directionality; float_t directionality;
// In seconds, where the loop segment ends and playback jumps back to // 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 // loopTo - -1 (the default) means "at the end of the stream", i.e. loop
@@ -119,13 +118,38 @@ typedef struct audiostream_s {
// onLoop for - only ever touched from the main thread. // onLoop for - only ever touched from the main thread.
uint32_t lastLoopCount; 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. // Stream type specific data.
union { union {
audiostreampcm_t pcm; audiostreampcm_t pcm;
audiostreammp3_t mp3; audiostreammp3_t mp3;
}; };
// Platform-specific playback state (e.g. SDL2 device, PSP channel, ansnd // Platform-specific playback state (e.g. SDL2 device, PSP channel, ASND
// voice). Defined by each platform's audiostreamplatform.h. // voice). Defined by each platform's audiostreamplatform.h.
audiostreamplatform_t platform; audiostreamplatform_t platform;
} audiostream_t; } audiostream_t;
@@ -143,11 +167,55 @@ typedef struct audiostream_s {
* *
* @param stream The audio stream to initialize. * @param stream The audio stream to initialize.
* @param asset The loaded asset to play - its type must be one this * @param asset The loaded asset to play - its type must be one this
* function supports (currently only ASSET_LOADER_TYPE_WAV). * function supports (ASSET_LOADER_TYPE_WAV or
* ASSET_LOADER_TYPE_MP3).
* @return Error indicating success or failure. * @return Error indicating success or failure.
*/ */
errorret_t audioStreamInit(audiostream_t *stream, assetentry_t *asset); 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. * Begins or resumes playback of the given audio stream.
* *
@@ -208,13 +276,34 @@ void audioStreamGetPanFactors(
float_t *outRight 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. * Sets the playback volume of the given audio stream.
* *
* @param stream The audio stream to update. * @param stream The audio stream to update.
* @param volume The new volume, from 0 (silent) to 0xFF (loudest). * @param volume The new volume, from 0.0 (silent) to 1.0 (loudest).
*/ */
void audioStreamSetVolume(audiostream_t *stream, const uint8_t volume); void audioStreamSetVolume(audiostream_t *stream, const float_t volume);
/** /**
* Sets the stereo directionality (panning) of the given audio stream. * Sets the stereo directionality (panning) of the given audio stream.
@@ -225,7 +314,7 @@ void audioStreamSetVolume(audiostream_t *stream, const uint8_t volume);
*/ */
void audioStreamSetDirectionality( void audioStreamSetDirectionality(
audiostream_t *stream, audiostream_t *stream,
const int8_t directionality const float_t directionality
); );
/** /**
@@ -239,6 +328,19 @@ void audioStreamSetDirectionality(
*/ */
void audioStreamSetLooping(audiostream_t *stream, const bool_t looping); 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 * Updates the given audio stream, decoding new data and advancing playback
* as needed. Should be called every frame for every active stream. * as needed. Should be called every frame for every active stream.
+167
View File
@@ -0,0 +1,167 @@
/**
* 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();
}
+140
View File
@@ -0,0 +1,140 @@
/**
* 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
);
@@ -10,6 +10,7 @@
#include "assert/assert.h" #include "assert/assert.h"
#include "util/math.h" #include "util/math.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/endian.h"
errorret_t audioStreamPcmInit(audiostream_t *stream) { errorret_t audioStreamPcmInit(audiostream_t *stream) {
assertNotNull(stream, "Stream cannot be NULL."); assertNotNull(stream, "Stream cannot be NULL.");
@@ -22,8 +23,8 @@ errorret_t audioStreamPcmInit(audiostream_t *stream) {
assetwavfile_t *wav = &stream->asset->data.wav; assetwavfile_t *wav = &stream->asset->data.wav;
stream->type = AUDIO_STREAM_TYPE_PCM; stream->type = AUDIO_STREAM_TYPE_PCM;
stream->pcm.sampleRate = wav->sampleRate; stream->sampleRate = wav->sampleRate;
stream->pcm.channels = wav->channels; stream->channels = wav->channels;
stream->duration = ( stream->duration = (
(float_t) audioStreamPcmGetTotalFrames(stream) / (float_t) audioStreamPcmGetTotalFrames(stream) /
(float_t) wav->sampleRate (float_t) wav->sampleRate
@@ -64,7 +65,7 @@ size_t audioStreamPcmGetTotalFrames(const audiostream_t *stream) {
const assetwavfile_t *wav = &stream->asset->data.wav; const assetwavfile_t *wav = &stream->asset->data.wav;
const size_t sourceFrameSize = ( const size_t sourceFrameSize = (
stream->pcm.channels * (wav->bitsPerSample / 8) stream->channels * (wav->bitsPerSample / 8)
); );
return wav->dataSize / sourceFrameSize; return wav->dataSize / sourceFrameSize;
} }
@@ -75,7 +76,7 @@ errorret_t audioStreamPcmSeek(audiostream_t *stream, const size_t frame) {
assetwavfile_t *wav = &stream->asset->data.wav; assetwavfile_t *wav = &stream->asset->data.wav;
const size_t sourceFrameSize = ( const size_t sourceFrameSize = (
stream->pcm.channels * (wav->bitsPerSample / 8) stream->channels * (wav->bitsPerSample / 8)
); );
const size_t targetByte = wav->dataOffset + (frame * sourceFrameSize); const size_t targetByte = wav->dataOffset + (frame * sourceFrameSize);
@@ -113,7 +114,7 @@ errorret_t audioStreamPcmRead(
assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM."); assertTrue(stream->type == AUDIO_STREAM_TYPE_PCM, "Stream is not PCM.");
assetwavfile_t *wav = &stream->asset->data.wav; assetwavfile_t *wav = &stream->asset->data.wav;
const size_t channels = stream->pcm.channels; const size_t channels = stream->channels;
const size_t sourceSampleBytes = wav->bitsPerSample / 8; const size_t sourceSampleBytes = wav->bitsPerSample / 8;
const size_t sourceFrameSize = channels * sourceSampleBytes; const size_t sourceFrameSize = channels * sourceSampleBytes;
const size_t dataEndByte = wav->dataOffset + wav->dataSize; const size_t dataEndByte = wav->dataOffset + wav->dataSize;
@@ -131,10 +132,19 @@ errorret_t audioStreamPcmRead(
} }
if(sourceSampleBytes == sizeof(int16_t)) { if(sourceSampleBytes == sizeof(int16_t)) {
// Output format already matches the source - read straight through. // 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( errorChain(assetFileRead(
&stream->pcm.file, buffer, framesToRead * sourceFrameSize &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 { } else {
// 24-bit source (the only other width assetWavParseHeader() accepts) - // 24-bit source (the only other width assetWavParseHeader() accepts) -
// read the raw 3-byte samples into a scratch buffer, then truncate // read the raw 3-byte samples into a scratch buffer, then truncate
@@ -12,12 +12,6 @@
typedef struct audiostream_s audiostream_t; typedef struct audiostream_s audiostream_t;
typedef struct { typedef struct {
// Sample rate of the stream's data, in Hz.
uint32_t sampleRate;
// Number of interleaved channels in the stream's data.
uint8_t channels;
// This stream's own private handle into its asset's underlying file - // This stream's own private handle into its asset's underlying file -
// deliberately not shared with any other stream reading the same asset // deliberately not shared with any other stream reading the same asset
// (see audioStreamPcmInit's own comment for why). Its read cursor is // (see audioStreamPcmInit's own comment for why). Its read cursor is
+50
View File
@@ -0,0 +1,50 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "audiostreamtype.h"
#include "util/string.h"
const audiostreamassettypeinfo_t
AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[ASSET_LOADER_TYPE_COUNT] = {
[ASSET_LOADER_TYPE_WAV] = {
.type = AUDIO_STREAM_TYPE_PCM, .extension = ".wav"
},
[ASSET_LOADER_TYPE_MP3] = {
.type = AUDIO_STREAM_TYPE_MP3, .extension = ".mp3"
}
};
assetloadertype_t audioStreamAssetTypeForPath(const char_t *path) {
for(assetloadertype_t i = 0; i < ASSET_LOADER_TYPE_COUNT; i++) {
const char_t *extension = AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[i].extension;
if(extension != NULL && stringEndsWithCaseInsensitive(path, extension)) {
return i;
}
}
return ASSET_LOADER_TYPE_NULL;
}
audistreamtype_t audioStreamTypeForAssetType(
const assetloadertype_t assetType
) {
return AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[assetType].type;
}
assetloadertype_t audioStreamAssetTypeForStreamType(
const audistreamtype_t streamType
) {
if(streamType == AUDIO_STREAM_TYPE_NULL) return ASSET_LOADER_TYPE_NULL;
for(assetloadertype_t i = 0; i < ASSET_LOADER_TYPE_COUNT; i++) {
if(AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[i].type == streamType) {
return i;
}
}
return ASSET_LOADER_TYPE_NULL;
}
+71
View File
@@ -0,0 +1,71 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "asset/loader/assetloader.h"
typedef enum {
AUDIO_STREAM_TYPE_NULL,
AUDIO_STREAM_TYPE_PCM,
AUDIO_STREAM_TYPE_MP3,
AUDIO_STREAM_TYPE_COUNT
} audistreamtype_t;
typedef struct {
// The audistreamtype_t an audio stream backed by this asset type should
// become - AUDIO_STREAM_TYPE_NULL (the zero-initialized default) for any
// asset type that can't back an audio stream.
audistreamtype_t type;
// This asset type's file extension, including the leading '.' (e.g.
// ".wav"). NULL for any asset type that can't back an audio stream.
const char_t *extension;
} audiostreamassettypeinfo_t;
// Maps an assetloadertype_t to the info describing the audio stream it
// backs. Indexed directly by assetentry_t.type; see audioStreamInit()'s own
// use of this for the canonical "is this asset type supported" check. Use
// the functions below rather than indexing this directly, except where
// you already have an assetloadertype_t in hand.
extern const audiostreamassettypeinfo_t
AUDIO_STREAM_TYPE_FOR_ASSET_TYPE[ASSET_LOADER_TYPE_COUNT];
/**
* Determines which asset loader type a file path's extension corresponds
* to, by matching it against AUDIO_STREAM_TYPE_FOR_ASSET_TYPE's own
* extensions (case-insensitively).
*
* @param path The file path to inspect, e.g. "audio/boa.mp3".
* @return The matching assetloadertype_t, or ASSET_LOADER_TYPE_NULL if the
* path's extension doesn't match any audio asset type.
*/
assetloadertype_t audioStreamAssetTypeForPath(const char_t *path);
/**
* Looks up the audistreamtype_t an audio stream backed by the given asset
* type should become.
*
* @param assetType The asset loader type to look up.
* @return The matching audistreamtype_t, or AUDIO_STREAM_TYPE_NULL if
* assetType can't back an audio stream.
*/
audistreamtype_t audioStreamTypeForAssetType(const assetloadertype_t assetType);
/**
* Looks up which asset loader type backs audio streams of the given type -
* the reverse of audioStreamTypeForAssetType(). Scans
* AUDIO_STREAM_TYPE_FOR_ASSET_TYPE for the first entry whose type matches,
* since it isn't itself indexed by audistreamtype_t.
*
* @param streamType The audio stream type to look up.
* @return The matching assetloadertype_t, or ASSET_LOADER_TYPE_NULL if
* streamType is AUDIO_STREAM_TYPE_NULL or otherwise unmapped.
*/
assetloadertype_t audioStreamAssetTypeForStreamType(
const audistreamtype_t streamType
);
+2 -2
View File
@@ -17,8 +17,8 @@ console_t CONSOLE;
void consoleInit(void) { void consoleInit(void) {
memoryZero(&CONSOLE, sizeof(console_t)); memoryZero(&CONSOLE, sizeof(console_t));
// CONSOLE.visible = false; CONSOLE.visible = false;
CONSOLE.visible = true; // CONSOLE.visible = true;
threadMutexInit(&CONSOLE.printMutex); threadMutexInit(&CONSOLE.printMutex);
} }
+5 -5
View File
@@ -55,8 +55,8 @@ void capsuleBuffer(
vertices[vi].uv[1] = (v); \ vertices[vi].uv[1] = (v); \
vi++; vi++;
/* ---- Top hemisphere ---- */ // ---- Top hemisphere ----
/* phi ranges from PI/2 (top pole) down to 0 (equator). */ // phi ranges from PI/2 (top pole) down to 0 (equator).
const float_t capStep = (float_t)GLM_PI_2 / (float_t)capRings; const float_t capStep = (float_t)GLM_PI_2 / (float_t)capRings;
for(int32_t i = 0; i < capRings; i++) { for(int32_t i = 0; i < capRings; i++) {
const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * capStep; const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * capStep;
@@ -67,8 +67,8 @@ void capsuleBuffer(
const float_t lxz1 = radius * cosf(phi1); const float_t lxz1 = radius * cosf(phi1);
const float_t lxz2 = radius * cosf(phi2); const float_t lxz2 = radius * cosf(phi2);
/* UV: top cap occupies v in [0.5 + halfHeightFrac .. 1.0]: we use a // UV: top cap occupies v in [0.5 + halfHeightFrac .. 1.0]: we use a
* simple per-band normalisation against the full height. */ // simple per-band normalisation against the full height.
const float_t v1 = 1.0f - (float_t)i / (float_t)(2 * capRings + 1); const float_t v1 = 1.0f - (float_t)i / (float_t)(2 * capRings + 1);
const float_t v2 = 1.0f - (float_t)(i + 1) / (float_t)(2 * capRings + 1); const float_t v2 = 1.0f - (float_t)(i + 1) / (float_t)(2 * capRings + 1);
@@ -97,7 +97,7 @@ void capsuleBuffer(
} }
} }
/* ---- Cylindrical body ---- */ // ---- Cylindrical body ----
{ {
const float_t yTop = cy + halfHeight; const float_t yTop = cy + halfHeight;
const float_t yBot = cy - halfHeight; const float_t yBot = cy - halfHeight;
+6 -4
View File
@@ -1,7 +1,9 @@
// Copyright (c) 2026 Dominic Masters /**
// * Copyright (c) 2026 Dominic Masters
// This software is released under the MIT License. *
// https://opensource.org/licenses/MIT * This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once #pragma once
#include "display/display.h" #include "display/display.h"
+3 -3
View File
@@ -59,7 +59,7 @@ void planeBuffer(
switch(axis) { switch(axis) {
case PLANE_AXIS_XY: { case PLANE_AXIS_XY: {
/* Flat in XY at z = min[2]; spans X and Y. */ // Flat in XY at z = min[2]; spans X and Y.
const float_t z = min[2]; const float_t z = min[2];
PLANE_VERT(0, min[0], min[1], z, u0, v0) PLANE_VERT(0, min[0], min[1], z, u0, v0)
PLANE_VERT(1, max[0], min[1], z, u1, v0) PLANE_VERT(1, max[0], min[1], z, u1, v0)
@@ -71,7 +71,7 @@ void planeBuffer(
} }
case PLANE_AXIS_XZ: { case PLANE_AXIS_XZ: {
/* Flat in XZ at y = min[1]; spans X and Z. */ // Flat in XZ at y = min[1]; spans X and Z.
const float_t y = min[1]; const float_t y = min[1];
PLANE_VERT(0, min[0], y, min[2], u0, v0) PLANE_VERT(0, min[0], y, min[2], u0, v0)
PLANE_VERT(1, max[0], y, min[2], u1, v0) PLANE_VERT(1, max[0], y, min[2], u1, v0)
@@ -83,7 +83,7 @@ void planeBuffer(
} }
case PLANE_AXIS_YZ: { case PLANE_AXIS_YZ: {
/* Flat in YZ at x = min[0]; spans Y and Z. */ // Flat in YZ at x = min[0]; spans Y and Z.
const float_t x = min[0]; const float_t x = min[0];
PLANE_VERT(0, x, min[1], min[2], u0, v0) PLANE_VERT(0, x, min[1], min[2], u0, v0)
PLANE_VERT(1, x, max[1], min[2], u1, v0) PLANE_VERT(1, x, max[1], min[2], u1, v0)
+13 -7
View File
@@ -44,7 +44,7 @@ void sphereBuffer(
int32_t vi = 0; int32_t vi = 0;
for(int32_t i = 0; i < stacks; i++) { for(int32_t i = 0; i < stacks; i++) {
/* Latitude angles: top of band -> bottom of band */ // Latitude angles: top of band -> bottom of band
const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * stackStep; const float_t phi1 = (float_t)GLM_PI_2 - (float_t)i * stackStep;
const float_t phi2 = (float_t)GLM_PI_2 - (float_t)(i + 1) * stackStep; const float_t phi2 = (float_t)GLM_PI_2 - (float_t)(i + 1) * stackStep;
@@ -73,27 +73,33 @@ void sphereBuffer(
const float_t u1 = (float_t)j / (float_t)sectors; const float_t u1 = (float_t)j / (float_t)sectors;
const float_t u2 = (float_t)(j + 1) / (float_t)sectors; const float_t u2 = (float_t)(j + 1) / (float_t)sectors;
vertices[vi].pos[0] = center[0] + x11; vertices[vi].pos[1] = center[1] + y1; vertices[vi].pos[0] = center[0] + x11;
vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[2] = center[2] + z11; vertices[vi].pos[2] = center[2] + z11;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v1; vi++; vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v1; vi++;
vertices[vi].pos[0] = center[0] + x21; vertices[vi].pos[1] = center[1] + y2; vertices[vi].pos[0] = center[0] + x21;
vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[2] = center[2] + z21; vertices[vi].pos[2] = center[2] + z21;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++; vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
vertices[vi].pos[0] = center[0] + x12; vertices[vi].pos[1] = center[1] + y1; vertices[vi].pos[0] = center[0] + x12;
vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[2] = center[2] + z12; vertices[vi].pos[2] = center[2] + z12;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++; vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
vertices[vi].pos[0] = center[0] + x12; vertices[vi].pos[1] = center[1] + y1; vertices[vi].pos[0] = center[0] + x12;
vertices[vi].pos[1] = center[1] + y1;
vertices[vi].pos[2] = center[2] + z12; vertices[vi].pos[2] = center[2] + z12;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++; vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
vertices[vi].pos[0] = center[0] + x21; vertices[vi].pos[1] = center[1] + y2; vertices[vi].pos[0] = center[0] + x21;
vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[2] = center[2] + z21; vertices[vi].pos[2] = center[2] + z21;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++; vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
vertices[vi].pos[0] = center[0] + x22; vertices[vi].pos[1] = center[1] + y2; vertices[vi].pos[0] = center[0] + x22;
vertices[vi].pos[1] = center[1] + y2;
vertices[vi].pos[2] = center[2] + z22; vertices[vi].pos[2] = center[2] + z22;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v2; vi++; vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v2; vi++;
} }
+5 -5
View File
@@ -47,17 +47,17 @@ void triPrismBuffer(
vertices[vi].uv[1] = (v); \ vertices[vi].uv[1] = (v); \
vi++; vi++;
/* --- Front face (z = maxZ), CCW from +Z --- */ // --- Front face (z = maxZ), CCW from +Z ---
PRISM_VERT(x0, y0, maxZ, 0.0f, 0.0f) PRISM_VERT(x0, y0, maxZ, 0.0f, 0.0f)
PRISM_VERT(x1, y1, maxZ, 1.0f, 0.0f) PRISM_VERT(x1, y1, maxZ, 1.0f, 0.0f)
PRISM_VERT(x2, y2, maxZ, 0.5f, 1.0f) PRISM_VERT(x2, y2, maxZ, 0.5f, 1.0f)
/* --- Back face (z = minZ), CCW from -Z (reverse winding) --- */ // --- Back face (z = minZ), CCW from -Z (reverse winding) ---
PRISM_VERT(x2, y2, minZ, 0.5f, 1.0f) PRISM_VERT(x2, y2, minZ, 0.5f, 1.0f)
PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f) PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f)
PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f) PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f)
/* --- Side face 0: edge p0->p1 --- */ // --- Side face 0: edge p0->p1 ---
PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f) PRISM_VERT(x0, y0, minZ, 0.0f, 0.0f)
PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f) PRISM_VERT(x1, y1, minZ, 1.0f, 0.0f)
PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f) PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f)
@@ -66,7 +66,7 @@ void triPrismBuffer(
PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f) PRISM_VERT(x1, y1, maxZ, 1.0f, 1.0f)
PRISM_VERT(x0, y0, maxZ, 0.0f, 1.0f) PRISM_VERT(x0, y0, maxZ, 0.0f, 1.0f)
/* --- Side face 1: edge p1->p2 --- */ // --- Side face 1: edge p1->p2 ---
PRISM_VERT(x1, y1, minZ, 0.0f, 0.0f) PRISM_VERT(x1, y1, minZ, 0.0f, 0.0f)
PRISM_VERT(x2, y2, minZ, 1.0f, 0.0f) PRISM_VERT(x2, y2, minZ, 1.0f, 0.0f)
PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f) PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f)
@@ -75,7 +75,7 @@ void triPrismBuffer(
PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f) PRISM_VERT(x2, y2, maxZ, 1.0f, 1.0f)
PRISM_VERT(x1, y1, maxZ, 0.0f, 1.0f) PRISM_VERT(x1, y1, maxZ, 0.0f, 1.0f)
/* --- Side face 2: edge p2->p0 --- */ // --- Side face 2: edge p2->p0 ---
PRISM_VERT(x2, y2, minZ, 0.0f, 0.0f) PRISM_VERT(x2, y2, minZ, 0.0f, 0.0f)
PRISM_VERT(x0, y0, minZ, 1.0f, 0.0f) PRISM_VERT(x0, y0, minZ, 1.0f, 0.0f)
PRISM_VERT(x0, y0, maxZ, 1.0f, 1.0f) PRISM_VERT(x0, y0, maxZ, 1.0f, 1.0f)
+10 -10
View File
@@ -13,14 +13,14 @@
shader_t *bound = NULL; shader_t *bound = NULL;
errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) { errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
errorChain(shaderInitPlatform(shader, def)); errorChain(shaderInitPlatform(shader, def));
bound = NULL; bound = NULL;
errorOk(); errorOk();
} }
errorret_t shaderBind(shader_t *shader) { errorret_t shaderBind(shader_t *shader) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
errorChain(shaderBindPlatform(shader)); errorChain(shaderBindPlatform(shader));
bound = shader; bound = shader;
errorOk(); errorOk();
@@ -31,9 +31,9 @@ errorret_t shaderSetMatrix(
const char_t *name, const char_t *name,
mat4 matrix mat4 matrix
) { ) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
assertStrLenMin(name, 1, "Uniform name cannot be empty"); assertStrLenMin(name, 1, "Uniform name cannot be empty");
assertNotNull(matrix, "Matrix cannot be null"); assertNotNull(matrix, "Matrix cannot be NULL");
assertTrue(bound == shader, "Shader must be bound."); assertTrue(bound == shader, "Shader must be bound.");
errorChain(shaderSetMatrixPlatform(shader, name, matrix)); errorChain(shaderSetMatrixPlatform(shader, name, matrix));
errorOk(); errorOk();
@@ -44,7 +44,7 @@ errorret_t shaderSetTexture(
const char_t *name, const char_t *name,
texture_t *texture texture_t *texture
) { ) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
assertStrLenMin(name, 1, "Uniform name cannot be empty"); assertStrLenMin(name, 1, "Uniform name cannot be empty");
assertTrue(bound == shader, "Shader must be bound."); assertTrue(bound == shader, "Shader must be bound.");
errorChain(shaderSetTexturePlatform(shader, name, texture)); errorChain(shaderSetTexturePlatform(shader, name, texture));
@@ -56,7 +56,7 @@ errorret_t shaderSetColor(
const char_t *name, const char_t *name,
color_t color color_t color
) { ) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
assertStrLenMin(name, 1, "Uniform name cannot be empty"); assertStrLenMin(name, 1, "Uniform name cannot be empty");
assertTrue(bound == shader, "Shader must be bound."); assertTrue(bound == shader, "Shader must be bound.");
errorChain(shaderSetColorPlatform(shader, name, color)); errorChain(shaderSetColorPlatform(shader, name, color));
@@ -67,16 +67,16 @@ errorret_t shaderSetMaterial(
shader_t *shader, shader_t *shader,
const shadermaterial_t *material const shadermaterial_t *material
) { ) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
assertNotNull(material, "Material cannot be null"); assertNotNull(material, "Material cannot be NULL");
assertTrue(bound == shader, "Shader must be bound."); assertTrue(bound == shader, "Shader must be bound.");
assertNotNull(shader->definition, "Shader definition cannot be null"); assertNotNull(shader->definition, "Shader definition cannot be NULL");
assertNotNull(shader->definition->setMaterial, "Def lacks setMaterial"); assertNotNull(shader->definition->setMaterial, "Def lacks setMaterial");
return shader->definition->setMaterial(shader, material); return shader->definition->setMaterial(shader, material);
} }
errorret_t shaderDispose(shader_t *shader) { errorret_t shaderDispose(shader_t *shader) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
bound = NULL; bound = NULL;
errorChain(shaderDisposePlatform(shader)); errorChain(shaderDisposePlatform(shader));
errorOk(); errorOk();
+3 -3
View File
@@ -41,10 +41,10 @@ errorret_t shaderListInit() {
} }
assertNotNull( assertNotNull(
SHADER_LIST_DEFS[i].shader, "Shader cannot be null" SHADER_LIST_DEFS[i].shader, "Shader cannot be NULL"
); );
assertNotNull( assertNotNull(
SHADER_LIST_DEFS[i].definition, "Shader definition cannot be null" SHADER_LIST_DEFS[i].definition, "Shader definition cannot be NULL"
); );
errorChain(shaderInit( errorChain(shaderInit(
@@ -78,7 +78,7 @@ errorret_t shaderListDispose(void) {
} }
assertNotNull( assertNotNull(
SHADER_LIST_DEFS[i].shader, "Shader cannot be null" SHADER_LIST_DEFS[i].shader, "Shader cannot be NULL"
); );
errorChain(shaderDispose(SHADER_LIST_DEFS[i].shader)); errorChain(shaderDispose(SHADER_LIST_DEFS[i].shader));
+6 -5
View File
@@ -31,9 +31,9 @@ errorret_t spriteBatchBuffer(
shader_t *shader, shader_t *shader,
const shadermaterial_t material const shadermaterial_t material
) { ) {
assertNotNull(sprites, "Sprites cannot be null"); assertNotNull(sprites, "Sprites cannot be NULL");
assertTrue(count > 0, "Count must be greater than zero"); assertTrue(count > 0, "Count must be greater than zero");
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be NULL");
// Did the shader or material data change? // Did the shader or material data change?
if(shader != SPRITEBATCH.shader) { if(shader != SPRITEBATCH.shader) {
@@ -76,7 +76,8 @@ errorret_t spriteBatchBuffer(
// Buffer to the mesh vertices. // Buffer to the mesh vertices.
spriteBatchBufferToMesh( spriteBatchBufferToMesh(
sprites + (count - remaining), batchCount, v, batchCount * QUAD_VERTEX_COUNT sprites + (count - remaining), batchCount, v,
batchCount * QUAD_VERTEX_COUNT
); );
SPRITEBATCH.spriteCount += batchCount; SPRITEBATCH.spriteCount += batchCount;
remaining -= batchCount; remaining -= batchCount;
@@ -91,9 +92,9 @@ void spriteBatchBufferToMesh(
meshvertex_t *vertices, meshvertex_t *vertices,
const uint32_t verticesSize const uint32_t verticesSize
) { ) {
assertNotNull(sprites, "Sprites cannot be null"); assertNotNull(sprites, "Sprites cannot be NULL");
assertTrue(count > 0, "Count must be greater than zero"); assertTrue(count > 0, "Count must be greater than zero");
assertNotNull(vertices, "Vertices cannot be null"); assertNotNull(vertices, "Vertices cannot be NULL");
assertTrue( assertTrue(
verticesSize >= count * QUAD_VERTEX_COUNT, "Vertices array too small" verticesSize >= count * QUAD_VERTEX_COUNT, "Vertices array too small"
); );
@@ -27,7 +27,7 @@ typedef struct {
* @param y Screen y position of the sprite's top-left corner. * @param y Screen y position of the sprite's top-left corner.
* @param width Width of the sprite in screen space. * @param width Width of the sprite in screen space.
* @param height Height of the sprite in screen space. * @param height Height of the sprite in screen space.
* @returns The populated sprite. * @return The populated sprite.
*/ */
spritebatchsprite_t spriteBatchSpriteTilesetPosition( spritebatchsprite_t spriteBatchSpriteTilesetPosition(
const tileset_t *tileset, const tileset_t *tileset,
+20 -10
View File
@@ -82,9 +82,11 @@ const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
// Caps Lock's row widths becomes a column height here, centered // Caps Lock's row widths becomes a column height here, centered
// vertically). Backslash was never drawn anyway, and isn't a key this // vertically). Backslash was never drawn anyway, and isn't a key this
// virtual keyboard can type - see FONT_ICON_BACKSPACE. // virtual keyboard can type - see FONT_ICON_BACKSPACE.
{ 0x00, 0x00, 0x08, 0x1F, 0x3F, 0x3F, 0x1F, 0x08, 0x00, 0x00 }, // FONT_ICON_BACKSPACE // FONT_ICON_BACKSPACE
{ 0x00, 0x00, 0x08, 0x1F, 0x3F, 0x3F, 0x1F, 0x08, 0x00, 0x00 },
{ 0x00, 0x18, 0x08, 0x08, 0x08, 0x08, 0x08, 0x18, 0x00, 0x00 }, // ] { 0x00, 0x18, 0x08, 0x08, 0x08, 0x08, 0x08, 0x18, 0x00, 0x00 }, // ]
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ^ (not drawn in source font) // ^ (not drawn in source font)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E }, // _ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E }, // _
// Custom icon glyph, not a real backtick - an up arrow for Shift, same // Custom icon glyph, not a real backtick - an up arrow for Shift, same
// head as Caps Lock's (see FONT_ICON_CAPSLOCK) but with a shaft 2px // head as Caps Lock's (see FONT_ICON_CAPSLOCK) but with a shaft 2px
@@ -92,7 +94,8 @@ const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
// lighter/broken version of Caps Lock's thicker uninterrupted one. // lighter/broken version of Caps Lock's thicker uninterrupted one.
// Backtick was never drawn anyway, and isn't a key this virtual // Backtick was never drawn anyway, and isn't a key this virtual
// keyboard can type - see FONT_ICON_SHIFT. // keyboard can type - see FONT_ICON_SHIFT.
{ 0x0C, 0x1E, 0x3F, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x0C, 0x00 }, // FONT_ICON_SHIFT // FONT_ICON_SHIFT
{ 0x0C, 0x1E, 0x3F, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x0C, 0x00 },
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // a { 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // a
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // b { 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // b
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // c { 0x00, 0x00, 0x00, 0x1C, 0x22, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // c
@@ -125,21 +128,25 @@ const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
// hooks left into a leftward-pointing arrowhead, i.e. "<-|" rotated // hooks left into a leftward-pointing arrowhead, i.e. "<-|" rotated
// into an L. Pipe was never drawn anyway, and isn't a key this // into an L. Pipe was never drawn anyway, and isn't a key this
// virtual keyboard can type - see FONT_ICON_NEWLINE. // virtual keyboard can type - see FONT_ICON_NEWLINE.
{ 0x02, 0x02, 0x02, 0x02, 0x0E, 0x1E, 0x08, 0x00, 0x00, 0x00 }, // FONT_ICON_NEWLINE // FONT_ICON_NEWLINE
{ 0x02, 0x02, 0x02, 0x02, 0x0E, 0x1E, 0x08, 0x00, 0x00, 0x00 },
{ 0x00, 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10, 0x00, 0x00 }, // } { 0x00, 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10, 0x00, 0x00 }, // }
// Custom icon glyph, not a real tilde - a spacebar symbol for the // Custom icon glyph, not a real tilde - a spacebar symbol for the
// keyboard's space key: an underscore with a tick at each end, like // keyboard's space key: an underscore with a tick at each end, like
// "|___|". Tilde was never drawn anyway, and was explicitly dropped // "|___|". Tilde was never drawn anyway, and was explicitly dropped
// from this virtual keyboard's own key set - see FONT_ICON_SPACE. // from this virtual keyboard's own key set - see FONT_ICON_SPACE.
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x3F }, // FONT_ICON_SPACE // FONT_ICON_SPACE
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x3F },
// Custom icon glyph, not a real ASCII character - a thick, solid, // Custom icon glyph, not a real ASCII character - a thick, solid,
// uninterrupted up arrow for Caps Lock (contrast FONT_ICON_SHIFT's // uninterrupted up arrow for Caps Lock (contrast FONT_ICON_SHIFT's
// same head but a thinner, gapped shaft). Assigned to char code 127 // same head but a thinner, gapped shaft). Assigned to char code 127
// (DEL) since that codepoint is never legitimately typed text and // (DEL) since that codepoint is never legitimately typed text and
// (unlike 128+) is still a positive value regardless of whether this // (unlike 128+) is still a positive value regardless of whether this
// platform's plain `char` is signed - see FONT_ICON_CAPSLOCK. // platform's plain `char` is signed - see FONT_ICON_CAPSLOCK.
{ 0x0C, 0x1E, 0x3F, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x00 }, // FONT_ICON_CAPSLOCK // FONT_ICON_CAPSLOCK
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // unused trailing tile { 0x0C, 0x1E, 0x3F, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x00 },
// unused trailing tile
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
}; };
errorret_t fontDefaultInit(void) { errorret_t fontDefaultInit(void) {
@@ -155,7 +162,8 @@ errorret_t fontDefaultInit(void) {
for(uint16_t i = 0; i < FONT_DEFAULT_TILE_COUNT; i++) { for(uint16_t i = 0; i < FONT_DEFAULT_TILE_COUNT; i++) {
const uint16_t tileX = (i % FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_WIDTH; const uint16_t tileX = (i % FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_WIDTH;
const uint16_t tileY = (i / FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_HEIGHT; const uint16_t tileY =
(i / FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_HEIGHT;
for(uint8_t row = 0; row < FONT_DEFAULT_TILE_HEIGHT; row++) { for(uint8_t row = 0; row < FONT_DEFAULT_TILE_HEIGHT; row++) {
const uint8_t bits = FONT_DEFAULT_GLYPHS[i][row]; const uint8_t bits = FONT_DEFAULT_GLYPHS[i][row];
@@ -172,8 +180,10 @@ errorret_t fontDefaultInit(void) {
FONT_DEFAULT_TILESET.columns = FONT_DEFAULT_COLUMNS; FONT_DEFAULT_TILESET.columns = FONT_DEFAULT_COLUMNS;
FONT_DEFAULT_TILESET.rows = FONT_DEFAULT_ROWS; FONT_DEFAULT_TILESET.rows = FONT_DEFAULT_ROWS;
FONT_DEFAULT_TILESET.tileCount = FONT_DEFAULT_TILE_COUNT; FONT_DEFAULT_TILESET.tileCount = FONT_DEFAULT_TILE_COUNT;
FONT_DEFAULT_TILESET.uv[0] = (float_t)FONT_DEFAULT_TILE_WIDTH / (float_t)width; FONT_DEFAULT_TILESET.uv[0] =
FONT_DEFAULT_TILESET.uv[1] = (float_t)FONT_DEFAULT_TILE_HEIGHT / (float_t)height; (float_t)FONT_DEFAULT_TILE_WIDTH / (float_t)width;
FONT_DEFAULT_TILESET.uv[1] =
(float_t)FONT_DEFAULT_TILE_HEIGHT / (float_t)height;
const texturedata_t data = { .rgbaColors = pixels }; const texturedata_t data = { .rgbaColors = pixels };
errorret_t textureResult = textureInit( errorret_t textureResult = textureInit(
+3 -28
View File
@@ -23,17 +23,10 @@
#include "console/console.h" #include "console/console.h"
#include "save/save.h" #include "save/save.h"
#include "audio/audio.h" #include "audio/audio.h"
#include "audio/mixer/audiomixer.h"
engine_t ENGINE; engine_t ENGINE;
void engineTestToneOnEnd(audiostream_t *stream) {
consolePrint("Test tone finished playing");
}
void engineTestToneOnLoop(audiostream_t *stream) {
consolePrint("Test tone looped");
}
errorret_t engineInit(const int32_t argc, const char_t **argv) { errorret_t engineInit(const int32_t argc, const char_t **argv) {
assertInit(); assertInit();
memoryZero(&ENGINE, sizeof(engine_t)); memoryZero(&ENGINE, sizeof(engine_t));
@@ -59,25 +52,6 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
#endif #endif
errorChain(sceneInit()); errorChain(sceneInit());
// Smoke-tests the audio subsystem end to end (asset loading -> PCM
// streaming -> platform playback) against a real WAV asset rather than
// synthesizing PCM data at runtime.
assetentry_t *testToneEntry = assetLock(
"audio/pepsiman.wav", ASSET_LOADER_TYPE_WAV, NULL
// "audio/audiotest.wav", ASSET_LOADER_TYPE_WAV, NULL
);
errorChain(assetRequireLoaded(testToneEntry));
audiostream_t *stream = audioAquireStream(testToneEntry);
assertNotNull(stream, "No free audio stream slots available.");
errorChain(audioStreamInit(stream, testToneEntry));
assetUnlockEntry(testToneEntry); // The stream now holds its own lock.
stream->onEnd = engineTestToneOnEnd;
stream->onLoop = engineTestToneOnLoop;
audioStreamSetLooping(stream, true);
audioStreamPlay(stream);
consolePrint("Engine initialized"); consolePrint("Engine initialized");
#ifdef DUSK_ASSERTIONS_FAKED #ifdef DUSK_ASSERTIONS_FAKED
@@ -100,7 +74,7 @@ errorret_t engineUpdate(void) {
timeUpdate(); timeUpdate();
inputUpdate(); inputUpdate();
consoleUpdate(); consoleUpdate();
errorChain(audioUpdate()); errorChain(audioUpdateEarly());
errorChain(rpgUpdate()); errorChain(rpgUpdate());
errorChain(sceneUpdate()); errorChain(sceneUpdate());
errorChain(assetUpdate()); errorChain(assetUpdate());
@@ -108,6 +82,7 @@ errorret_t engineUpdate(void) {
// Render // Render
errorChain(displayUpdate()); errorChain(displayUpdate());
errorChain(audioUpdateLate());
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false; if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
errorOk(); errorOk();
} }
+4 -4
View File
@@ -152,7 +152,7 @@ float_t inputGetLastValue(const inputaction_t action) {
const inputaction_t negY, const inputaction_t posY, const inputaction_t negY, const inputaction_t posY,
vec2 result vec2 result
) { ) {
assertNotNull(result, "Result vector cannot be null"); assertNotNull(result, "Result vector cannot be NULL");
result[0] = inputAxisDynamic(negX, posX); result[0] = inputAxisDynamic(negX, posX);
result[1] = inputAxisDynamic(negY, posY); result[1] = inputAxisDynamic(negY, posY);
} }
@@ -162,7 +162,7 @@ float_t inputGetLastValue(const inputaction_t action) {
const inputaction_t negY, const inputaction_t posY, const inputaction_t negY, const inputaction_t posY,
vec2 result vec2 result
) { ) {
assertNotNull(result, "Result vector cannot be null"); assertNotNull(result, "Result vector cannot be NULL");
float_t x = inputAxisDynamic(negX, posX); float_t x = inputAxisDynamic(negX, posX);
float_t y = inputAxisDynamic(negY, posY); float_t y = inputAxisDynamic(negY, posY);
float_t mag = sqrtf(x * x + y * y); float_t mag = sqrtf(x * x + y * y);
@@ -208,7 +208,7 @@ void inputAxis2D(
const inputaction_t negY, const inputaction_t posY, const inputaction_t negY, const inputaction_t posY,
vec2 result vec2 result
) { ) {
assertNotNull(result, "Result vector cannot be null"); assertNotNull(result, "Result vector cannot be NULL");
result[0] = inputAxis(negX, posX); result[0] = inputAxis(negX, posX);
result[1] = inputAxis(negY, posY); result[1] = inputAxis(negY, posY);
} }
@@ -218,7 +218,7 @@ void inputAngle2D(
const inputaction_t negY, const inputaction_t posY, const inputaction_t negY, const inputaction_t posY,
vec2 result vec2 result
) { ) {
assertNotNull(result, "Result vector cannot be null"); assertNotNull(result, "Result vector cannot be NULL");
float_t x = inputAxis(negX, posX); float_t x = inputAxis(negX, posX);
float_t y = inputAxis(negY, posY); float_t y = inputAxis(negY, posY);
float_t mag = sqrtf(x * x + y * y); float_t mag = sqrtf(x * x + y * y);
+33 -3
View File
@@ -34,13 +34,43 @@ errorret_t localeManagerInit();
errorret_t localeManagerSetLocale(const localeinfo_t *locale); errorret_t localeManagerSetLocale(const localeinfo_t *locale);
/** /**
* Get a localized string for the given message ID. * Get a localized string for the given message ID verbatim, with no
* * printf-style formatting applied - use this (rather than
* localeManagerGetText with no variadic args) whenever the raw string
* is displayed as-is, or cached to be formatted later (e.g. a
* "_format" message ID whose %-specifiers are filled in by the caller
* itself via stringFormat once the actual values are known). Passing a
* "_format" string through localeManagerGetText/GetTextArgs instead
* would consume it immediately as a format string with zero args,
* which is wrong for this use, and would also mishandle any literal
* '%' in a plain display string.
*
* @param id The message ID to retrieve. * @param id The message ID to retrieve.
* @param buffer Buffer to write the retrieved string to. * @param buffer Buffer to write the retrieved string to.
* @param bufferSize Size of the buffer. * @param bufferSize Size of the buffer.
* @param plural Plural index to retrieve. * @param plural Plural index to retrieve.
* @param ... Additional arguments for formatting the string. * @return An error code if a failure occurs.
*/
#define localeManagerGetString(id, buffer, bufferSize, plural) \
assetLocaleGetString( \
&LOCALE.entry->data.locale, \
id, \
plural, \
buffer, \
bufferSize \
)
/**
* Get a localized string for the given message ID, formatted
* printf-style with the given variadic arguments.
*
* @param id The message ID to retrieve.
* @param buffer Buffer to write the retrieved string to.
* @param bufferSize Size of the buffer.
* @param plural Plural index to retrieve.
* @param ... Arguments for formatting the string - must not be empty,
* since the retrieved string is always run through vsnprintf; see
* localeManagerGetString for a message ID with no format args at all.
* @return An error code if a failure occurs. * @return An error code if a failure occurs.
*/ */
#define localeManagerGetText(id, buffer, bufferSize, plural, ...) \ #define localeManagerGetText(id, buffer, bufferSize, plural, ...) \
+3 -1
View File
@@ -214,7 +214,9 @@ void battleMoveTeamFirst(const battlefighterteam_t team) {
sorted[count++] = BATTLE.executionOrder[i]; sorted[count++] = BATTLE.executionOrder[i];
} }
memoryCopy(BATTLE.executionOrder, sorted, sizeof(uint8_t) * BATTLE.executionCount); memoryCopy(
BATTLE.executionOrder, sorted, sizeof(uint8_t) * BATTLE.executionCount
);
} }
battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter) { battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter) {
+1 -1
View File
@@ -82,6 +82,6 @@ void battleFighterInit(
* is not dead). * is not dead).
* *
* @param fighter Pointer to the fighter to check. * @param fighter Pointer to the fighter to check.
* @returns True if the fighter can act. * @return True if the fighter can act.
*/ */
bool_t battleFighterIsAlive(const battlefighter_t *fighter); bool_t battleFighterIsAlive(const battlefighter_t *fighter);
+122
View File
@@ -65,6 +65,17 @@ typedef struct cutscene_s {
#define CUTSCENE_RESTART() \ #define CUTSCENE_RESTART() \
{ .type = CUTSCENE_ITEM_TYPE_RESTART } { .type = CUTSCENE_ITEM_TYPE_RESTART }
// Blocks the cutscene here indefinitely - it never completes on its own,
// only cutsceneGoTo (called externally, e.g. from a UI callback) can move
// execution past it.
#define CUTSCENE_IDLE() \
{ .type = CUTSCENE_ITEM_TYPE_IDLE }
// Opens a full-screen UI panel (e.g. the main menu) declaratively, then
// immediately continues on to whatever follows this item.
#define CUTSCENE_UI_SHOW(SCREEN) \
{ .type = CUTSCENE_ITEM_TYPE_UI_SHOW, .uiShow = { .screen = SCREEN } }
// Requests a switch to a different SCENE_TYPE via sceneSet, then // Requests a switch to a different SCENE_TYPE via sceneSet, then
// immediately continues on to whatever follows this item - the switch // immediately continues on to whatever follows this item - the switch
// itself doesn't happen until the next sceneUpdate() tick, so it does // itself doesn't happen until the next sceneUpdate() tick, so it does
@@ -389,3 +400,114 @@ typedef struct cutscene_s {
), \ ), \
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \ CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED) CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
// Longhand - every audioMixerQueuePlay() parameter. See
// CUTSCENE_AUDIO_PLAY_SIMPLE/CUTSCENE_AUDIO_PLAY_LOOPED below for the
// shorthands.
#define CUTSCENE_AUDIO_PLAY( \
FILE, CHANNEL, VOLUME, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_PLAY, \
.audioPlay = { \
.file = FILE, \
.channel = CHANNEL, \
.volume = VOLUME, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
}
// Shorthand: play FILE on CHANNEL once, full volume, centered (0.0f, same
// as AUDIO_STREAM_CENTER), no loop.
#define CUTSCENE_AUDIO_PLAY_SIMPLE(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, false, 0, -1.0f, 0.0f)
// Shorthand: play FILE on CHANNEL looping the whole clip forever, full
// volume, centered (0.0f, same as AUDIO_STREAM_CENTER).
#define CUTSCENE_AUDIO_PLAY_LOOPED(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, true, 0, -1.0f, 0.0f)
#define CUTSCENE_AUDIO_STOP(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_STOP, .audioStopChannel = CHANNEL }
#define CUTSCENE_AUDIO_PAUSE(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_PAUSE, .audioPauseChannel = CHANNEL }
#define CUTSCENE_AUDIO_RESUME(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_RESUME, .audioResumeChannel = CHANNEL }
// Longhand - starts CHANNEL fading from FROM to TO over DURATION seconds,
// eased by EASING. Doesn't wait for it - pair with
// CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) to block until it finishes. See
// CUTSCENE_AUDIO_FADE_OUT/CUTSCENE_AUDIO_FADE_IN below for the shorthands;
// use this directly for a custom range, e.g.
// CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.3f, 5.0f, EASING_LINEAR) to fade
// down to "playing quietly" rather than silent.
#define CUTSCENE_AUDIO_FADE(CHANNEL, FROM, TO, DURATION, EASING) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE, \
.audioFade = { \
.channel = CHANNEL, \
.from = FROM, \
.to = TO, \
.duration = DURATION, \
.easing = EASING \
} \
}
// Shorthand: fade CHANNEL from full volume to silent over DURATION seconds.
#define CUTSCENE_AUDIO_FADE_OUT(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.0f, DURATION, EASING_LINEAR)
// Shorthand: fade CHANNEL from silent to full volume over DURATION seconds.
#define CUTSCENE_AUDIO_FADE_IN(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 0.0f, 1.0f, DURATION, EASING_LINEAR)
// Waits until CHANNEL's fade (started elsewhere by CUTSCENE_AUDIO_FADE)
// has finished - a no-op wait if CHANNEL isn't fading.
#define CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT, \
.audioFadeWaitChannel = CHANNEL \
}
#define CUTSCENE_AUDIO_SET_PAN(CHANNEL, PAN) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN, \
.audioSetPan = { .channel = CHANNEL, .pan = PAN } \
}
#define CUTSCENE_AUDIO_SET_LOOP( \
CHANNEL, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP, \
.audioSetLoop = { \
.channel = CHANNEL, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
}
// Combined form of CUTSCENE_AUDIO_SET_PAN + CUTSCENE_AUDIO_SET_LOOP, for
// setting both at once rather than as two separate items.
#define CUTSCENE_AUDIO_SET( \
CHANNEL, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET, \
.audioSet = { \
.channel = CHANNEL, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
}
+18 -1
View File
@@ -10,6 +10,8 @@
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "asset/asset.h"
#include "ui/overlay/uifatalerror.h"
cutscenesystem_t CUTSCENE_SYSTEM; cutscenesystem_t CUTSCENE_SYSTEM;
@@ -61,6 +63,21 @@ void cutsceneSystemStartCutsceneAndGoToMarker(
cutsceneGoTo(marker); cutsceneGoTo(marker);
} }
void cutsceneSystemLoad(const char_t *file) {
char_t path[ASSET_FILE_NAME_MAX];
stringFormat(path, sizeof(path), "cutscenes/%s", file);
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL);
errorret_t result = assetRequireLoaded(entry);
if(errorIsNotOk(result)) {
errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL);
return;
}
cutsceneSystemStartCutscene(&entry->data.cutscene.cutscene);
}
void cutsceneRestart(void) { void cutsceneRestart(void) {
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.scene, "cutsceneRestart called with no cutscene running" CUTSCENE_SYSTEM.scene, "cutsceneRestart called with no cutscene running"
@@ -119,7 +136,7 @@ void cutsceneSystemNext() {
// Start item. // Start item.
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem(); const cutsceneitem_t *item = cutsceneSystemGetCurrentItem();
memset(&CUTSCENE_SYSTEM.data, 0, sizeof(CUTSCENE_SYSTEM.data)); memoryZero(&CUTSCENE_SYSTEM.data, sizeof(CUTSCENE_SYSTEM.data));
cutsceneItemStart(item, &CUTSCENE_SYSTEM.data); cutsceneItemStart(item, &CUTSCENE_SYSTEM.data);
} }
+20 -4
View File
@@ -96,6 +96,22 @@ void cutsceneSystemStartCutsceneAndGoToMarker(
const char_t *marker const char_t *marker
); );
/**
* Locks, loads and immediately starts a cutscene asset by file name,
* e.g. cutsceneSystemLoad("main_menu.jsonc") loads and starts
* assets/cutscenes/main_menu.jsonc - same lock/assetRequireLoaded/start
* sequence as sceneInitialInit's INITIAL_CUTSCENE_ENTRY. The entry is
* locked forever (never unlocked), same lifetime convention as
* LOCALE.entry - it's fine to call this again later for the same file,
* it'll just resolve to the same already-loaded entry. Opens the fatal
* error overlay (see uiFatalErrorOpen) instead of starting anything if
* the asset fails to load.
*
* @param file Cutscene file name (with .jsonc extension), relative to
* assets/cutscenes/.
*/
void cutsceneSystemLoad(const char_t *file);
/** /**
* Restarts the currently running cutscene from its first item, * Restarts the currently running cutscene from its first item,
* preserving whatever interact/interacted entities triggered it. * preserving whatever interact/interacted entities triggered it.
@@ -130,7 +146,7 @@ void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete);
* Asserts the resolved entity is within bounds. * Asserts the resolved entity is within bounds.
* *
* @param entityIndex Raw entity index or sentinel value. * @param entityIndex Raw entity index or sentinel value.
* @returns Pointer to the resolved entity. * @return Pointer to the resolved entity.
*/ */
entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex); entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
@@ -139,7 +155,7 @@ entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
* a concrete map area ID. * a concrete map area ID.
* *
* @param areaId Raw map area ID or sentinel value. * @param areaId Raw map area ID or sentinel value.
* @returns The resolved map area ID. * @return The resolved map area ID.
*/ */
uint8_t cutsceneSystemGetAreaId(const uint8_t areaId); uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
@@ -148,7 +164,7 @@ uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
* sentinel) to a concrete UI_TEXTBOX_MINI_LIST slot index. * sentinel) to a concrete UI_TEXTBOX_MINI_LIST slot index.
* *
* @param index Raw slot index or sentinel value. * @param index Raw slot index or sentinel value.
* @returns The resolved slot index. * @return The resolved slot index.
*/ */
uint8_t cutsceneSystemGetTextMiniId(const uint8_t index); uint8_t cutsceneSystemGetTextMiniId(const uint8_t index);
@@ -158,7 +174,7 @@ uint8_t cutsceneSystemGetTextMiniId(const uint8_t index);
* once its keyboard closes). Empty ("") if nothing has been cached yet * once its keyboard closes). Empty ("") if nothing has been cached yet
* for the running cutscene. * for the running cutscene.
* *
* @returns The cached text. * @return The cached text.
*/ */
const char_t * cutsceneSystemGetTextCache(void); const char_t * cutsceneSystemGetTextCache(void);
@@ -6,6 +6,7 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
cutsceneitem.c cutsceneitem.c
cutsceneitembase.c
cutscenecallback.c cutscenecallback.c
cutsceneprint.c cutsceneprint.c
) )
@@ -17,3 +18,5 @@ add_subdirectory(maparea)
add_subdirectory(ui) add_subdirectory(ui)
add_subdirectory(battle) add_subdirectory(battle)
add_subdirectory(save) add_subdirectory(save)
add_subdirectory(audio)
add_subdirectory(json)
@@ -0,0 +1,17 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
cutsceneaudioplay.c
cutsceneaudiostop.c
cutsceneaudiopause.c
cutsceneaudioresume.c
cutsceneaudiofade.c
cutsceneaudiofadewait.c
cutsceneaudiosetpan.c
cutsceneaudiosetloop.c
cutsceneaudioset.c
)
@@ -0,0 +1,61 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
#include "rpg/cutscene/item/json/cutscenejsoneasing.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
void cutsceneAudioFadeStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerFadeTo(
item->audioFade.channel,
item->audioFade.from,
item->audioFade.to,
item->audioFade.duration,
item->audioFade.easing
);
}
bool_t cutsceneAudioFadeUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioFadeLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
audiomixerchannel_t channelValue;
if(!cutsceneJsonLookupAudioChannel(
yyjson_get_str(yyjson_obj_get(itemObj, "channel")), &channelValue
)) {
errorThrow("Cutscene item (AUDIO_FADE): invalid 'channel'");
}
item->audioFade.channel = channelValue;
item->audioFade.from = cutsceneJsonGetFloat(itemObj, "from", 0.0f);
item->audioFade.to = cutsceneJsonGetFloat(itemObj, "to", 0.0f);
item->audioFade.duration = cutsceneJsonGetFloat(itemObj, "duration", 0.0f);
const char_t *easingName =
yyjson_get_str(yyjson_obj_get(itemObj, "easing"));
easingtype_t easingValue = EASING_LINEAR;
if(easingName != NULL &&
!cutsceneJsonLookupEasing(easingName, &easingValue)) {
errorThrow("Cutscene item (AUDIO_FADE): invalid 'easing'");
}
item->audioFade.easing = easingValue;
errorOk();
}
@@ -0,0 +1,60 @@
/**
* 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"
#include "animation/easing.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct {
audiomixerchannel_t channel;
float_t from;
float_t to;
float_t duration;
easingtype_t easing;
} cutsceneaudiofade_t;
/**
* Starts an audio fade step (starts the fade via audioMixerFadeTo() -
* doesn't wait for it; pair with CUTSCENE_AUDIO_FADE_WAIT to block on it).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioFadeStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio fade step (always completes immediately - the fade
* itself keeps running independently of cutscene progression).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioFadeUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_FADE cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_FADE needs no pool storage).
* @param poolOffset Unused (AUDIO_FADE needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioFadeLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,26 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
bool_t cutsceneAudioFadeWaitUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return !audioMixerIsFading(item->audioFadeWaitChannel);
}
errorret_t cutsceneAudioFadeWaitLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
return cutsceneJsonLoadAudioChannelOnly(itemObj, &item->audioFadeWaitChannel);
}
@@ -0,0 +1,40 @@
/**
* 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"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Updates an audio fade-wait step, completing once the watched channel's
* fade (started by a CUTSCENE_AUDIO_FADE elsewhere) finishes. Has no Start
* callback -- there's nothing to do until the fade is actually done.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true once the channel is no longer fading.
*/
bool_t cutsceneAudioFadeWaitUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_FADE_WAIT cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_FADE_WAIT needs no pool storage).
* @param poolOffset Unused (AUDIO_FADE_WAIT needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioFadeWaitLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
void cutsceneAudioPauseStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerPause(item->audioPauseChannel);
}
bool_t cutsceneAudioPauseUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioPauseLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
return cutsceneJsonLoadAudioChannelOnly(itemObj, &item->audioPauseChannel);
}
@@ -0,0 +1,49 @@
/**
* 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"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Starts an audio pause step (pauses the channel immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioPauseStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio pause step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioPauseUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_PAUSE cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_PAUSE needs no pool storage).
* @param poolOffset Unused (AUDIO_PAUSE needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioPauseLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,64 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
void cutsceneAudioPlayStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerQueuePlay(
item->audioPlay.file,
item->audioPlay.channel,
item->audioPlay.volume,
item->audioPlay.pan,
item->audioPlay.looping,
item->audioPlay.loopCount,
item->audioPlay.loopStart,
item->audioPlay.loopTo
);
}
bool_t cutsceneAudioPlayUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioPlayLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
if(!cutsceneJsonCopyString(
itemObj, "file", NULL, item->audioPlay.file, AUDIO_PATH_MAX
)) {
errorThrow("Cutscene item (AUDIO_PLAY): missing/too-long 'file'");
}
audiomixerchannel_t channelValue;
if(!cutsceneJsonLookupAudioChannel(
yyjson_get_str(yyjson_obj_get(itemObj, "channel")), &channelValue
)) {
errorThrow("Cutscene item (AUDIO_PLAY): invalid 'channel'");
}
item->audioPlay.channel = channelValue;
item->audioPlay.volume = cutsceneJsonGetFloat(itemObj, "volume", 1.0f);
item->audioPlay.pan = cutsceneJsonGetFloat(itemObj, "pan", 0.0f);
item->audioPlay.looping = cutsceneJsonGetBool(itemObj, "looping", false);
item->audioPlay.loopCount =
(uint8_t)cutsceneJsonGetInt(itemObj, "loopCount", 0);
item->audioPlay.loopStart =
cutsceneJsonGetFloat(itemObj, "loopStart", -1.0f);
item->audioPlay.loopTo = cutsceneJsonGetFloat(itemObj, "loopTo", 0.0f);
errorOk();
}
@@ -0,0 +1,62 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct {
char_t file[AUDIO_PATH_MAX];
audiomixerchannel_t channel;
float_t volume;
float_t pan;
bool_t looping;
uint8_t loopCount;
float_t loopStart;
float_t loopTo;
} cutsceneaudioplay_t;
/**
* Starts an audio play step (queues the sound via audioMixerQueuePlay() -
* see its own comment on when it actually starts).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioPlayStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio play step (always completes immediately - the sound
* keeps loading/playing independently of cutscene progression).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioPlayUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_PLAY cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_PLAY needs no pool storage).
* @param poolOffset Unused (AUDIO_PLAY needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioPlayLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
void cutsceneAudioResumeStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerResume(item->audioResumeChannel);
}
bool_t cutsceneAudioResumeUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioResumeLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
return cutsceneJsonLoadAudioChannelOnly(itemObj, &item->audioResumeChannel);
}
@@ -0,0 +1,49 @@
/**
* 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"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Starts an audio resume step (resumes the channel immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioResumeStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio resume step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioResumeUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_RESUME cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_RESUME needs no pool storage).
* @param poolOffset Unused (AUDIO_RESUME needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioResumeLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,56 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
void cutsceneAudioSetStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerSetPan(item->audioSet.channel, item->audioSet.pan);
audioMixerSetLoop(
item->audioSet.channel,
item->audioSet.looping,
item->audioSet.loopCount,
item->audioSet.loopStart,
item->audioSet.loopTo
);
}
bool_t cutsceneAudioSetUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioSetLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
audiomixerchannel_t channelValue;
if(!cutsceneJsonLookupAudioChannel(
yyjson_get_str(yyjson_obj_get(itemObj, "channel")), &channelValue
)) {
errorThrow("Cutscene item (AUDIO_SET): invalid 'channel'");
}
item->audioSet.channel = channelValue;
item->audioSet.pan = cutsceneJsonGetFloat(itemObj, "pan", 0.0f);
item->audioSet.looping = cutsceneJsonGetBool(itemObj, "looping", true);
item->audioSet.loopCount =
(uint8_t)cutsceneJsonGetInt(itemObj, "loopCount", 0);
item->audioSet.loopStart =
cutsceneJsonGetFloat(itemObj, "loopStart", -1.0f);
item->audioSet.loopTo = cutsceneJsonGetFloat(itemObj, "loopTo", 0.0f);
errorOk();
}
@@ -0,0 +1,61 @@
/**
* 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"
#include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct {
audiomixerchannel_t channel;
float_t pan;
bool_t looping;
uint8_t loopCount;
float_t loopStart;
float_t loopTo;
} cutsceneaudioset_t;
/**
* Starts an audio set step - applies pan and looping behaviour together in
* one item (via audioMixerSetPan()/audioMixerSetLoop()), for when you want
* to change both at once rather than using CUTSCENE_AUDIO_SET_PAN/
* CUTSCENE_AUDIO_SET_LOOP separately.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioSetStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio set step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioSetUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_SET cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_SET needs no pool storage).
* @param poolOffset Unused (AUDIO_SET needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioSetLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,54 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
void cutsceneAudioSetLoopStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerSetLoop(
item->audioSetLoop.channel,
item->audioSetLoop.looping,
item->audioSetLoop.loopCount,
item->audioSetLoop.loopStart,
item->audioSetLoop.loopTo
);
}
bool_t cutsceneAudioSetLoopUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioSetLoopLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
audiomixerchannel_t channelValue;
if(!cutsceneJsonLookupAudioChannel(
yyjson_get_str(yyjson_obj_get(itemObj, "channel")), &channelValue
)) {
errorThrow("Cutscene item (AUDIO_SET_LOOP): invalid 'channel'");
}
item->audioSetLoop.channel = channelValue;
item->audioSetLoop.looping = cutsceneJsonGetBool(itemObj, "looping", true);
item->audioSetLoop.loopCount =
(uint8_t)cutsceneJsonGetInt(itemObj, "loopCount", 0);
item->audioSetLoop.loopStart =
cutsceneJsonGetFloat(itemObj, "loopStart", -1.0f);
item->audioSetLoop.loopTo = cutsceneJsonGetFloat(itemObj, "loopTo", 0.0f);
errorOk();
}
@@ -0,0 +1,58 @@
/**
* 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"
#include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct {
audiomixerchannel_t channel;
bool_t looping;
uint8_t loopCount;
float_t loopStart;
float_t loopTo;
} cutsceneaudiosetloop_t;
/**
* Starts an audio set-loop step (applies the new looping behaviour
* immediately, via audioMixerSetLoop()).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioSetLoopStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio set-loop step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioSetLoopUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_SET_LOOP cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_SET_LOOP needs no pool storage).
* @param poolOffset Unused (AUDIO_SET_LOOP needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioSetLoopLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,43 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
void cutsceneAudioSetPanStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerSetPan(item->audioSetPan.channel, item->audioSetPan.pan);
}
bool_t cutsceneAudioSetPanUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioSetPanLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
audiomixerchannel_t channelValue;
if(!cutsceneJsonLookupAudioChannel(
yyjson_get_str(yyjson_obj_get(itemObj, "channel")), &channelValue
)) {
errorThrow("Cutscene item (AUDIO_SET_PAN): invalid 'channel'");
}
item->audioSetPan.channel = channelValue;
item->audioSetPan.pan = cutsceneJsonGetFloat(itemObj, "pan", 0.0f);
errorOk();
}
@@ -0,0 +1,55 @@
/**
* 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"
#include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct {
audiomixerchannel_t channel;
float_t pan;
} cutsceneaudiosetpan_t;
/**
* Starts an audio set-pan step (applies the new pan immediately, via
* audioMixerSetPan()).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioSetPanStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio set-pan step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioSetPanUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_SET_PAN cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_SET_PAN needs no pool storage).
* @param poolOffset Unused (AUDIO_SET_PAN needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioSetPanLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "audio/mixer/audiomixer.h"
#include "rpg/cutscene/item/json/cutscenejsonaudiochannel.h"
void cutsceneAudioStopStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
audioMixerStop(item->audioStopChannel);
}
bool_t cutsceneAudioStopUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneAudioStopLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
return cutsceneJsonLoadAudioChannelOnly(itemObj, &item->audioStopChannel);
}
@@ -0,0 +1,49 @@
/**
* 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"
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Starts an audio stop step (stops the channel immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneAudioStopStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an audio stop step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @return true always.
*/
bool_t cutsceneAudioStopUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses an AUDIO_STOP cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (AUDIO_STOP needs no pool storage).
* @param poolOffset Unused (AUDIO_STOP needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneAudioStopLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -23,3 +23,17 @@ bool_t cutsceneBattleForceActionUpdate(
) { ) {
return true; return true;
} }
errorret_t cutsceneBattleForceActionLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
item->battleForceAction.fighterIndex =
(uint8_t)yyjson_get_int(yyjson_obj_get(itemObj, "fighterIndex"));
item->battleForceAction.targetIndex =
(uint8_t)yyjson_get_int(yyjson_obj_get(itemObj, "targetIndex"));
errorOk();
}
@@ -7,15 +7,13 @@
#pragma once #pragma once
#include "rpg/battle/battle.h" #include "rpg/battle/battle.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct { typedef struct {
uint8_t fighterIndex; uint8_t fighterIndex;
uint8_t targetIndex; uint8_t targetIndex;
} cutscenebattleforceaction_t; } cutscenebattleforceaction_t;
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
/** /**
* Starts a battle force-action step: immediately queues an attack for the * Starts a battle force-action step: immediately queues an attack for the
* given fighter against the given target, bypassing normal player/AI * given fighter against the given target, bypassing normal player/AI
@@ -34,9 +32,25 @@ void cutsceneBattleForceActionStart(
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
* @returns true always. * @return true always.
*/ */
bool_t cutsceneBattleForceActionUpdate( bool_t cutsceneBattleForceActionUpdate(
const cutsceneitem_t *item, const cutsceneitem_t *item,
cutsceneitemdata_t *data cutsceneitemdata_t *data
); );
/**
* Parses a BATTLE_FORCE_ACTION cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (BATTLE_FORCE_ACTION needs no pool storage).
* @param poolOffset Unused (BATTLE_FORCE_ACTION needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneBattleForceActionLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
@@ -6,6 +6,7 @@
*/ */
#include "rpg/cutscene/item/cutsceneitem.h" #include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/item/json/cutscenejsonbattlestate.h"
bool_t cutsceneBattleWaitStateUpdate( bool_t cutsceneBattleWaitStateUpdate(
const cutsceneitem_t *item, const cutsceneitem_t *item,
@@ -13,3 +14,20 @@ bool_t cutsceneBattleWaitStateUpdate(
) { ) {
return BATTLE.state == item->battleWaitState.state; return BATTLE.state == item->battleWaitState.state;
} }
errorret_t cutsceneBattleWaitStateLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
) {
battlestate_t stateValue;
if(!cutsceneJsonLookupBattleState(
yyjson_get_str(yyjson_obj_get(itemObj, "state")), &stateValue
)) {
errorThrow("Cutscene item (BATTLE_WAIT_STATE): invalid 'state'");
}
item->battleWaitState.state = stateValue;
errorOk();
}
@@ -7,14 +7,12 @@
#pragma once #pragma once
#include "rpg/battle/battle.h" #include "rpg/battle/battle.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct { typedef struct {
battlestate_t state; battlestate_t state;
} cutscenebattlewaitstate_t; } cutscenebattlewaitstate_t;
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
/** /**
* Updates a battle wait-state step, completing once BATTLE.state reaches * Updates a battle wait-state step, completing once BATTLE.state reaches
* the watched state. Has no Start callback -- there's nothing to do until * the watched state. Has no Start callback -- there's nothing to do until
@@ -22,9 +20,25 @@ typedef union cutsceneitemdata_u cutsceneitemdata_t;
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
* @returns true once BATTLE.state equals the watched state. * @return true once BATTLE.state equals the watched state.
*/ */
bool_t cutsceneBattleWaitStateUpdate( bool_t cutsceneBattleWaitStateUpdate(
const cutsceneitem_t *item, const cutsceneitem_t *item,
cutsceneitemdata_t *data cutsceneitemdata_t *data
); );
/**
* Parses a BATTLE_WAIT_STATE cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @param pool Unused (BATTLE_WAIT_STATE needs no pool storage).
* @param poolOffset Unused (BATTLE_WAIT_STATE needs no pool storage).
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneBattleWaitStateLoad(
yyjson_val *itemObj,
cutsceneitem_t *item,
uint8_t *pool,
size_t *poolOffset
);
Loaded 100 of 352 files, more files were not shown because too many files have changed in this diff. Show more