122 Commits

Author SHA1 Message Date
YourWishes 93ab7690ba Add asset/event test coverage, fix caching-breaking eventSubscribe bug
Adds missing test coverage for the asset pipeline's binary loaders
(mesh/model/texture), assetfile.c, and assetbatch.c, plus a new
test/event suite for the shared event primitive.

Found and fixed two real bugs while writing this:
- assetFileRead's NULL-buffer skip path double-counted file->position,
  which could trip stb_image's EOF check early on images that skip
  bytes mid-decode.
- eventSubscribe/eventUnsubscribe matched only on the callback pointer
  instead of the (callback, user) pair the docs already promised, so
  two independent consumers of the same cached asset (e.g. two
  assetbatch_t's) would abort. Covered by dedicated caching tests in
  both test_assetbatch.c and test_assetmodelloader.c.

Also drops test_overworldscene.c, broken by the in-progress
overworldscene.js/init.js export-contract rewrite.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 14:34:51 -05:00
YourWishes 68c3f88181 Build on PSP 2026-08-11 13:11:22 -05:00
YourWishes 830864aa8a Gating network behind compile flag 2026-08-11 12:52:38 -05:00
YourWishes 5f34cb34b2 Add a thin declarative API for defining script methods/properties
scriptvalue.h/.c holds the scriptvalue_t tagged-union type and its
JS<->C decode/encode helpers; scriptdef.h/.c holds the declarative
scriptfuncdef_t/scriptpropdef_t definitions, the binding registry,
and the JerryScript trampolines. Lets a module declare its JS-facing
methods/properties/globals as typed data instead of hand-writing
argument-checking boilerplate per method. Framework only for now --
no existing module has been migrated onto it yet.
2026-08-03 19:36:08 -05:00
YourWishes b9d2fe60fd Split overworldscene.js's player/plane/camera into their own classes
Extracts Player (extends Entity), TestPlane, and PlayerCamera into
their own files; the camera now tracks the player's live position
at a fixed offset instead of orbiting the world origin over time.
Updates test_overworldscene.c to match the new entity order and to
build an in-memory zip fixture, since overworldscene.js now
require()s these sibling files and require() always resolves
through ASSET.zip.
2026-08-03 19:35:54 -05:00
YourWishes 06bc4fcd55 .MD remove 2026-08-03 14:35:30 -05:00
YourWishes 42cb84b610 Extract player entity setup into a Player class
Moves the capsule/physics/renderable/PLAYER setup out of
overworldscene.js's inline init() into assets/scripts/Player.js so the
scene module just instantiates it.
2026-08-02 21:06:31 -05:00
YourWishes f8607d114c Add UDP socket client/server multiplayer protocol
Implements the multiplayer transport layer from ROADMAP.md: UUID-based
client identity, a reliable-packet channel over UDP, handshake/ack/
ping/disconnect/player-joined/player-left/player-state packet types,
and split online (networked) vs offline (in-process singleplayer)
server modes wired into the engine's update/dispose loop.
2026-08-02 21:06:23 -05:00
YourWishes 56230dd340 Fix ref-count underflow, PSP timezone units, thread restart race, color codegen
- util/ref.c: refUnlock's assert(count >= 0) on an unsigned count was
  tautological, so a double-unlock silently underflowed to UINT32_MAX
  instead of asserting. Now asserts count > 0 before decrementing.
- duskpsp/time/timepsp.c: timeGetRealTimeZonePSP returned hours while
  every other platform (and timeepoch.c's math) expects seconds.
- thread.c: threadHandler reset threadId outside the mutex, after
  signaling STOPPED, letting a caller's immediate threadStart() race
  threadStartRequest()'s "thread id not 0" assert. threadId is now
  reset inside the same locked section.
- tools/color.py: whole-number CSV channels (0, 1) produced invalid C
  float literals (0f, 1f) for the generated COLOR_*_3F/_4F macros.
  Route through float() so they always stringify with a decimal point.

Also adds .claude/code-check.md: a full review pass over every
subsystem in src/dusk/, with the above (plus several other findings
not yet acted on) written up in detail.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 15:02:17 -05:00
YourWishes df9fdf26c8 Refresh STATUS.md/ROADMAP.md for the Scene.set()/UI caching/CI work
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 13:53:06 -05:00
YourWishes 8f8fa8f8d1 Scene.set() JS lifecycle, UI sprite caching, emulator test scripts
- Add Scene.set(module) so JerryScript can switch scenes via
  require()'d {init, update, dispose} modules; wire it into
  engineUpdate() and rework overworldscene.js/init.js to the new shape.
- Fix scriptManagerExecFile() never pushing its own file's directory
  onto the require() dir stack, breaking relative require() calls from
  a top-level entry script (e.g. init.js -> ./overworldscene.js).
- Cache sprite geometry across frames for uislider/uitab/uiframe
  (dialogs/textbox/settings) and give uitextbox a per-page glyph cache
  instead of one spriteBatchBuffer call per visible character. uiconsole
  drops its alloc/free vertex buffer for a fixed-size one. uifps skips
  rebuilding its label when the text hasn't changed.
- Add PSP_OPTIMIZATION_PLAN.md and a handful of UI/spritebatch unit
  tests covering the new caching logic.
- Add Dolphin/PPSSPP emulator smoke-test scripts (+ Docker variants and
  CI jobs) for GameCube/Wii/PSP.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 13:21:57 -05:00
YourWishes 07f98c119a Script stuff 2026-07-31 09:40:53 -05:00
YourWishes d49194fc4d Embed font into binary 2026-07-30 15:18:07 -05:00
YourWishes e61914bad4 Finish JerryScript Entity/Scene wiring; remove JSON serialize/deserialize
Register Entity, the generic Component wrapper, and Scene as JerryScript
classes (modulelist.c ties them together, plus their .d.ts stubs), so
scenes/entities can be built from script going forward instead of the
JSON scene format.

With scripting now the intended authoring path, drop the JSON
serialize/deserialize machinery entirely: componentdefinition_t's
serialize/deserialize callbacks, every component's *Serialize/
*Deserialize function, entitySerialize/entityDeserialize,
sceneSerialize/sceneDeserialize, and the "prefabs/<name>.json"/
"scenes/<name>.json" asset fallback in entityPrefabResolveAndApply/
scenePrefabResolveAndApply (C-coded prefabs only now). physicsshape.c
and its test are removed outright since they only existed for this.
game.c's test scene now comes from the existing overworldSceneCreate()
C builder instead of loading the now-deleted assets/scenes/test.json.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 11:19:08 -05:00
YourWishes 015d90519f WIP: start JerryScript integration (core engine + Component wrapper)
Ports the core scripting engine (scriptmanager, scriptproto, modulebase,
moduleplatform) and a generic Component JS wrapper from the old we-ball
branch, adapted to the current entitymanager_t/multi-scene architecture.

Not yet buildable: moduleentity.c, modulescene, modulelist.h/.c, and the
CMakeLists.txt for the new module subdirectories are still missing, and
engine.c isn't wired up yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 09:06:34 -05:00
YourWishes 7b4f0abfb8 Cutscene progress 2026-07-24 15:57:13 -05:00
YourWishes 0667a44e14 Restored cutscene code 2026-07-23 09:15:47 -05:00
YourWishes 0852b8463b ANIM 2026-07-21 18:55:23 -05:00
YourWishes 1436fda858 Some animation work 2026-07-21 09:29:14 -05:00
YourWishes 0826908068 First round of animation improvements 2026-07-20 16:07:38 -05:00
YourWishes 7ceb9e571d Scene prefabs 2026-07-20 15:11:38 -05:00
YourWishes 38c2f6b6f9 Add prefab support 2026-07-20 14:44:14 -05:00
YourWishes b9f06fef7a Add area and flag on physics 2026-07-20 12:31:14 -05:00
YourWishes 373f1c1010 test 2026-07-19 22:12:53 -05:00
YourWishes e80d693d85 More ui optimization 2026-07-19 17:39:38 -05:00
YourWishes ef60ddf6a8 UI Optim 2026-07-19 17:31:29 -05:00
YourWishes de0ff2e263 Fix collide issue on PSP 2026-07-19 14:51:57 -05:00
YourWishes 13a435e9c1 Test 2026-07-19 14:05:46 -05:00
YourWishes 725338cd5a Game code start 2026-07-19 11:49:13 -05:00
YourWishes acd14f46a8 Optimize PSP slightly 2026-07-19 11:15:22 -05:00
YourWishes ef78f023ed yeah whatever 2026-07-18 23:07:45 -05:00
YourWishes 85b6109792 Fixed save crash 2026-07-18 21:17:24 -05:00
YourWishes 6c5738c863 Testing physics 2026-07-18 20:53:22 -05:00
YourWishes 1174e471f6 Time fixes 2026-07-18 20:31:42 -05:00
YourWishes a618ff46fe Physics 2026-07-18 20:01:44 -05:00
YourWishes 1fa5cd316e Restore ECS 2026-07-18 19:05:51 -05:00
YourWishes 11e5d37563 Cleanup more. 2026-07-18 17:38:25 -05:00
YourWishes 9f86c20129 remove rpg 2026-07-18 17:15:45 -05:00
YourWishes 8fb1c9fb42 physics and rendering fixes 2026-07-17 21:06:21 -05:00
YourWishes 5f08337726 physics stuff 2026-07-17 19:07:32 -05:00
YourWishes 0bc80d5df3 Roadmap and physics 2026-07-17 13:09:58 -05:00
YourWishes 2432443ea6 Cleaned settings a bit 2026-07-17 09:11:19 -05:00
YourWishes fa138971e7 Console optimized slightly for rendering 2026-07-16 23:52:47 -05:00
YourWishes d7982599d1 Simplified PSP network 2026-07-16 22:55:47 -05:00
YourWishes f16c80aa0f Fixed PSP rendering 2026-07-16 21:20:49 -05:00
YourWishes ef5adf8274 PSP Network connect 2026-07-16 20:09:39 -05:00
YourWishes 2ffc65b1b1 Network conn and disconn 2026-07-16 19:32:44 -05:00
YourWishes d4a17bd98d Net 2026-07-16 19:08:32 -05:00
YourWishes dcf5f434c5 Remove vita for now 2026-07-16 15:50:19 -05:00
YourWishes 78cd973a33 Remove story and battle stuff 2026-07-16 15:37:55 -05:00
YourWishes ca02ee0352 Add camera shake 2026-07-11 11:02:09 -05:00
YourWishes fbaa54145e Fixed dolphin rendering. 2026-07-10 20:15:26 -05:00
YourWishes 28754ffbf2 Removed old scripted types 2026-07-10 13:24:21 -05:00
YourWishes 470c0eba7a Whatever, some minor map chunking improvements 2026-07-10 12:57:31 -05:00
YourWishes 7098dcec43 Cleaned some log 2026-07-09 23:25:43 -05:00
YourWishes 07137f57af Assets are slightly optimized 2026-07-09 23:25:26 -05:00
YourWishes 8b7491a3d3 Emoji support to characters 2026-07-09 13:18:48 -05:00
YourWishes 8cfa8ddfeb Weaather baseline 2026-07-08 12:57:13 -05:00
YourWishes ef284a15a1 pre-cache shader matrices 2026-07-08 12:36:40 -05:00
YourWishes 3723921573 Render culling on sceneoverworld.h 2026-07-08 12:02:41 -05:00
YourWishes 195399635e Updating mini textbox 2026-07-08 11:45:10 -05:00
YourWishes 46e2a924d3 Mini textboxes 2026-07-08 10:53:53 -05:00
YourWishes b693ea4102 Starting item and battle stuff 2026-07-08 10:05:21 -05:00
YourWishes a73f55beb0 Battle stuff
Build Dusk / build-linux (push) Successful in 7m5s
Build Dusk / build-psp (push) Successful in 1m33s
Build Dusk / build-knulli (push) Successful in 4m0s
Build Dusk / build-gamecube (push) Successful in 3m31s
Build Dusk / build-gamecube-iso (push) Successful in 3m39s
Build Dusk / build-wii (push) Successful in 3m5s
Build Dusk / build-wii-iso (push) Successful in 3m25s
2026-07-08 07:55:15 -05:00
YourWishes 0bd2491ab7 Dropdown test. 2026-07-07 15:18:33 -05:00
YourWishes 860c797c9c Last round of cleanup for settings for now. 2026-07-07 14:56:08 -05:00
YourWishes 38c5080f9f Collapsing more ui settings code 2026-07-07 14:36:19 -05:00
YourWishes fae191d8fe Settings improvements 2026-07-07 14:00:37 -05:00
YourWishes d83a953e2d First pass of language 2026-07-07 11:14:02 -05:00
YourWishes 2dcf0d0f0d UI Confirm 2026-07-07 10:12:22 -05:00
YourWishes 6dee37d8c1 Slider widget and some cleanup 2026-07-07 09:58:10 -05:00
YourWishes 3bad03afb3 Item entity 2026-07-07 07:52:22 -05:00
YourWishes 6a6d8448f7 Area cutscene controls 2026-07-07 07:28:12 -05:00
YourWishes 189babd2cf Trigger types on areas 2026-07-07 07:07:32 -05:00
YourWishes 988a0f2294 Area basics 2026-07-06 23:19:05 -05:00
YourWishes 85bf455731 entity pos sets chunk now 2026-07-04 18:43:09 -05:00
YourWishes 589e4224f3 Example global ent 2026-07-04 13:03:24 -05:00
YourWishes bd7fa154b4 Add user data to callbacks 2026-07-04 09:13:37 -05:00
YourWishes a292f1992b Change to use the Z tile system 2026-07-04 08:40:53 -05:00
YourWishes 88ddf429b7 add some entity management in prep for global entities. 2026-07-03 12:25:24 -05:00
YourWishes 7a1f6662df More cutscene tools 2026-07-03 09:17:49 -05:00
YourWishes afc68bccc6 Update test runner
Build Dusk / build-linux (push) Successful in 5m36s
Build Dusk / build-psp (push) Successful in 1m15s
Build Dusk / build-knulli (push) Successful in 4m53s
Build Dusk / build-gamecube (push) Successful in 3m51s
Build Dusk / build-gamecube-iso (push) Successful in 3m52s
Build Dusk / build-wii (push) Successful in 3m17s
Build Dusk / build-wii-iso (push) Successful in 4m54s
2026-07-02 19:20:17 -05:00
YourWishes b4cdc4a64f Add remove event
Build Dusk / run-tests (push) Failing after 5m7s
Build Dusk / build-linux (push) Successful in 5m41s
Build Dusk / build-psp (push) Successful in 1m17s
Build Dusk / build-knulli (push) Successful in 4m22s
Build Dusk / build-gamecube (push) Successful in 3m43s
Build Dusk / build-gamecube-iso (push) Successful in 3m36s
Build Dusk / build-wii (push) Successful in 3m36s
Build Dusk / build-wii-iso (push) Successful in 3m22s
2026-07-02 16:10:47 -05:00
YourWishes 3ad5afb81c Fix item crash 2026-07-02 16:04:41 -05:00
YourWishes bed3f20118 Lot of cutscene cleanup 2026-07-02 15:53:02 -05:00
YourWishes de67315178 Cutscene cleanup 2026-07-02 14:59:41 -05:00
YourWishes 8d5c0c7cad Path finding (first pass) 2026-07-02 14:08:59 -05:00
YourWishes a8271e01bd Fade cutscene items 2026-07-02 13:26:41 -05:00
YourWishes 900b3f8558 More cutscene stuff 2026-07-02 12:54:12 -05:00
YourWishes fdc4e056f9 Cutscene defs 2026-07-02 11:32:31 -05:00
YourWishes 7b98e40ccf Cutscene tests 2026-07-02 11:18:36 -05:00
YourWishes 01d89cf22c Map tweaks 2026-07-01 21:07:24 -05:00
YourWishes 503a3c799a Grid to editor 2026-07-01 20:51:46 -05:00
YourWishes 0b21388844 Fixing bugs, one at a time 2026-07-01 20:23:44 -05:00
YourWishes 117bdf0c00 Fov tweaks 2026-07-01 20:18:32 -05:00
YourWishes 172dc5d37b Tile Z is now hypotenused to 1 rather than stretching to have Z of 1. 2026-07-01 16:27:59 -05:00
YourWishes 874c6258ab New ramp types
Build Dusk / run-tests (push) Failing after 5m33s
Build Dusk / build-linux (push) Successful in 5m3s
Build Dusk / build-psp (push) Successful in 1m17s
Build Dusk / build-knulli (push) Successful in 4m45s
Build Dusk / build-gamecube (push) Successful in 3m49s
Build Dusk / build-gamecube-iso (push) Successful in 3m50s
Build Dusk / build-wii (push) Successful in 3m29s
Build Dusk / build-wii-iso (push) Successful in 4m4s
2026-07-01 16:05:02 -05:00
YourWishes a2d0a12c1a more editor stuff 2026-07-01 15:58:59 -05:00
YourWishes 38b24e1c3d editor first pass 2026-07-01 15:48:59 -05:00
YourWishes 5ecbbe296b Chunk load skin 2026-07-01 13:29:01 -05:00
YourWishes 9d7a769d8f Disable console printing on map chunk loading 2026-07-01 13:03:54 -05:00
YourWishes 9b75e5ed83 Async chunk loading 2026-07-01 12:58:33 -05:00
YourWishes a9ab8dc1d8 Chunks, models, and more 2026-07-01 08:35:01 -05:00
YourWishes a34831aa02 Add entity turn lockout 2026-06-30 21:23:34 -05:00
YourWishes 84ebaa0751 A lot of PSP optimizations 2026-06-30 21:01:11 -05:00
YourWishes 55352805ee Efficient loading of chunks now and PSP is slighty more optimized 2026-06-30 20:00:34 -05:00
YourWishes c0a3f2e16a Add scene scaling 2026-06-30 19:30:13 -05:00
YourWishes 28ff331a28 Create some test chunks and buildings 2026-06-30 19:08:39 -05:00
YourWishes f9a53ec719 Ramps fixed 2026-06-30 18:30:10 -05:00
YourWishes 6a403e6caf Add test hill 2026-06-30 18:21:46 -05:00
YourWishes a6f449bb93 example building 2 2026-06-30 16:21:47 -05:00
YourWishes 0614bfc446 example building 2026-06-30 16:21:46 -05:00
YourWishes bb020c36c1 CHUNK STUFF 2026-06-27 17:19:44 -05:00
YourWishes f17b0bfcfb Tiles 2026-06-27 08:50:55 -05:00
YourWishes 2a85c9503f npc interact turn to face player 2026-06-27 06:30:45 -05:00
YourWishes 182428d6d6 Merge branch 'cutscene'
Build Dusk / build-linux (push) Successful in 5m53s
Build Dusk / run-tests (push) Failing after 16m6s
Build Dusk / build-psp (push) Successful in 3m38s
Build Dusk / build-knulli (push) Successful in 3m50s
Build Dusk / build-gamecube (push) Successful in 3m7s
Build Dusk / build-gamecube-iso (push) Successful in 3m22s
Build Dusk / build-wii (push) Successful in 3m58s
Build Dusk / build-wii-iso (push) Successful in 2m57s
2026-06-26 19:43:30 -05:00
YourWishes 8181a28557 Bunch of stuff done 2026-06-26 19:42:34 -05:00
YourWishes 88aed11d98 Blocked path 2026-06-26 14:42:35 -05:00
YourWishes 67010592b8 Fixing some performance 2026-06-26 14:41:30 -05:00
YourWishes dd22d6424a testing some performance stuff 2026-06-26 14:29:55 -05:00
YourWishes e53775b97f Fixed player turn bug 2026-06-26 14:24:13 -05:00
YourWishes d326f6c1ac NPC movements 2026-06-26 14:21:48 -05:00
674 changed files with 35708 additions and 8188 deletions
-30
View File
@@ -4,36 +4,6 @@ on:
tags:
- '*'
jobs:
run-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
python3 \
python3-pip \
python3-polib \
python3-pil \
libsdl2-dev \
libgl1-mesa-dev \
libzip-dev \
python3-dotenv \
python3-pyqt5 \
python3-opengl \
xz-utils \
liblzma-dev \
libbz2-dev \
zlib1g-dev \
git \
libssl-dev
- name: Run tests
run: ./scripts/test-linux.sh
build-linux:
runs-on: ubuntu-latest
steps:
+106
View File
@@ -0,0 +1,106 @@
name: Test Dusk
on:
pull_request:
branches:
- main
jobs:
run-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
python3 \
python3-pip \
python3-polib \
python3-pil \
libsdl2-dev \
libgl1-mesa-dev \
libzip-dev \
python3-dotenv \
python3-pyqt5 \
python3-opengl \
xz-utils \
liblzma-dev \
libbz2-dev \
zlib1g-dev \
git \
libssl-dev
- name: Run tests
run: ./scripts/test-linux.sh
# Emulator smoke tests: boot the built disc/EBOOT for a fixed window and
# confirm the emulator doesn't crash. Not yet verified against a real
# runner (no CI run has exercised these) -- continue-on-error so a
# flaky/broken emulator step doesn't block the required Linux test job.
run-tests-gamecube-dolphin:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ghcr.io/extremscorner/libogc2:latest
steps:
- name: Install Node.js
run: apt-get update && apt-get install -y nodejs
- name: Checkout repository
uses: actions/checkout@v4
- name: Install additional dependencies
run: |
apt-get install -y \
python3-pip python3-polib python3-pil \
python3-dotenv python3-pyqt5 python3-opengl xorriso \
dolphin-emu xvfb
dkp-pacman -Syu --noconfirm
dkp-pacman -S --needed --noconfirm \
gamecube-sdl2 ppc-liblzma ppc-libzip \
gamecube-tools ppc-libmad ppc-zlib-ng ppc-bzip2 ppc-zstd
- name: Build GameCube ISO and boot it in Dolphin
run: ./scripts/test-gamecube-dolphin.sh
run-tests-wii-dolphin:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ghcr.io/extremscorner/libogc2:latest
steps:
- name: Install Node.js
run: apt-get update && apt-get install -y nodejs
- name: Checkout repository
uses: actions/checkout@v4
- name: Install additional dependencies
run: |
apt-get install -y \
python3-pip python3-polib python3-pil \
python3-dotenv python3-pyqt5 python3-opengl xorriso \
dolphin-emu xvfb
dkp-pacman -Syu --noconfirm
dkp-pacman -S --needed --noconfirm \
gamecube-sdl2 ppc-liblzma ppc-libzip \
gamecube-tools ppc-libmad ppc-zlib-ng ppc-bzip2 ppc-zstd
- name: Build Wii ISO and boot it in Dolphin
run: ./scripts/test-wii-dolphin.sh
run-tests-psp-ppsspp:
runs-on: ubuntu-latest
continue-on-error: true
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup pspdev
uses: ./.github/actions/setup-pspdev
- name: Install PPSSPPHeadless build dependencies
run: |
sudo apt-get update
sudo apt-get install -y git cmake ninja-build libsdl2-dev zlib1g-dev
- name: Build PPSSPPHeadless
run: |
git clone --recursive --depth 1 https://github.com/hrydgard/ppsspp.git /tmp/ppsspp
cmake -S /tmp/ppsspp -B /tmp/ppsspp/build -DCMAKE_BUILD_TYPE=Release
cmake --build /tmp/ppsspp/build --target PPSSPPHeadless -- -j$(nproc)
echo "PPSSPP_HEADLESS_BIN=/tmp/ppsspp/build/PPSSPPHeadless" >> "$GITHUB_ENV"
- name: Build PSP EBOOT and boot it in PPSSPPHeadless
run: ./scripts/test-psp-ppsspp.sh
-432
View File
@@ -1,432 +0,0 @@
# Dusk — Claude Code rules
## File headers
Every C, H, and JS file starts with:
```c
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
```
JS files use `//` comment style instead.
---
## C conventions
### Types
Always use the project-defined aliases instead of bare C primitives:
| Use | Not |
|-----------|--------------|
| `bool_t` | `bool` |
| `int_t` | `int` |
| `float_t` | `float` |
| `char_t` | `char` |
Use `uint8_t`, `uint16_t`, `int32_t`, etc. for fixed-width integers.
All struct and enum types end in `_t` (`animation_t`, `errorret_t`, …).
### Naming
- **Functions** — snake_case, prefixed with their module:
`assetLock()`, `entityPositionInit()`, `moduleAssetBatchCtor()`
- **Struct fields** — camelCase: `keyframeCount`, `localPosition`
- **Macros / constants** — UPPER_SNAKE_CASE:
`ENTITY_ID_INVALID`, `ERROR_OK`, `COMPONENT_TYPE_COUNT`
- **Files** — snake_case matching the primary type: `entityposition.c`,
`moduleassetbatch.c`
### Header files (`.h`)
- Use `#pragma once` — no include guards.
- Declare every public function, `#define`, and `extern` global.
- Write a JSDoc block (`/** … */`) above every declaration explaining
purpose, `@param`s, and `@returns`.
- Only include headers that the `.h` file itself strictly requires for
the types it exposes. Move everything else to the `.c` file.
Do not use forward declarations as a workaround — use the real
include in the `.c` file instead.
### Implementation files (`.c`)
- Contain function bodies only; no declarations.
- Pull in whatever additional includes the implementation needs.
- Do not use `static` or `inline` on **functions**. Every function,
including internal helpers, must be declared in the matching `.h` and
defined in the `.c` file. Internal helpers belong near the bottom of
the `.c` file, not at the top with a `static` qualifier.
`static` and `inline` on functions are only appropriate when the
function body is written directly inside a `.h` file.
`static` on **variables** (file-scope state) is fine and expected.
### Formatting
- Hard-wrap all lines at **80 characters**.
### Error handling
Return `errorret_t` from fallible functions. Use these macros:
```c
errorOk(); // return success
errorThrow("msg %d", val); // return failure with message
errorChain(someCall()); // propagate failure, continue on success
errorIsOk(ret) / errorIsNotOk(ret) // test a result
errorCatch(ret); // handle + free an error
```
Never return raw error codes or use `errno` for in-engine errors.
### Memory
Use the project allocator — never raw `malloc`/`free`:
```c
memoryAllocate(size) // allocate
memoryFree(ptr) // free
memoryZero(dest, size) // zero a block
memoryCopy(dest, src, size) // copy
```
### Asserts
Prefer specific assert macros over bare `assert()`:
```c
assertNotNull(ptr, "msg");
assertTrue(cond, "msg");
assertFalse(cond, "msg");
assertUnreachable("msg");
assertIsMainThread("msg");
```
---
## Build system
Each subdirectory has its own `CMakeLists.txt` that adds sources with:
```cmake
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
myfile.c
)
```
Never add source files to the root `CMakeLists.txt` directly.
---
## Platform support
### Targets
Set `DUSK_TARGET_SYSTEM` at CMake configure time to select a platform:
| `DUSK_TARGET_SYSTEM` | Macro defined | Platform |
|----------------------|-------------------|------------------|
| `linux` | `DUSK_LINUX` | Linux desktop |
| `knulli` | `DUSK_KNULLI` | Knulli (handheld)|
| `psp` | `DUSK_PSP` | Sony PSP |
| `vita` | `DUSK_VITA` | PlayStation Vita |
| `gamecube` | `DUSK_GAMECUBE` | Nintendo GameCube|
| `wii` | `DUSK_WII` | Nintendo Wii |
### Layer structure
```
src/dusk/ core, platform-agnostic game logic
src/duskgl/ OpenGL abstraction (Linux, Knulli, PSP, Vita)
src/dusksdl2/ SDL2 window + input (Linux, Knulli, PSP, Vita)
src/dusklinux/ Linux + Knulli platform impl
src/duskpsp/ PSP platform impl
src/duskvita/ Vita platform impl
src/duskdolphin/ GameCube / Wii platform impl (no SDL2/OpenGL)
```
Dolphin is the only target that bypasses SDL2 and OpenGL entirely —
it uses native GameCube/Wii rendering and input APIs.
### Platform guards
Use the compile-time macros for platform-specific code:
```c
#ifdef DUSK_PSP
// PSP-only path
#elif defined(DUSK_GAMECUBE) || defined(DUSK_WII)
// GameCube / Wii path
#else
// Generic / Linux fallback
#endif
```
Additional capability macros set per-target:
`DUSK_SDL2`, `DUSK_OPENGL`, `DUSK_OPENGL_ES`, `DUSK_OPENGL_LEGACY`,
`DUSK_INPUT_GAMEPAD`, `DUSK_INPUT_KEYBOARD`, `DUSK_INPUT_POINTER`,
`DUSK_PLATFORM_ENDIAN_BIG` / `DUSK_PLATFORM_ENDIAN_LITTLE`.
### Abstraction pattern
Platform-specific implementations are wired in via `#define` macros in
each platform's `displayplatform.h` / `inputplatform.h` etc., which
the core calls through. Functions that a platform does not support are
simply left undefined — the core guards calls with `#ifdef`.
### Adding platform-specific code
- Put it under `src/dusk<platform>/` in the matching subsystem folder.
- Gate any core call-site with the appropriate `#ifdef DUSK_<PLATFORM>`
or capability macro.
- Keep the `src/dusk/` core free of platform ifdefs — delegate through
the platform header macros instead.
---
## Adding a new asset loader type
1. Add an enum value to `assetloadertype_t` (before `_COUNT`) in
`src/dusk/asset/loader/assetloader.h`.
2. Add fields to the input/loading/output unions in `assetloader.h`.
3. Implement `assetXxxLoaderSync`, `assetXxxLoaderAsync`, and
`assetXxxDispose` in a new `src/dusk/asset/loader/xxx/` directory.
4. Register the three callbacks in `ASSET_LOADER_CALLBACKS[]` in
`src/dusk/asset/loader/assetloader.c`.
5. If user-facing, create a JS module (see below) and a `.d.ts` file.
---
## Adding a new entity component
1. Create `src/dusk/entity/component/<category>/entityMyComp.h/.c` with
struct `entityMyComp_t`, `entityMyCompInit()`, and optionally
`entityMyCompDispose()`.
2. Add the include to `src/dusk/entity/componentlist.h` header block.
3. Add a row to `src/dusk/entity/componentlist.h`:
```c
X(MYCOMP, entityMyComp_t, myComp, entityMyCompInit, NULL, NULL)
```
This auto-generates the enum, union field, and definition entry.
4. If JS-facing, create the script module and `.d.ts` (see below).
---
## Adding a new script (JS) module
1. Create `src/dusk/script/module/<category>/moduleMyMod.h/.c`.
- Declare `extern scriptproto_t MODULE_MYMOD_PROTO;` in the header.
- Use `moduleBaseFunction(name)` to define JS-callable functions.
- Register props/funcs in `moduleMyModInit()` with
`scriptProtoDefineProp` / `scriptProtoDefineFunc` /
`scriptProtoDefineStaticFunc`.
2. `#include` the header in
`src/dusk/script/module/modulelist.c` and call
`moduleMyModInit()` in `moduleListInit()` (and `Dispose` in
`moduleListDispose()`).
3. For component modules also register in
`src/dusk/script/module/entity/component/modulecomponentlist.c`
so `entity.add()` returns the typed wrapper.
4. Create `types/<category>/mymod.d.ts` and add a
`/// <reference path="..." />` line to `types/index.d.ts`.
---
## Script module type declarations
Whenever a `src/dusk/script/module/**/*.c` file is created or modified,
check whether the corresponding `types/**/*.d.ts` needs updating and
apply any changes before finishing the task.
---
## JavaScript (asset scripts)
- Use `var` for module-level state; `const` for values that never
change.
- Always use semicolons.
- Scene objects are plain objects (`var scene = {}`) with assigned
methods.
- Export via `module.exports = scene`.
- Async scene init should use `async function` and `await`.
---
## Coding style
### ASCII only
Source files (`.c`, `.h`, `.js`) must contain only ASCII characters (U+0000U+007F).
Non-ASCII characters are banned even in comments and string literals.
Use ASCII-only substitutes instead:
- `--` or `-` instead of `` (em dash)
- `->` instead of `` (arrow)
- `x` or `*` instead of `×` (multiplication)
Only non-script asset files (e.g. `.po` locale files) may contain non-ASCII text.
### Indentation
2 spaces. No tabs.
### Keyword and operator spacing
No space between a keyword or function name and its opening parenthesis:
```c
if(!ptr) return;
for(uint8_t i = 0; i < count; i++) {
while(entry->state != DONE) {
switch(type) {
sizeof(assetbatch_t)
memoryZero(ptr, size)
```
Spaces around all binary operators and after every comma:
```c
pos->flags |= ENTITY_POSITION_FLAG_WORLD_DIRTY;
(size_t)end - (size_t)start
foo(a, b, c)
```
### Braces
Opening brace on the **same line** as the statement (K&R style) for all
constructs — functions, `if`, `else`, `for`, `while`, `switch`:
```c
void assetEntryLock(assetentry_t *entry) {
...
}
if(dirty) {
...
} else {
...
}
```
### Guard returns
Short guards go on one line with no braces:
```c
if(!ptr) return;
if(!b || !b->batch) return jerry_undefined();
if(!(flags & DIRTY)) return;
```
### Blank lines
- One blank line between functions; no blank line at the start or end of
a function body.
- One blank line between logical blocks inside a function body.
- No trailing blank lines at the end of a file.
### Pointer placement
`*` is attached to the variable name, not the type:
```c
assetentry_t *entry
const char_t *name
void *ptr
uint8_t *d = (uint8_t *)dest;
```
### Casts
Space between cast and operand:
```c
(assetbatch_t *)user
(uint8_t *)dest
(textureformat_t)v
```
### Return
No parentheses around the return value:
```c
return ptr;
return MEMORY_POINTERS_IN_USE;
```
### switch / case
`case` indented 2 spaces from `switch`; body indented 2 more from `case`:
```c
switch(type) {
case ASSET_LOADER_TYPE_TEXTURE:
descs[i].input.texture = (textureformat_t)v;
break;
default:
break;
}
```
### Multi-line function signatures
When parameters don't fit on one line, put each on its own line indented
2 spaces; the closing `) {` (definition) or `);` (declaration) goes on
its own line at column 0:
```c
void assetEntryInit(
assetentry_t *entry,
const char_t *name,
const assetloadertype_t type,
assetloaderinput_t *input
) {
errorret_t memoryCompare(
const void *a,
const void *b,
const size_t size
);
```
### Structs and enums
Anonymous inner struct or enum with a `typedef`, `_t` suffix, closing
brace and name on the same line:
```c
typedef struct {
errorcode_t code;
char_t *message;
} errorstate_t;
typedef enum {
ASSET_LOADER_TYPE_NULL,
ASSET_LOADER_TYPE_COUNT
} assetloadertype_t;
```
### Designated initialisers
Spaces inside braces; `.field = value`:
```c
jsassetentry_t e = { .entry = entry };
assetbatchloadedpend_t init = { .batch = batch };
```
### Ternary operator
Spaces around `?` and `:`:
```c
const float val = psx > 0.0f ? pt[0][0] / psx : 0.0f;
```
### const placement
`const` before the type, `*` attached to the variable:
```c
const char_t *name
const void *src
const size_t size
```
### Comments in `.c` files
- Do not use section dividers (`/* ---- ... ---- */`). Just let the
functions follow one another with a single blank line between them.
- Multi-line explanatory comments inside function bodies use `//` lines:
```c
// Script modules are freed; orphaned JS wrapper objects now get GC'd
// so their finalizers fire before assetDispose() checks ref counts.
jerry_heap_gc(JERRY_GC_PRESSURE_HIGH);
```
- Do not use `/* */` for inline or inline-block comments inside `.c`
function bodies.
### Comments in `.h` files
Every public declaration gets a Javadoc block (`/** … */`) with
`@param` and `@returns` where relevant. Keep it on the lines immediately
above the declaration with no blank line in between.
---
## Tests
- Tests live in `test/` mirroring `src/dusk/` structure.
- Use cmocka; include `dusktest.h`.
- Test functions: `static void test_something(void **state)`.
- After each test, assert `memoryGetAllocatedCount() == 0` to catch
leaks.
- Build with `-DDUSK_BUILD_TESTS=ON`.
+12 -1
View File
@@ -13,6 +13,7 @@ cmake_policy(SET CMP0079 NEW)
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
option(DUSK_BUILD_TESTS "Enable tests" OFF)
option(DUSK_NETWORKING "Enable networking support" OFF)
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
@@ -90,6 +91,12 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
DUSK_VERSION="${DUSK_VERSION}"
)
if(DUSK_NETWORKING)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_NETWORKING
)
endif()
# Toolchains
include(cmake/targets/${DUSK_TARGET_SYSTEM}.cmake)
@@ -116,7 +123,11 @@ if(DUSK_BUILD_TESTS)
endif()
# Build assets
file(GLOB_RECURSE DUSK_ASSET_FILES CONFIGURE_DEPENDS "${DUSK_ASSETS_DIR}/*")
# Deliberately not CONFIGURE_DEPENDS: that reruns the full CMake configure
# step (which invalidates generated headers and forces a huge rebuild) on
# every single asset edit. Re-run cmake manually when assets are added or
# removed.
file(GLOB_RECURSE DUSK_ASSET_FILES "${DUSK_ASSETS_DIR}/*")
add_custom_command(
OUTPUT "${DUSK_ASSETS_ZIP}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${DUSK_ASSETS_DIR}"
-21
View File
@@ -1,21 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
const platformNames = {
[System.PLATFORM_LINUX]: 'Linux',
[System.PLATFORM_KNULLI]: 'Knulli',
[System.PLATFORM_PSP]: 'PSP',
[System.PLATFORM_GAMECUBE]: 'GameCube',
[System.PLATFORM_WII]: 'Wii',
};
Console.print('Platform: ' + (platformNames[System.platform] || 'Unknown'));
UIFullboxOver.setColor(Color.BLACK);
requireAsync('testscene.js').then(Scene.set).catch(err => {
Console.print('Error loading scene: ' + err);
Engine.exit();
});
+49 -43
View File
@@ -10,51 +10,57 @@ msgid "ui.title"
msgstr ""
"Welcome"
#: ui/user.c:22
msgid "ui.greeting"
msgstr "Hello, %s!"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.general"
msgstr "General"
#: ui/files.c:40
msgid "ui.file_status"
msgstr "%s has %d files."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.input"
msgstr "Input"
#: ui/cart.c:55
msgid "cart.item_count"
msgid_plural "cart.item_count"
msgstr[0] "%d item"
msgstr[1] "%d items (dual)"
msgstr[2] "%d items (few)"
msgstr[3] "%d items (many)"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.display"
msgstr "Display"
#: ui/notifications.c:71
msgid ""
"ui.multiline_help"
msgstr ""
"Line one of the help text.\n"
"Line two continues here.\n"
"Line three ends here."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.audio"
msgstr "Audio"
#: ui/errors.c:90
msgid ""
"error.upload_failed.long"
msgstr ""
"Upload failed for file \"%s\".\n"
"Please try again later or contact support."
msgid "ui.settings.input.deadzone"
msgstr "Deadzone"
#: ui/messages.c:110
msgid ""
"user.invite_status"
msgid_plural ""
"user.invite_status"
msgstr[0] ""
"%s invited %d user.\n"
"Please review the request."
msgstr[1] ""
"%s invited %d users (dual).\n"
"Please review the requests."
msgstr[2] ""
"%s invited %d users (few).\n"
"Please review the requests."
msgstr[3] ""
"%s invited %d users (many).\n"
"Please review the requests."
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
msgid "ui.settings.general.language"
msgstr "Language"
msgid "ui.settings.general.language_detail"
msgstr "Takes effect after restarting the application."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.apply"
msgstr "Apply"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "Discard unsaved changes?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "Characters"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "Items"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "Settings"
msgid "item.potion.name"
msgstr "Potion"
msgid "item.potato.name"
msgstr "Potato"
msgid "item.apple.name"
msgstr "Apple"
+70
View File
@@ -0,0 +1,70 @@
msgid ""
msgstr ""
"Project-Id-Version: ExampleApp 1.0\n"
"Language: es\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n==1 ? 0 : 1);\n"
#: ui/menu.c:10
msgid "ui.title"
msgstr ""
"Bienvenido"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.general"
msgstr "General"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.input"
msgstr "Entrada"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.display"
msgstr "Pantalla"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.audio"
msgstr "Audio"
msgid "ui.settings.input.deadzone"
msgstr "Deadzone"
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
msgid "ui.settings.general.language"
msgstr "Idioma"
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
msgid "ui.settings.general.language_detail"
msgstr "Se aplica después de reiniciar la aplicación."
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.apply"
msgstr "Aplicar"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "¿Descartar los cambios no guardados?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "Personajes"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "Objetos"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "Configuración"
#: src/dusk/rpg/item/item.json
msgid "item.potion.name"
msgstr "Poción"
#: src/dusk/rpg/item/item.json
msgid "item.potato.name"
msgstr "Papa"
#: src/dusk/rpg/item/item.json
msgid "item.apple.name"
msgstr "Manzana"
+70
View File
@@ -0,0 +1,70 @@
msgid ""
msgstr ""
"Project-Id-Version: ExampleApp 1.0\n"
"Language: ja\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=1; plural=(0);\n"
#: ui/menu.c:10
msgid "ui.title"
msgstr ""
"歓迎"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.general"
msgstr "一般"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.input"
msgstr "入力"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.display"
msgstr "表示"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.tabs.audio"
msgstr "オーディオ"
msgid "ui.settings.input.deadzone"
msgstr "デッドゾーン"
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
msgid "ui.settings.general.language"
msgstr "言語"
#: src/dusk/ui/frame/settings/uisettingsgeneral.c
msgid "ui.settings.general.language_detail"
msgstr "アプリケーションを再起動すると適用されます。"
#: src/dusk/ui/frame/settings/uisettings.c
msgid "ui.settings.apply"
msgstr "適用"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "未保存の変更を破棄しますか?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "キャラクター"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "アイテム"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "設定"
#: src/dusk/rpg/item/item.json
msgid "item.potion.name"
msgstr "ポーション"
#: src/dusk/rpg/item/item.json
msgid "item.potato.name"
msgstr "ジャガイモ"
#: src/dusk/rpg/item/item.json
msgid "item.apple.name"
msgstr "リンゴ"
-63
View File
@@ -1,63 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
const PLAYER_SPEED = 5.0;
// 1 world unit = 16 pixels.
const PIXEL_SCALE = 1.0 / 16.0;
// Player sprite is 32x32 px (test.png dimensions).
const PLAYER_W = 32 * PIXEL_SCALE;
const PLAYER_H = 32 * PIXEL_SCALE;
var player = {};
player.getAssets = () => {
return [
{ path: 'test.png', type: Asset.TYPE_TEXTURE, format: Texture.FORMAT_RGBA }
];
}
player.init = function(scene) {
var texture = scene.assets.getAssetByPath('test.png');
Console.print('Player init: got texture ' + texture);
_entity = Entity.create();
_position = _entity.add(Component.POSITION);
_physics = _entity.add(Component.PHYSICS);
_physics.bodyType = Physics.DYNAMIC;
_physics.shape = Physics.SHAPE_CUBE;
_physics.gravityScale = 1.0;
var r = _entity.add(Component.RENDERABLE);
r.texture = texture.texture;
r.type = Renderable.SPRITEBATCH;
r.color = new Color(220, 80, 80);
// Upright quad centered on X, bottom-aligned on Y.
r.sprites = [[-PLAYER_W/2, 0, 0, PLAYER_W/2, PLAYER_H, 0, 0, 1, 1, 0]];
_position.localPosition = new Vec3(0, PLAYER_H, 0);
};
player.getPosition = function() {
return _position;
};
player.update = function() {
if(!_physics) return;
var vx = Input.axis(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT) * PLAYER_SPEED;
var vz = Input.axis(INPUT_ACTION_DOWN, INPUT_ACTION_UP) * PLAYER_SPEED;
// Preserve vertical velocity so gravity and landing work correctly.
var vy = _physics.velocity.y;
_physics.velocity = new Vec3(vx, vy, vz);
};
player.dispose = function() {
Entity.dispose(_entity);
_entity = null;
_position = null;
_physics = null;
};
module.exports = player;
+28
View File
@@ -0,0 +1,28 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
class Player extends Entity {
constructor() {
super();
this.position = this.add(POSITION);
this.position.setLocalPosition(0.0, 2.0, 0.0);
this.physics = this.add(PHYSICS);
this.physics.setShape(PHYSICS_SHAPE_CAPSULE, 0.5, 0.5);
this.renderable = this.add(RENDERABLE);
this.renderable.setMesh(0, MESH_CAPSULE);
this.renderable.setColor(0, 0, 255, 255);
this.add(PLAYER);
}
dispose() {
}
}
module.exports = Player;
+41
View File
@@ -0,0 +1,41 @@
var CAMERA_OFFSET_ANGLE = 0.0;
var CAMERA_OFFSET_RADIUS = 18.0;
var CAMERA_OFFSET_HEIGHT = 10.0;
class PlayerCamera extends Entity {
constructor(target) {
super();
this.target = target;
this.position = this.add(POSITION);
this.add(CAMERA);
this.update();
}
update() {
var targetPosition = this.target.position.getLocalPosition();
var eyeX = (
targetPosition.x + Math.cos(CAMERA_OFFSET_ANGLE) * CAMERA_OFFSET_RADIUS
);
var eyeY = (
targetPosition.y + CAMERA_OFFSET_HEIGHT
);
var eyeZ = (
targetPosition.z + Math.sin(CAMERA_OFFSET_ANGLE) * CAMERA_OFFSET_RADIUS
);
this.position.lookAt(
eyeX, eyeY, eyeZ,
targetPosition.x, targetPosition.y, targetPosition.z,
0.0, 1.0, 0.0
);
}
dispose() {
this.target = null;
}
}
module.exports = PlayerCamera;
+23
View File
@@ -0,0 +1,23 @@
class TestPlane extends Entity {
constructor() {
super();
this.position = this.add(POSITION);
this.position.setLocalPosition(-10.0, 0.0, -10.0);
this.position.setLocalScale(20.0, 1.0, 20.0);
this.physics = this.add(PHYSICS);
this.physics.setBodyType(PHYSICS_BODY_STATIC);
this.physics.setShape(PHYSICS_SHAPE_PLANE, 0.0, 1.0, 0.0, 0.0);
this.renderable = this.add(RENDERABLE);
this.renderable.setMesh(0, MESH_PLANE);
this.renderable.setColor(128, 128, 128, 255);
}
dispose() {
}
}
module.exports = TestPlane;
+3
View File
@@ -0,0 +1,3 @@
var OverworldScene = require('./overworldscene.js');
Scene.set(new OverworldScene());
+36
View File
@@ -0,0 +1,36 @@
var Player = require('./Player.js');
var PlayerCamera = require('./PlayerCamera.js');
var TestPlane = require('./TestPlane.js');
class OverworldScene {
constructor() {
this.time = 0;
}
init() {
this.player = new Player();
this.plane = new TestPlane();
this.camera = new PlayerCamera(this.player);
}
update() {
this.camera.update();
this.time += Time.delta;
if(this.time > 3.0) {
Scene.set(new OverworldScene());
}
}
dispose() {
this.camera.dispose();
this.player.dispose();
this.plane.dispose();
this.camera = null;
this.player = null;
this.plane = null;
}
}
module.exports = OverworldScene;
-42
View File
@@ -1,42 +0,0 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var scene = {};
// Pokemon DS-style camera: ~34 degrees elevation (atan(6/9)).
// CAM_HEIGHT / CAM_DIST ratio controls the tilt - keep it under 0.7 for
// the characteristically shallow DS angle.
const CAM_HEIGHT = 6;
const CAM_DIST = 9;
scene.init = async function() {
// Camera
scene.cam = Entity.create();
var camPos = scene.cam.add(Component.POSITION);
var cam = scene.cam.add(Component.CAMERA);
camPos.localPosition = new Vec3(3, 3, 3);
camPos.lookAt(new Vec3(0, 0, 0));
// Floor - large flat slab, no texture needed.
scene.floor = Entity.create();
var floorPos = scene.floor.add(Component.POSITION);
var floorR = scene.floor.add(Component.RENDERABLE);
floorR.type = Renderable.SHADER_MATERIAL;
floorR.color = Color.BLUE;
// floorPos.localScale = new Vec3(16, 0.2, 16);
// floorPos.localPosition = new Vec3(0, -0.1, 0);
await UIFullboxOver.transition(Color.BLACK, Color.TRANSPARENT, 1.0);
};
scene.update = function() {
};
scene.dispose = function() {
Entity.dispose(scene.floor);
Entity.dispose(scene.cam);
};
module.exports = scene;
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

-6
View File
@@ -1,6 +0,0 @@
module = {
render() {
Text.draw(0, 0, "Hello World");
SpriteBatch.flush();
}
};
+96
View File
@@ -0,0 +1,96 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Turn things off we don't need
set(JERRY_CMDLINE OFF CACHE BOOL "" FORCE)
set(JERRY_EXT ON CACHE BOOL "" FORCE)
set(JERRY_DEBUGGER OFF CACHE BOOL "" FORCE)
set(JERRY_BUILTIN_DATE OFF CACHE BOOL "" FORCE)
set(ENABLE_LTO OFF CACHE BOOL "" FORCE)
# Fetch Jerry
include(FetchContent)
FetchContent_Declare(
jerryscript
GIT_REPOSITORY https://git.wish.moe/YourWishes/jerryscript
GIT_TAG float32-fix
)
FetchContent_MakeAvailable(jerryscript)
# Mark found
set(jerryscript_FOUND ON)
# Define targets
if(TARGET jerryscript-core)
set(JERRY_CORE_TARGET jerryscript-core)
elseif(TARGET jerry-core)
set(JERRY_CORE_TARGET jerry-core)
endif()
if(TARGET jerryscript-ext)
set(JERRY_EXT_TARGET jerryscript-ext)
elseif(TARGET jerry-ext)
set(JERRY_EXT_TARGET jerry-ext)
endif()
if(TARGET jerryscript-port-default)
set(JERRY_PORT_TARGET jerryscript-port-default)
elseif(TARGET jerry-port-default)
set(JERRY_PORT_TARGET jerry-port-default)
elseif(TARGET jerryscript-port)
set(JERRY_PORT_TARGET jerryscript-port)
elseif(TARGET jerry-port)
set(JERRY_PORT_TARGET jerry-port)
endif()
if(NOT JERRY_CORE_TARGET)
message(FATAL_ERROR "JerryScript core target not found")
endif()
if(NOT JERRY_EXT_TARGET)
message(FATAL_ERROR "JerryScript ext target not found")
endif()
if(NOT JERRY_PORT_TARGET)
message(FATAL_ERROR "JerryScript port target not found")
endif()
foreach(tgt IN ITEMS
${JERRY_CORE_TARGET}
${JERRY_EXT_TARGET}
${JERRY_PORT_TARGET}
)
if(TARGET ${tgt})
set_property(TARGET ${tgt} PROPERTY INTERPROCEDURAL_OPTIMIZATION OFF)
target_compile_definitions(${JERRY_CORE_TARGET} PRIVATE
JERRY_NUMBER_TYPE_FLOAT64=0
JERRY_BUILTIN_DATE=0
)
endif()
endforeach()
# Export include dirs through the targets
target_include_directories(${JERRY_CORE_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-core/include
)
target_include_directories(${JERRY_EXT_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-ext/include
)
target_include_directories(${JERRY_PORT_TARGET} INTERFACE
${jerryscript_SOURCE_DIR}/jerry-port/default/include
)
# Suppress JerryScript-only warning
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(${JERRY_CORE_TARGET} PRIVATE
-Wno-error
)
endif()
add_library(jerryscript::core ALIAS ${JERRY_CORE_TARGET})
add_library(jerryscript::ext ALIAS ${JERRY_EXT_TARGET})
add_library(jerryscript::port ALIAS ${JERRY_PORT_TARGET})
+3
View File
@@ -16,6 +16,9 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DOL=1
ISO=2
DUSK_DOLPHIN_BUILD_TYPE=${DUSK_DOLPHIN_BUILD_TYPE}
# GameCube/Wii PowerPC is always big-endian; declare it at compile time
# like every other target instead of relying on endian.h's runtime probe.
DUSK_PLATFORM_ENDIAN_BIG
)
# Custom compiler flags
+1 -1
View File
@@ -6,7 +6,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
# Link libraries
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
# bba
bba
)
# ISO post-build: produce NTSC-J, NTSC-U and PAL disc images
+1 -2
View File
@@ -32,11 +32,10 @@ set(DUSK_BACKTRACE ON CACHE BOOL "Enable backtrace support for assert failures."
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SDL2
DUSK_OPENGL
DUSK_CONSOLE_POSIX
# DUSK_OPENGL_LEGACY
DUSK_LINUX
DUSK_DISPLAY_SIZE_DYNAMIC
DUSK_DISPLAY_WIDTH_DEFAULT=640
DUSK_DISPLAY_WIDTH_DEFAULT=854
DUSK_DISPLAY_HEIGHT_DEFAULT=480
DUSK_DISPLAY_SCREEN_HEIGHT=240
DUSK_INPUT_KEYBOARD
+5
View File
@@ -1,3 +1,7 @@
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
set(CMAKE_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
set(CMAKE_RANLIB "$ENV{PSPDEV}/bin/psp-ranlib" CACHE FILEPATH "" FORCE)
set(CMAKE_C_COMPILER_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
@@ -55,6 +59,7 @@ target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_DISPLAY_WIDTH=480
DUSK_DISPLAY_HEIGHT=272
DUSK_THREAD_PTHREAD
DUSK_DISPLAY_OVERSCAN=6
)
# Postbuild, create .pbp file for PSP.
-88
View File
@@ -1,88 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
if(NOT DEFINED ENV{VITASDK})
message(FATAL_ERROR "VITASDK environment variable is not set.")
endif()
include("$ENV{VITASDK}/share/vita.cmake" REQUIRED)
set(VITA_APP_NAME "Dusk")
set(VITA_TITLEID "DUSK00001")
set(VITA_VERSION "01.00")
find_package(SDL2 REQUIRED)
# Custom flags for cglm
set(CGLM_SHARED OFF CACHE BOOL "Build cglm shared" FORCE)
set(CGLM_STATIC ON CACHE BOOL "Build cglm static" FORCE)
find_package(cglm REQUIRED)
# Link libraries
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
${SDL2_LIBRARIES}
cglm
SDL2
SDL2main
zip
bz2
z
zstd
crypto
lzma
m
pthread
stdc++
vitaGL
mathneon
vitashark
kubridge_stub
SceAppMgr_stub
SceAudio_stub
SceCtrl_stub
SceCommonDialog_stub
SceDisplay_stub
SceKernelDmacMgr_stub
SceGxm_stub
SceShaccCg_stub
SceSysmodule_stub
ScePower_stub
SceTouch_stub
SceVshBridge_stub
SceIofilemgr_stub
SceShaccCgExt
libtaihen_stub.a
# SceKernel_stub
SceAppUtil_stub
SceHid_stub
SceRtc_stub
)
target_include_directories(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
${SDL2_INCLUDE_DIRS}
)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SDL2
DUSK_OPENGL
DUSK_VITA
DUSK_INPUT_GAMEPAD
DUSK_PLATFORM_ENDIAN_LITTLE
DUSK_OPENGL_LEGACY
DUSK_DISPLAY_WIDTH=960
DUSK_DISPLAY_HEIGHT=544
)
# Post-build: create SELF from the ELF binary (UNSAFE = homebrew, no signing)
vita_create_self(${DUSK_BINARY_TARGET_NAME}.self ${DUSK_BINARY_TARGET_NAME} UNSAFE)
# Post-build: package SELF + assets into a .vpk installable on the Vita
vita_create_vpk(${DUSK_BINARY_TARGET_NAME}.vpk ${VITA_TITLEID} ${DUSK_BINARY_TARGET_NAME}.self
VERSION ${VITA_VERSION}
NAME ${VITA_APP_NAME}
FILE ${DUSK_ASSETS_ZIP} dusk.dsk
)
+7
View File
@@ -0,0 +1,7 @@
FROM ghcr.io/extremscorner/libogc2
WORKDIR /workdir
RUN apt update && \
dkp-pacman -Syu --noconfirm && \
apt install -y python3 python3-pip python3-polib python3-pil python3-dotenv python3-pyqt5 python3-opengl xorriso dolphin-emu xvfb && \
dkp-pacman -S --needed --noconfirm gamecube-sdl2 ppc-liblzma ppc-libzip libogc2 gamecube-tools ppc-libmad ppc-zlib-ng ppc-liblzma ppc-bzip2 ppc-zstd
VOLUME ["/workdir"]
+28
View File
@@ -0,0 +1,28 @@
FROM pspdev/pspdev:latest
WORKDIR /workdir
RUN apk add --no-cache \
python3 \
py3-pip \
py3-dotenv \
git \
cmake \
make \
g++ \
sdl2-dev \
zlib-dev \
linux-headers
# PPSSPP has no Alpine/Linux distro package -- build the "PPSSPPHeadless"
# target (the CLI/no-window build PPSSPP's own CI uses for automated runs)
# from source instead. The target name and exact CMake options have moved
# around across PPSSPP versions -- if this breaks, check
# https://github.com/hrydgard/ppsspp's CMakeLists.txt for the current name.
RUN git clone --recursive --depth 1 \
https://github.com/hrydgard/ppsspp.git /opt/ppsspp && \
cd /opt/ppsspp && \
cmake -B build -DCMAKE_BUILD_TYPE=Release && \
cmake --build build --target PPSSPPHeadless -- -j$(nproc) && \
cp build/PPSSPPHeadless /usr/local/bin/PPSSPPHeadless && \
rm -rf /opt/ppsspp
VOLUME ["/workdir"]
+159
View File
@@ -0,0 +1,159 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
// ChunkTerrain - JS port of the terrain-quad generation performed by
// tools/asset/chunk/__main__.py (build_terrain_verts / _tile_quad /
// _RAMP_CORNERS) so the editor's 3D preview can show the same geometry the
// Python compiler will bake into the chunk's terrain mesh, without waiting
// for a compile pass. Vertex layout matches DMF: interleaved [u, v, x, y, z].
const ChunkTerrain = (() => {
const CHUNK_WIDTH = 16;
const CHUNK_HEIGHT = 16;
const CHUNK_DEPTH = 4;
const TILE_COUNT = CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_DEPTH;
// World-space Z distance of one Z-layer/story, in world-float space.
// Must match WORLD_LAYER_HEIGHT in src/dusk/rpg/overworld/worldpos.h.
const WORLD_LAYER_HEIGHT = Math.SQRT1_2;
const TILE_SHAPE_NULL = 0;
const TILE_SHAPE_GROUND = 1;
const TILE_SHAPE_RAMP_NORTH = 2;
const TILE_SHAPE_RAMP_EAST = 3;
const TILE_SHAPE_RAMP_SOUTH = 4;
const TILE_SHAPE_RAMP_WEST = 5;
const TILE_SHAPE_RAMP_NORTHEAST = 6;
const TILE_SHAPE_RAMP_NORTHWEST = 7;
const TILE_SHAPE_RAMP_SOUTHEAST = 8;
const TILE_SHAPE_RAMP_SOUTHWEST = 9;
const TILE_SHAPE_RAMP_NORTHEAST_INNER = 10;
const TILE_SHAPE_RAMP_NORTHWEST_INNER = 11;
const TILE_SHAPE_RAMP_SOUTHEAST_INNER = 12;
const TILE_SHAPE_RAMP_SOUTHWEST_INNER = 13;
// Per-shape corner heights as [sw, se, ne, nw] offsets from tile base Z.
// NORTH=+Y, EAST=+X. Cardinal ramps: low face at 0, high face at 1.
// Diagonal outer-corner ramps: only the named corner raised, rest at 0.
// Diagonal inner-corner ramps: only the corner opposite the named one is
// lowered to 0, the rest (including the named corner) stay raised at 1.
const RAMP_CORNERS = {
[TILE_SHAPE_GROUND]: [0.0, 0.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_NORTH]: [0.0, 0.0, 1.0, 1.0],
[TILE_SHAPE_RAMP_SOUTH]: [1.0, 1.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_EAST]: [0.0, 1.0, 1.0, 0.0],
[TILE_SHAPE_RAMP_WEST]: [1.0, 0.0, 0.0, 1.0],
[TILE_SHAPE_RAMP_NORTHEAST]: [0.0, 0.0, 1.0, 0.0],
[TILE_SHAPE_RAMP_NORTHWEST]: [0.0, 0.0, 0.0, 1.0],
[TILE_SHAPE_RAMP_SOUTHEAST]: [0.0, 1.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_SOUTHWEST]: [1.0, 0.0, 0.0, 0.0],
[TILE_SHAPE_RAMP_NORTHEAST_INNER]: [0.0, 1.0, 1.0, 1.0],
[TILE_SHAPE_RAMP_NORTHWEST_INNER]: [1.0, 0.0, 1.0, 1.0],
[TILE_SHAPE_RAMP_SOUTHEAST_INNER]: [1.0, 1.0, 1.0, 0.0],
[TILE_SHAPE_RAMP_SOUTHWEST_INNER]: [1.0, 1.0, 0.0, 1.0],
};
function tileIndex(x, y, z) {
return x + y * CHUNK_WIDTH + z * CHUNK_WIDTH * CHUNK_HEIGHT;
}
// Six vertices (2 CCW triangles) for a quad with per-corner Z heights.
// Corner order: SW=(fx,fy), SE=(fx+1,fy), NE=(fx+1,fy+1), NW=(fx,fy+1).
function pushTileQuad(out, u0, u1, v0, v1, fx, fy, swZ, seZ, neZ, nwZ) {
out.push(
u0, v0, fx, fy, swZ,
u1, v0, fx + 1, fy, seZ,
u1, v1, fx + 1, fy + 1, neZ,
u0, v0, fx, fy, swZ,
u1, v1, fx + 1, fy + 1, neZ,
u0, v1, fx, fy + 1, nwZ,
);
}
// Generate terrain quads for every non-null tile in a flat tiles array
// (length TILE_COUNT, indexed via tileIndex). Returns a Float32Array of
// interleaved [u, v, x, y, z] vertices, matching DMF.VERTEX_FLOATS.
function buildTerrainVerts(tiles) {
const out = [];
for(let z = 0; z < CHUNK_DEPTH; z++) {
for(let y = 0; y < CHUNK_HEIGHT; y++) {
for(let x = 0; x < CHUNK_WIDTH; x++) {
const type = tiles[tileIndex(x, y, z)] || TILE_SHAPE_NULL;
const corners = RAMP_CORNERS[type];
if(!corners) continue;
const u0 = x / CHUNK_WIDTH;
const u1 = (x + 1) / CHUNK_WIDTH;
const v0 = y / CHUNK_HEIGHT;
const v1 = (y + 1) / CHUNK_HEIGHT;
const [sw, se, ne, nw] = corners;
pushTileQuad(
out, u0, u1, v0, v1, x, y,
(z + sw) * WORLD_LAYER_HEIGHT,
(z + se) * WORLD_LAYER_HEIGHT,
(z + ne) * WORLD_LAYER_HEIGHT,
(z + nw) * WORLD_LAYER_HEIGHT
);
}
}
}
return new Float32Array(out);
}
// Four edges (SW-SE, SE-NE, NE-NW, NW-SW) of a tile's quad as line
// segments, lifted slightly above the terrain surface to avoid
// z-fighting - same corner-height convention as pushTileQuad().
function pushTileGridLines(out, fx, fy, swZ, seZ, neZ, nwZ) {
const eps = 0.01;
const sw = [fx, fy, swZ + eps];
const se = [fx + 1, fy, seZ + eps];
const ne = [fx + 1, fy + 1, neZ + eps];
const nw = [fx, fy + 1, nwZ + eps];
const edges = [sw, se, se, ne, ne, nw, nw, sw];
for(const [x, y, z] of edges) out.push(0, 0, x, y, z);
}
// Generate grid-outline line segments for every non-null tile, following
// the same per-corner heights as buildTerrainVerts() so lines hug ramps
// instead of cutting through them. Returns a Float32Array of interleaved
// [u, v, x, y, z] vertices meant to be drawn with gl.LINES (pairs).
function buildGridLines(tiles) {
const out = [];
for(let z = 0; z < CHUNK_DEPTH; z++) {
for(let y = 0; y < CHUNK_HEIGHT; y++) {
for(let x = 0; x < CHUNK_WIDTH; x++) {
const type = tiles[tileIndex(x, y, z)] || TILE_SHAPE_NULL;
const corners = RAMP_CORNERS[type];
if(!corners) continue;
const [sw, se, ne, nw] = corners;
pushTileGridLines(
out, x, y,
(z + sw) * WORLD_LAYER_HEIGHT,
(z + se) * WORLD_LAYER_HEIGHT,
(z + ne) * WORLD_LAYER_HEIGHT,
(z + nw) * WORLD_LAYER_HEIGHT
);
}
}
}
return new Float32Array(out);
}
return Object.freeze({
CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH, TILE_COUNT, WORLD_LAYER_HEIGHT,
TILE_SHAPE_NULL, TILE_SHAPE_GROUND,
TILE_SHAPE_RAMP_NORTH, TILE_SHAPE_RAMP_EAST,
TILE_SHAPE_RAMP_SOUTH, TILE_SHAPE_RAMP_WEST,
TILE_SHAPE_RAMP_NORTHEAST, TILE_SHAPE_RAMP_NORTHWEST,
TILE_SHAPE_RAMP_SOUTHEAST, TILE_SHAPE_RAMP_SOUTHWEST,
TILE_SHAPE_RAMP_NORTHEAST_INNER, TILE_SHAPE_RAMP_NORTHWEST_INNER,
TILE_SHAPE_RAMP_SOUTHEAST_INNER, TILE_SHAPE_RAMP_SOUTHWEST_INNER,
RAMP_CORNERS, tileIndex, buildTerrainVerts, buildGridLines,
});
})();
+64
View File
@@ -0,0 +1,64 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
// DMF - Dusk Mesh Format
//
// Header (12 bytes):
// [0-3] "DMF\0" magic
// [4-7] uint32 version (little-endian)
// [8-11] uint32 vertCount (little-endian)
//
// Followed by vertCount vertices, each 20 bytes:
// [0-7] float32[2] uv (little-endian)
// [8-19] float32[3] pos (little-endian)
const DMF = (() => {
const MAGIC = [0x44, 0x4d, 0x46, 0x00]; // "DMF\0"
const VERSION = 1;
const HEADER_SIZE = 12;
const VERTEX_FLOATS = 5; // uv[2] + pos[3]
const VERTEX_SIZE = VERTEX_FLOATS * 4;
// Decode a DMF ArrayBuffer into { version, vertexCount, floats }, where
// floats is a Float32Array of tightly interleaved [u, v, x, y, z] per
// vertex - ready to hand straight to gl.bufferData().
function decode(buffer) {
const bytes = new Uint8Array(buffer);
const view = new DataView(buffer);
if(bytes.length < HEADER_SIZE) throw new Error("File too small to be a valid DMF");
if(
bytes[0] !== MAGIC[0] || bytes[1] !== MAGIC[1] ||
bytes[2] !== MAGIC[2] || bytes[3] !== MAGIC[3]
) {
throw new Error("Invalid DMF magic bytes - not a DMF file");
}
const version = view.getUint32(4, true);
if(version !== VERSION) {
throw new Error(`Unsupported DMF version: ${version}`);
}
const vertexCount = view.getUint32(8, true);
const expected = HEADER_SIZE + vertexCount * VERTEX_SIZE;
if(bytes.length < expected) {
throw new Error(`DMF vertex data truncated (expected ${expected} bytes, got ${bytes.length})`);
}
const floats = new Float32Array(vertexCount * VERTEX_FLOATS);
for(let i = 0; i < floats.length; i++) {
floats[i] = view.getFloat32(HEADER_SIZE + i * 4, true);
}
return { version, vertexCount, floats };
}
return Object.freeze({
decode,
VERSION, HEADER_SIZE, VERTEX_FLOATS, VERTEX_SIZE,
});
})();
+6
View File
@@ -0,0 +1,6 @@
<div class="row">
<div class="col-12">
<h1>Dusk Map Editor</h1>
<p class="text-muted">Browse and edit project assets.</p>
</div>
</div>
+92
View File
@@ -0,0 +1,92 @@
<link rel="stylesheet" href="/map/map.css">
<div class="row g-3">
<div class="col-12">
<div class="d-flex flex-wrap align-items-end gap-2 mb-2">
<div>
<label class="form-label mb-0">X</label>
<input type="number" id="coordX" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Y</label>
<input type="number" id="coordY" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Z</label>
<input type="number" id="coordZ" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<button id="btnLoad" type="button" class="btn btn-sm btn-secondary">Load</button>
<div class="dropdown">
<button
class="btn btn-sm btn-outline-secondary dropdown-toggle"
type="button" data-bs-toggle="dropdown"
>Browse</button>
<ul class="dropdown-menu" id="chunkBrowseList"></ul>
</div>
<div class="dpad" title="Navigate to the neighboring chunk">
<button type="button" class="btn btn-sm btn-outline-secondary dpad-n" id="navN" title="North (+Y)">N</button>
<button type="button" class="btn btn-sm btn-outline-secondary dpad-w" id="navW" title="West (-X)">W</button>
<button type="button" class="btn btn-sm btn-outline-secondary dpad-e" id="navE" title="East (+X)">E</button>
<button type="button" class="btn btn-sm btn-outline-secondary dpad-s" id="navS" title="South (-Y)">S</button>
</div>
<div class="d-flex flex-column gap-1">
<button type="button" class="btn btn-sm btn-outline-secondary" id="navUp" title="Up (+Z)">Up</button>
<button type="button" class="btn btn-sm btn-outline-secondary" id="navDown" title="Down (-Z)">Down</button>
</div>
<button id="btnSave" type="button" class="btn btn-sm btn-primary ms-auto">
Save &amp; Compile
</button>
</div>
<div id="statusLine" class="small text-muted mb-2">&nbsp;</div>
</div>
<div class="col-12 col-lg-6">
<div class="d-flex align-items-center gap-2 mb-2">
<label class="form-label mb-0">Z-Level</label>
<button type="button" class="btn btn-sm btn-outline-secondary" id="zLevelDown">-</button>
<input type="range" id="zLevel" class="form-range" style="width:150px" min="0" max="3" value="0">
<button type="button" class="btn btn-sm btn-outline-secondary" id="zLevelUp">+</button>
<span id="zLevelLabel">0</span>
</div>
<div class="d-flex gap-3">
<div id="toolPalette" class="tile-palette"></div>
<div id="tilePalette" class="tile-palette"></div>
<canvas id="gridCanvas" class="border tile-grid" width="512" height="512"></canvas>
</div>
<h5 class="mt-3">Meshes</h5>
<ul id="meshList" class="list-group mb-2"></ul>
<div class="d-flex gap-2 align-items-end flex-wrap">
<div style="min-width:220px">
<label class="form-label mb-0">Model</label>
<select id="meshPicker" class="form-select form-select-sm"></select>
</div>
<div>
<label class="form-label mb-0">X</label>
<input id="meshX" type="number" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Y</label>
<input id="meshY" type="number" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<div>
<label class="form-label mb-0">Z</label>
<input id="meshZ" type="number" class="form-control form-control-sm" style="width:5rem" value="0">
</div>
<button id="btnAddMesh" type="button" class="btn btn-sm btn-outline-primary">Add</button>
</div>
</div>
<div class="col-12 col-lg-6">
<p class="small text-muted mb-2">Preview (scroll to zoom)</p>
<canvas id="previewCanvas" class="border" width="512" height="512"></canvas>
</div>
</div>
<script src="/common/dmf.js"></script>
<script src="/common/chunkterrain.js"></script>
<script src="/map/renderer.js"></script>
<script src="/map/map.js"></script>
+65
View File
@@ -0,0 +1,65 @@
/* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
.tile-palette {
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 6px;
max-height: 600px;
}
.tile-swatch {
position: relative;
width: 32px;
height: 32px;
border: 2px solid transparent;
border-radius: 4px;
cursor: pointer;
padding: 0;
}
.tile-swatch.active {
border-color: #fff;
}
.tile-swatch-icon {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
.dpad {
display: grid;
grid-template-columns: repeat(3, 2rem);
grid-template-rows: repeat(3, 2rem);
grid-template-areas:
". n ."
"w . e"
". s .";
gap: 2px;
}
.dpad-n { grid-area: n; }
.dpad-w { grid-area: w; }
.dpad-e { grid-area: e; }
.dpad-s { grid-area: s; }
.dpad button { padding: 0; }
.tile-grid {
image-rendering: pixelated;
cursor: crosshair;
touch-action: none;
max-width: 100%;
height: auto;
}
#previewCanvas {
width: 100%;
aspect-ratio: 1 / 1;
height: auto;
}
+918
View File
@@ -0,0 +1,918 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
(() => {
const SHAPES = [
{ type: ChunkTerrain.TILE_SHAPE_NULL, name: "Erase", color: "#20232a" },
{ type: ChunkTerrain.TILE_SHAPE_GROUND, name: "Ground", color: "#4caf50" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTH, name: "Ramp North", color: "#2196f3" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_EAST, name: "Ramp East", color: "#03a9f4" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTH, name: "Ramp South", color: "#00bcd4" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_WEST, name: "Ramp West", color: "#009688" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST, name: "Ramp NE", color: "#ff9800" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST, name: "Ramp NW", color: "#ff5722" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST, name: "Ramp SE", color: "#9c27b0" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST, name: "Ramp SW", color: "#e91e63" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST_INNER, name: "Ramp NE Inner", color: "#795548" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST_INNER, name: "Ramp NW Inner", color: "#607d8b" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST_INNER, name: "Ramp SE Inner", color: "#8bc34a" },
{ type: ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST_INNER, name: "Ramp SW Inner", color: "#ffc107" },
];
const SHAPE_COLORS = Object.fromEntries(SHAPES.map((s) => [s.type, s.color]));
// Arrow direction per ramp, in canvas/screen space: north is up (dy < 0),
// east is right (dx > 0) - matches renderGrid()'s north-is-up convention.
const SHAPE_DIRECTIONS = {
[ChunkTerrain.TILE_SHAPE_RAMP_NORTH]: { dx: 0, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTH]: { dx: 0, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_EAST]: { dx: 1, dy: 0 },
[ChunkTerrain.TILE_SHAPE_RAMP_WEST]: { dx: -1, dy: 0 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST]: { dx: 1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST]: { dx: -1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST]: { dx: 1, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST]: { dx: -1, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST_INNER]: { dx: 1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST_INNER]: { dx: -1, dy: -1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST_INNER]: { dx: 1, dy: 1 },
[ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST_INNER]: { dx: -1, dy: 1 },
};
const INNER_CORNER_SHAPES = new Set([
ChunkTerrain.TILE_SHAPE_RAMP_NORTHEAST_INNER,
ChunkTerrain.TILE_SHAPE_RAMP_NORTHWEST_INNER,
ChunkTerrain.TILE_SHAPE_RAMP_SOUTHEAST_INNER,
ChunkTerrain.TILE_SHAPE_RAMP_SOUTHWEST_INNER,
]);
// Draws a single-headed arrow from (tailX, tailY) to (tipX, tipY).
function drawArrowSegment(ctx, tailX, tailY, tipX, tipY, size) {
ctx.strokeStyle = "#ffffff";
ctx.fillStyle = "#ffffff";
ctx.lineWidth = Math.max(1, size * 0.08);
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(tailX, tailY);
ctx.lineTo(tipX, tipY);
ctx.stroke();
const headLen = size * 0.18;
const angle = Math.atan2(tipY - tailY, tipX - tailX);
const leftAngle = angle + Math.PI * 0.8;
const rightAngle = angle - Math.PI * 0.8;
ctx.beginPath();
ctx.moveTo(tipX, tipY);
ctx.lineTo(tipX + Math.cos(leftAngle) * headLen, tipY + Math.sin(leftAngle) * headLen);
ctx.lineTo(tipX + Math.cos(rightAngle) * headLen, tipY + Math.sin(rightAngle) * headLen);
ctx.closePath();
ctx.fill();
}
// Draws an arrow centered at (cx, cy) pointing toward the ramp's high
// side, so ramp direction is visible at a glance on both the palette
// swatches and the tile grid. Used for cardinal ramps and outer-corner
// ramps (a single raised corner).
function drawArrow(ctx, cx, cy, size, dx, dy) {
const mag = Math.hypot(dx, dy) || 1;
const ux = dx / mag, uy = dy / mag;
const len = size * 0.32;
drawArrowSegment(ctx, cx - ux * len, cy - uy * len, cx + ux * len, cy + uy * len, size);
}
// Draws a plain right-angle bracket - two line segments meeting at 90
// degrees at the tile's corner, one running along each of the two edges
// adjacent to it - so inner-corner ramps (three corners raised, one
// dropped) read as "the adjacent sides meeting in a 90-degree corner",
// distinct from the single diagonal arrow used for outer-corner ramps.
function drawCornerBracket(ctx, cx, cy, size, dx, dy) {
const cornerDist = size * 0.42;
const armLen = size * 0.34;
const cornerX = cx + dx * cornerDist;
const cornerY = cy + dy * cornerDist;
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = Math.max(1, size * 0.08);
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(cornerX - dx * armLen, cornerY);
ctx.lineTo(cornerX, cornerY);
ctx.lineTo(cornerX, cornerY - dy * armLen);
ctx.stroke();
}
// Draws the direction icon for a ramp tile `type` in a `size`x`size` area
// centered at (cx, cy): a diagonal arrow for cardinal/outer-corner ramps,
// or a right-angle bracket for inner-corner ramps. No-op for shapes with
// no direction (ground, erase).
function drawShapeIcon(ctx, cx, cy, size, type) {
const dir = SHAPE_DIRECTIONS[type];
if(!dir) return;
if(INNER_CORNER_SHAPES.has(type)) {
drawCornerBracket(ctx, cx, cy, size, dir.dx, dir.dy);
} else {
drawArrow(ctx, cx, cy, size, dir.dx, dir.dy);
}
}
// Draws a small pencil icon centered in a `size`x`size` canvas.
function drawPencilIcon(ctx, size) {
ctx.save();
ctx.translate(size / 2, size / 2);
ctx.rotate(-Math.PI / 4);
const shaftW = size * 0.18;
const shaftH = size * 0.62;
ctx.fillStyle = "#e0e0e0";
ctx.fillRect(-shaftW / 2, shaftH * 0.28, shaftW, shaftH * 0.22);
ctx.fillStyle = "#f0c419";
ctx.fillRect(-shaftW / 2, -shaftH * 0.5, shaftW, shaftH * 0.78);
ctx.fillStyle = "#8d6e63";
ctx.beginPath();
ctx.moveTo(-shaftW / 2, -shaftH * 0.5);
ctx.lineTo(shaftW / 2, -shaftH * 0.5);
ctx.lineTo(0, -shaftH * 0.5 - shaftW);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// Draws a small paint bucket icon centered in a `size`x`size` canvas.
function drawBucketIcon(ctx, size) {
ctx.save();
ctx.translate(size / 2, size / 2);
const w = size * 0.5, h = size * 0.34;
ctx.strokeStyle = "#e0e0e0";
ctx.lineWidth = Math.max(1, size * 0.06);
ctx.beginPath();
ctx.arc(0, -h * 0.4, w * 0.4, Math.PI, 0);
ctx.stroke();
ctx.fillStyle = "#03a9f4";
ctx.beginPath();
ctx.moveTo(-w / 2, -h * 0.2);
ctx.lineTo(w / 2, -h * 0.2);
ctx.lineTo(w * 0.32, h * 0.6);
ctx.lineTo(-w * 0.32, h * 0.6);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(-w * 0.55, h * 0.75, size * 0.06, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
const TOOLS = [
{ id: "pencil", name: "Pencil", draw: drawPencilIcon },
{ id: "bucket", name: "Paint Bucket", draw: drawBucketIcon },
];
let coord = { x: 0, y: 0, z: 0 };
let tiles = new Int32Array(ChunkTerrain.TILE_COUNT);
let meshes = [];
let chunkExists = false;
let currentZLevel = 0;
let selectedShape = ChunkTerrain.TILE_SHAPE_GROUND;
let zoomWorldH = 20;
let dirty = false;
let hoverTile = null;
let activeTool = "pencil";
let mapRenderer = null;
let terrainMesh = null;
let gridLinesMesh = null;
let terrainTexturePromise = null;
let modelIndex = null;
let neighborChunks = [];
const modelCache = new Map();
const UNDO_LIMIT = 100;
let undoStack = [];
function markDirty() {
dirty = true;
}
function snapshotState() {
return {
tiles: tiles.slice(),
meshes: meshes.map((m) => ({ file: m.file, pos: m.pos.slice() })),
};
}
function pushUndo() {
undoStack.push(snapshotState());
if(undoStack.length > UNDO_LIMIT) undoStack.shift();
}
function undo() {
if(!undoStack.length) return;
const snap = undoStack.pop();
tiles = snap.tiles;
meshes = snap.meshes;
dirty = true;
renderGrid();
renderMeshList();
renderPreview();
updateStatus("Undid last change.");
}
// Returns true if it's OK to proceed (no unsaved changes, or the user
// confirmed discarding them).
function confirmDiscardIfDirty() {
if(!dirty) return true;
return window.confirm("You have unsaved changes to this chunk. Discard them?");
}
function statusLine() {
return document.getElementById("statusLine");
}
function updateStatus(msg, isError) {
const el = statusLine();
el.textContent = msg;
el.classList.toggle("text-danger", !!isError);
el.classList.toggle("text-muted", !isError);
}
async function apiReadJson(path) {
const res = await fetch(`/api/read?path=${encodeURIComponent(path)}`);
const data = await res.json();
return { ok: res.ok, data };
}
async function apiWrite(path, content) {
return fetch(`/api/write?path=${encodeURIComponent(path)}`, {
method: "POST",
body: JSON.stringify({ content }),
});
}
async function apiDelete(path) {
return fetch(`/api/delete?path=${encodeURIComponent(path)}`, { method: "POST" });
}
async function apiCompileChunk(x, y, z) {
const res = await fetch(`/api/compile-chunk?x=${x}&y=${y}&z=${z}`, { method: "POST" });
return res.json();
}
async function apiLs(path) {
const res = await fetch(`/api/ls?path=${encodeURIComponent(path)}`);
return res.json();
}
async function apiFind(path, ext) {
const res = await fetch(`/api/find?path=${encodeURIComponent(path)}&ext=${encodeURIComponent(ext)}`);
return res.json();
}
function base64ToBuffer(base64) {
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
return bytes.buffer;
}
async function loadImageTexture(assetPath) {
const { ok, data } = await apiReadJson(assetPath);
if(!ok || data.error) return null;
const blob = new Blob([base64ToBuffer(data.content)], { type: "image/png" });
const bitmap = await createImageBitmap(blob);
return mapRenderer.createTextureFromImage(bitmap);
}
async function readDmfVertices(assetPath) {
const { ok, data } = await apiReadJson(assetPath);
if(!ok || data.error) throw new Error(`Failed to read ${assetPath}`);
return DMF.decode(base64ToBuffer(data.content)).floats;
}
async function ensureModelIndex() {
if(modelIndex) return modelIndex;
const res = await apiFind("assets/models", ".json");
modelIndex = new Map();
for(const file of res.files || []) {
const base = file.split("/").pop().replace(/\.json$/, "");
modelIndex.set(base, file);
}
return modelIndex;
}
// Scales a mesh's stored [x, y, z] offset for preview, matching the
// Z scaling mapChunkLoaded() applies at runtime (chunk.meshOffsets[m][2]
// * WORLD_LAYER_HEIGHT) - x/y stay 1:1 since only Z is height-scaled.
function scaledMeshOffset(pos) {
return [pos[0], pos[1], pos[2] * ChunkTerrain.WORLD_LAYER_HEIGHT];
}
// Resolves a chunk mesh entry's bare filename (e.g. "house_5_3.dmf") to
// its model JSON by basename, mirroring find_model() in
// tools/asset/chunk/__main__.py - the chunk JSON only ever stores a bare
// filename, not a path.
async function resolveModelForMeshFile(file) {
await ensureModelIndex();
const base = file.replace(/\.[^.]+$/, "");
const rel = modelIndex.get(base);
if(!rel) return null;
const modelPath = `assets/models/${rel}`;
if(modelCache.has(modelPath)) return modelCache.get(modelPath);
const promise = (async () => {
const { ok, data } = await apiReadJson(modelPath);
if(!ok || data.error) throw new Error(`Failed to read model ${modelPath}`);
const modelDef = JSON.parse(data.content);
const meshFloats = await readDmfVertices(`assets/${modelDef.mesh}`);
const mesh = mapRenderer.createMesh(meshFloats);
const texture = modelDef.texture ? await loadImageTexture(`assets/${modelDef.texture}`) : null;
const colorBytes = modelDef.color || [255, 255, 255, 255];
const color = colorBytes.map((c) => c / 255);
return { mesh, texture, color };
})();
modelCache.set(modelPath, promise);
return promise;
}
function chunkPaths(x, y, z) {
return {
raw: `assetsraw/chunks/chunk_${x}_${y}_${z}.json`,
dcf: `assets/chunks/${x}_${y}_${z}.dcf`,
terrainDmf: `assets/meshes/chunks/chunk_${x}_${y}_${z}_0.dmf`,
terrainModel: `assets/models/chunks/chunk_${x}_${y}_${z}_0.json`,
};
}
// Loads the 8 same-Z neighbors around `coord` (read-only, for context in
// the 3D preview) and pre-builds their render data so renderPreview()
// doesn't have to rebuild GL buffers on every paint stroke.
async function loadNeighborChunks() {
const offsets = [];
for(let dy = -1; dy <= 1; dy++) {
for(let dx = -1; dx <= 1; dx++) {
if(dx || dy) offsets.push({ dx, dy });
}
}
const results = await Promise.all(offsets.map(async ({ dx, dy }) => {
const nx = coord.x + dx, ny = coord.y + dy, nz = coord.z;
const { ok, data } = await apiReadJson(chunkPaths(nx, ny, nz).raw);
if(!ok || data.error) return null;
const json = JSON.parse(data.content);
const neighborTiles = new Int32Array(ChunkTerrain.TILE_COUNT);
for(const t of json.tiles || []) {
const [tx, ty, tz] = t.pos;
neighborTiles[ChunkTerrain.tileIndex(tx, ty, tz)] = t.type;
}
const neighborMeshes = (json.meshes || []).map((m) => ({ file: m.file, pos: m.pos || [0, 0, 0] }));
const floats = ChunkTerrain.buildTerrainVerts(neighborTiles);
const terrain = floats.length ? { mesh: mapRenderer.createMesh(floats) } : null;
const models = [];
for(const m of neighborMeshes) {
try {
const resolved = await resolveModelForMeshFile(m.file);
if(resolved) models.push({ ...resolved, offset: scaledMeshOffset(m.pos) });
} catch(e) {
console.warn("Failed to load neighbor mesh preview", m.file, e);
}
}
return {
offset: [dx * ChunkTerrain.CHUNK_WIDTH, dy * ChunkTerrain.CHUNK_HEIGHT, 0],
terrain,
models,
};
}));
neighborChunks = results.filter(Boolean);
}
async function loadChunk(x, y, z) {
coord = { x, y, z };
tiles = new Int32Array(ChunkTerrain.TILE_COUNT);
meshes = [];
chunkExists = false;
const { ok, data } = await apiReadJson(chunkPaths(x, y, z).raw);
if(ok && !data.error) {
chunkExists = true;
const json = JSON.parse(data.content);
for(const t of json.tiles || []) {
const [tx, ty, tz] = t.pos;
tiles[ChunkTerrain.tileIndex(tx, ty, tz)] = t.type;
}
meshes = (json.meshes || []).map((m) => ({ file: m.file, pos: m.pos || [0, 0, 0] }));
}
await loadNeighborChunks();
dirty = false;
undoStack = [];
renderGrid();
renderMeshList();
renderPreview();
updateStatus(chunkExists
? `Loaded chunk_${x}_${y}_${z}.json`
: `New (empty) chunk at ${x}, ${y}, ${z} - paint a tile and save to create it.`);
}
async function saveChunk() {
const tilesArr = [];
for(let z = 0; z < ChunkTerrain.CHUNK_DEPTH; z++) {
for(let y = 0; y < ChunkTerrain.CHUNK_HEIGHT; y++) {
for(let x = 0; x < ChunkTerrain.CHUNK_WIDTH; x++) {
const type = tiles[ChunkTerrain.tileIndex(x, y, z)];
if(type && type !== ChunkTerrain.TILE_SHAPE_NULL) {
tilesArr.push({ pos: [x, y, z], type, tile: 0 });
}
}
}
}
const paths = chunkPaths(coord.x, coord.y, coord.z);
if(tilesArr.length === 0 && meshes.length === 0) {
await Promise.all(Object.values(paths).map((p) => apiDelete(p)));
chunkExists = false;
dirty = false;
updateStatus(`Chunk ${coord.x}, ${coord.y}, ${coord.z} is empty - deleted.`);
return;
}
const json = { tiles: tilesArr, meshes: meshes.map((m) => ({ file: m.file, pos: m.pos })) };
await apiWrite(paths.raw, JSON.stringify(json, null, 2));
chunkExists = true;
dirty = false;
updateStatus("Saved. Compiling...");
const result = await apiCompileChunk(coord.x, coord.y, coord.z);
if(result.ok) {
updateStatus(`Compiled OK.\n${result.stdout}`);
} else {
updateStatus(`Compile FAILED (code ${result.returncode}):\n${result.stderr}`, true);
}
}
function buildPalette() {
const el = document.getElementById("tilePalette");
el.innerHTML = "";
for(const s of SHAPES) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "tile-swatch" + (s.type === selectedShape ? " active" : "");
btn.style.background = s.color;
btn.title = s.name;
btn.addEventListener("click", () => {
selectedShape = s.type;
buildPalette();
});
if(SHAPE_DIRECTIONS[s.type]) {
const icon = document.createElement("canvas");
icon.width = 32;
icon.height = 32;
icon.className = "tile-swatch-icon";
drawShapeIcon(icon.getContext("2d"), 16, 16, 32, s.type);
btn.appendChild(icon);
}
el.appendChild(btn);
}
}
function buildToolPalette() {
const el = document.getElementById("toolPalette");
el.innerHTML = "";
for(const tool of TOOLS) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "tile-swatch" + (tool.id === activeTool ? " active" : "");
btn.style.background = "#2a2d33";
btn.title = tool.name;
btn.addEventListener("click", () => {
activeTool = tool.id;
buildToolPalette();
});
const icon = document.createElement("canvas");
icon.width = 32;
icon.height = 32;
icon.className = "tile-swatch-icon";
tool.draw(icon.getContext("2d"), 32);
btn.appendChild(icon);
el.appendChild(btn);
}
}
function canvasToTile(e, canvas) {
const rect = canvas.getBoundingClientRect();
const cell = canvas.width / ChunkTerrain.CHUNK_WIDTH;
const px = (e.clientX - rect.left) * (canvas.width / rect.width);
const py = (e.clientY - rect.top) * (canvas.height / rect.height);
const x = Math.floor(px / cell);
const yFromTop = Math.floor(py / cell);
const y = ChunkTerrain.CHUNK_HEIGHT - 1 - yFromTop;
if(x < 0 || x >= ChunkTerrain.CHUNK_WIDTH || y < 0 || y >= ChunkTerrain.CHUNK_HEIGHT) return null;
return { x, y };
}
function renderGrid() {
const canvas = document.getElementById("gridCanvas");
const ctx = canvas.getContext("2d");
const cell = canvas.width / ChunkTerrain.CHUNK_WIDTH;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(let y = 0; y < ChunkTerrain.CHUNK_HEIGHT; y++) {
for(let x = 0; x < ChunkTerrain.CHUNK_WIDTH; x++) {
const type = tiles[ChunkTerrain.tileIndex(x, y, currentZLevel)];
const sy = (ChunkTerrain.CHUNK_HEIGHT - 1 - y) * cell;
ctx.fillStyle = SHAPE_COLORS[type] || "#15171b";
ctx.fillRect(x * cell, sy, cell, cell);
ctx.strokeStyle = "rgba(255, 255, 255, 0.25)";
ctx.strokeRect(x * cell, sy, cell, cell);
drawShapeIcon(ctx, x * cell + cell / 2, sy + cell / 2, cell, type);
}
}
ctx.fillStyle = "#ffffff";
for(const m of meshes) {
const [mx, my, mz] = m.pos;
if(Math.round(mz) !== currentZLevel) continue;
const sy = (ChunkTerrain.CHUNK_HEIGHT - 1 - my) * cell;
ctx.beginPath();
ctx.arc(mx * cell + cell / 2, sy + cell / 2, cell * 0.3, 0, Math.PI * 2);
ctx.fill();
}
if(hoverTile) {
const sy = (ChunkTerrain.CHUNK_HEIGHT - 1 - hoverTile.y) * cell;
ctx.strokeStyle = "#ffeb3b";
ctx.lineWidth = 2;
ctx.strokeRect(hoverTile.x * cell + 1, sy + 1, cell - 2, cell - 2);
}
}
function hitTestMesh(e, canvas) {
const rect = canvas.getBoundingClientRect();
const cell = canvas.width / ChunkTerrain.CHUNK_WIDTH;
const px = (e.clientX - rect.left) * (canvas.width / rect.width);
const py = (e.clientY - rect.top) * (canvas.height / rect.height);
let closest = -1;
let closestDist = cell * 0.5;
meshes.forEach((m, i) => {
const [mx, my, mz] = m.pos;
if(Math.round(mz) !== currentZLevel) return;
const cx = mx * cell + cell / 2;
const cy = (ChunkTerrain.CHUNK_HEIGHT - 1 - my) * cell + cell / 2;
const dist = Math.hypot(px - cx, py - cy);
if(dist < closestDist) { closestDist = dist; closest = i; }
});
return closest;
}
function moveMeshTo(e, index) {
const canvas = document.getElementById("gridCanvas");
const t = canvasToTile(e, canvas);
if(!t) return;
meshes[index].pos[0] = t.x;
meshes[index].pos[1] = t.y;
markDirty();
renderGrid();
renderMeshList();
renderPreview();
}
function paintAt(e) {
const canvas = document.getElementById("gridCanvas");
const t = canvasToTile(e, canvas);
if(!t) return;
tiles[ChunkTerrain.tileIndex(t.x, t.y, currentZLevel)] = selectedShape;
markDirty();
renderGrid();
renderPreview();
}
// 4-connected flood fill of same-type tiles at the current Z-level,
// starting from (startX, startY), replacing them with selectedShape.
function floodFill(startX, startY) {
const targetType = tiles[ChunkTerrain.tileIndex(startX, startY, currentZLevel)];
if(targetType === selectedShape) return;
const stack = [[startX, startY]];
const visited = new Set();
while(stack.length) {
const [x, y] = stack.pop();
const key = `${x},${y}`;
if(visited.has(key)) continue;
if(x < 0 || x >= ChunkTerrain.CHUNK_WIDTH || y < 0 || y >= ChunkTerrain.CHUNK_HEIGHT) continue;
visited.add(key);
const idx = ChunkTerrain.tileIndex(x, y, currentZLevel);
if(tiles[idx] !== targetType) continue;
tiles[idx] = selectedShape;
stack.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);
}
}
function fillAt(e) {
const canvas = document.getElementById("gridCanvas");
const t = canvasToTile(e, canvas);
if(!t) return;
pushUndo();
floodFill(t.x, t.y);
markDirty();
renderGrid();
renderPreview();
}
function rebuildTerrainMesh() {
const floats = ChunkTerrain.buildTerrainVerts(tiles);
terrainMesh = floats.length ? mapRenderer.createMesh(floats) : null;
const lineFloats = ChunkTerrain.buildGridLines(tiles);
gridLinesMesh = lineFloats.length ? mapRenderer.createMesh(lineFloats) : null;
}
// Keeps the preview canvas's backing-store resolution matched to its
// actual displayed CSS size (times devicePixelRatio) - the canvas
// otherwise stays at its fixed width/height attributes (512x512) while
// CSS stretches it to fill the column, which upscales and blurs the
// WebGL output on wider or high-DPI screens.
function resizePreviewCanvas() {
const canvas = document.getElementById("previewCanvas");
const dpr = window.devicePixelRatio || 1;
const displayWidth = Math.max(1, Math.round(canvas.clientWidth * dpr));
const displayHeight = Math.max(1, Math.round(canvas.clientHeight * dpr));
if(canvas.width !== displayWidth || canvas.height !== displayHeight) {
canvas.width = displayWidth;
canvas.height = displayHeight;
}
}
async function renderPreview() {
if(!mapRenderer) return;
resizePreviewCanvas();
rebuildTerrainMesh();
const models = [];
for(const m of meshes) {
try {
const resolved = await resolveModelForMeshFile(m.file);
if(resolved) models.push({ ...resolved, offset: scaledMeshOffset(m.pos) });
} catch(e) {
console.warn("Failed to load mesh preview", m.file, e);
}
}
let terrainTexture = null;
if(terrainMesh || neighborChunks.some((n) => n.terrain)) {
if(!terrainTexturePromise) terrainTexturePromise = loadImageTexture("assets/tiles.png");
terrainTexture = await terrainTexturePromise;
}
const neighbors = neighborChunks.map((n) => ({
offset: n.offset,
terrain: n.terrain ? { mesh: n.terrain.mesh, texture: terrainTexture } : null,
models: n.models,
}));
const zLevelHeight = currentZLevel * ChunkTerrain.WORLD_LAYER_HEIGHT;
mapRenderer.render({
target: [ChunkTerrain.CHUNK_WIDTH / 2, ChunkTerrain.CHUNK_HEIGHT / 2, zLevelHeight],
worldH: zoomWorldH,
terrain: terrainMesh ? { mesh: terrainMesh, texture: terrainTexture } : null,
gridLines: gridLinesMesh ? { mesh: gridLinesMesh } : null,
models,
neighbors,
highlight: hoverTile ? { x: hoverTile.x, y: hoverTile.y, z: zLevelHeight } : null,
});
}
function renderMeshList() {
const ul = document.getElementById("meshList");
ul.innerHTML = "";
meshes.forEach((m, i) => {
const li = document.createElement("li");
li.className = "list-group-item d-flex align-items-center gap-2 flex-wrap";
const label = document.createElement("span");
label.className = "me-auto";
label.textContent = m.file;
li.appendChild(label);
["X", "Y", "Z"].forEach((axis, axisIndex) => {
const input = document.createElement("input");
input.type = "number";
input.className = "form-control form-control-sm";
input.style.width = "5rem";
input.title = axis;
input.value = m.pos[axisIndex];
input.addEventListener("change", () => {
pushUndo();
m.pos[axisIndex] = parseFloat(input.value) || 0;
markDirty();
renderGrid();
renderPreview();
});
li.appendChild(input);
});
const btn = document.createElement("button");
btn.type = "button";
btn.className = "btn btn-sm btn-outline-danger";
btn.textContent = "Remove";
btn.addEventListener("click", () => {
pushUndo();
meshes.splice(i, 1);
markDirty();
renderMeshList();
renderGrid();
renderPreview();
});
li.appendChild(btn);
ul.appendChild(li);
});
}
async function buildMeshPicker() {
await ensureModelIndex();
const select = document.getElementById("meshPicker");
select.innerHTML = "";
for(const [base, rel] of [...modelIndex.entries()].sort()) {
const opt = document.createElement("option");
opt.value = base;
opt.textContent = rel;
select.appendChild(opt);
}
}
async function buildChunkBrowseList() {
const list = document.getElementById("chunkBrowseList");
list.innerHTML = "";
const res = await apiLs("assetsraw/chunks");
for(const entry of res.entries || []) {
const m = entry.name.match(/^chunk_(-?\d+)_(-?\d+)_(-?\d+)\.json$/);
if(!m) continue;
const [, x, y, z] = m;
const li = document.createElement("li");
const a = document.createElement("a");
a.className = "dropdown-item";
a.href = "#";
a.textContent = `${x}, ${y}, ${z}`;
a.addEventListener("click", (e) => {
e.preventDefault();
goToChunk(parseInt(x, 10), parseInt(y, 10), parseInt(z, 10));
});
li.appendChild(a);
list.appendChild(li);
}
}
function setCoordInputs(x, y, z) {
document.getElementById("coordX").value = x;
document.getElementById("coordY").value = y;
document.getElementById("coordZ").value = z;
}
function goToChunk(x, y, z) {
if(!confirmDiscardIfDirty()) return;
setCoordInputs(x, y, z);
loadChunk(x, y, z);
}
function bindEvents() {
const gridCanvas = document.getElementById("gridCanvas");
let painting = false;
let draggingMeshIndex = -1;
gridCanvas.addEventListener("mousedown", (e) => {
if(activeTool === "bucket") {
fillAt(e);
return;
}
const hit = hitTestMesh(e, gridCanvas);
pushUndo();
if(hit !== -1) {
draggingMeshIndex = hit;
return;
}
painting = true;
paintAt(e);
});
window.addEventListener("mouseup", () => { painting = false; draggingMeshIndex = -1; });
gridCanvas.addEventListener("mousemove", (e) => {
hoverTile = canvasToTile(e, gridCanvas);
if(draggingMeshIndex !== -1) { moveMeshTo(e, draggingMeshIndex); return; }
if(painting) { paintAt(e); return; }
renderGrid();
renderPreview();
});
gridCanvas.addEventListener("mouseleave", () => {
hoverTile = null;
renderGrid();
renderPreview();
});
function setZLevel(z) {
currentZLevel = Math.max(0, Math.min(ChunkTerrain.CHUNK_DEPTH - 1, z));
document.getElementById("zLevel").value = currentZLevel;
document.getElementById("zLevelLabel").textContent = currentZLevel;
renderGrid();
renderPreview();
}
document.getElementById("zLevel").addEventListener("input", (e) => {
setZLevel(parseInt(e.target.value, 10));
});
document.getElementById("zLevelDown").addEventListener("click", () => setZLevel(currentZLevel - 1));
document.getElementById("zLevelUp").addEventListener("click", () => setZLevel(currentZLevel + 1));
document.getElementById("btnLoad").addEventListener("click", () => {
const x = parseInt(document.getElementById("coordX").value, 10) || 0;
const y = parseInt(document.getElementById("coordY").value, 10) || 0;
const z = parseInt(document.getElementById("coordZ").value, 10) || 0;
goToChunk(x, y, z);
});
// NORTH=+Y, EAST=+X (matches tile-shape convention used by the tile
// grid and tools/asset/chunk/__main__.py).
document.getElementById("navN").addEventListener("click", () => goToChunk(coord.x, coord.y + 1, coord.z));
document.getElementById("navS").addEventListener("click", () => goToChunk(coord.x, coord.y - 1, coord.z));
document.getElementById("navE").addEventListener("click", () => goToChunk(coord.x + 1, coord.y, coord.z));
document.getElementById("navW").addEventListener("click", () => goToChunk(coord.x - 1, coord.y, coord.z));
document.getElementById("navUp").addEventListener("click", () => goToChunk(coord.x, coord.y, coord.z + 1));
document.getElementById("navDown").addEventListener("click", () => goToChunk(coord.x, coord.y, coord.z - 1));
function runSave() {
saveChunk().catch((e) => updateStatus(`Save failed: ${e.message}`, true));
}
document.getElementById("btnSave").addEventListener("click", runSave);
document.getElementById("btnAddMesh").addEventListener("click", () => {
const base = document.getElementById("meshPicker").value;
if(!base) return;
const pos = [
parseFloat(document.getElementById("meshX").value) || 0,
parseFloat(document.getElementById("meshY").value) || 0,
parseFloat(document.getElementById("meshZ").value) || 0,
];
pushUndo();
meshes.push({ file: `${base}.dmf`, pos });
markDirty();
renderMeshList();
renderGrid();
renderPreview();
});
document.getElementById("previewCanvas").addEventListener("wheel", (e) => {
e.preventDefault();
zoomWorldH = Math.min(60, Math.max(4, zoomWorldH + Math.sign(e.deltaY)));
renderPreview();
}, { passive: false });
window.addEventListener("resize", () => renderPreview());
window.addEventListener("keydown", (e) => {
if(!(e.ctrlKey || e.metaKey)) return;
const key = e.key.toLowerCase();
if(key === "z") {
e.preventDefault();
undo();
} else if(key === "s") {
e.preventDefault();
runSave();
}
});
}
document.addEventListener("DOMContentLoaded", async () => {
buildPalette();
buildToolPalette();
mapRenderer = MapRenderer.create(document.getElementById("previewCanvas"));
bindEvents();
await Promise.all([buildChunkBrowseList(), buildMeshPicker()]);
await loadChunk(coord.x, coord.y, coord.z);
});
})();
+298
View File
@@ -0,0 +1,298 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
"use strict";
// MapRenderer - a minimal, dependency-free WebGL renderer for the chunk
// preview pane. The camera formula is ported 1:1 from
// src/dusk/scene/overworld/sceneoverworld.c (lines 62-81) so the preview
// approximates the game's own fixed-angle 3rd-person camera: the eye sits
// worldH units "behind" the target along Y and a proportional distance
// "above" along Z, always looking at the target, up = (0, 1, 0).
//
// The material model mirrors SHADER_UNLIT: a texture sampler multiplied by
// a flat RGBA tint, with a 1x1 white fallback texture standing in for
// untextured models.
const MapRenderer = (() => {
const VERT_SRC = `
attribute vec2 aUV;
attribute vec3 aPos;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProjection;
varying vec2 vUV;
void main() {
vUV = aUV;
gl_Position = uProjection * uView * uModel * vec4(aPos, 1.0);
}
`;
const FRAG_SRC = `
precision mediump float;
varying vec2 vUV;
uniform sampler2D uTexture;
uniform vec4 uColor;
void main() {
gl_FragColor = texture2D(uTexture, vUV) * uColor;
}
`;
function mat4Identity(out) {
out.fill(0);
out[0] = out[5] = out[10] = out[15] = 1;
return out;
}
function mat4Translation(out, v) {
mat4Identity(out);
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
return out;
}
function mat4Perspective(out, fovy, aspect, near, far) {
const f = 1.0 / Math.tan(fovy / 2);
out.fill(0);
out[0] = f / aspect;
out[5] = f;
out[10] = (far + near) / (near - far);
out[11] = -1;
out[14] = (2 * far * near) / (near - far);
return out;
}
function vec3Sub(a, b) {
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
}
function vec3Cross(a, b) {
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
}
function vec3Normalize(a) {
const len = Math.hypot(a[0], a[1], a[2]) || 1;
return [a[0] / len, a[1] / len, a[2] / len];
}
function mat4LookAt(out, eye, center, up) {
const zAxis = vec3Normalize(vec3Sub(eye, center));
const xAxis = vec3Normalize(vec3Cross(up, zAxis));
const yAxis = vec3Cross(zAxis, xAxis);
out[0] = xAxis[0]; out[1] = yAxis[0]; out[2] = zAxis[0]; out[3] = 0;
out[4] = xAxis[1]; out[5] = yAxis[1]; out[6] = zAxis[1]; out[7] = 0;
out[8] = xAxis[2]; out[9] = yAxis[2]; out[10] = zAxis[2]; out[11] = 0;
out[12] = -(xAxis[0] * eye[0] + xAxis[1] * eye[1] + xAxis[2] * eye[2]);
out[13] = -(yAxis[0] * eye[0] + yAxis[1] * eye[1] + yAxis[2] * eye[2]);
out[14] = -(zAxis[0] * eye[0] + zAxis[1] * eye[1] + zAxis[2] * eye[2]);
out[15] = 1;
return out;
}
// Ported from sceneoverworld.c:62-81. Returns { eye, view }.
function computeCamera(target, worldH) {
const fov = Math.PI / 4; // glm_rad(45.0f)
const zDist = (worldH * 0.5) / Math.tan(fov * 0.5);
const offset = -worldH;
const eye = [target[0], target[1] + offset, target[2] + zDist];
const view = mat4LookAt(new Float32Array(16), eye, target, [0, 1, 0]);
return { eye, view, fov };
}
function compileShader(gl, type, src) {
const shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const info = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error(`Shader compile failed: ${info}`);
}
return shader;
}
function create(canvas) {
const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
if(!gl) throw new Error("WebGL is not available in this browser");
const program = gl.createProgram();
gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, VERT_SRC));
gl.attachShader(program, compileShader(gl, gl.FRAGMENT_SHADER, FRAG_SRC));
gl.linkProgram(program);
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(`Program link failed: ${gl.getProgramInfoLog(program)}`);
}
const attribs = {
aUV: gl.getAttribLocation(program, "aUV"),
aPos: gl.getAttribLocation(program, "aPos"),
};
const uniforms = {
uModel: gl.getUniformLocation(program, "uModel"),
uView: gl.getUniformLocation(program, "uView"),
uProjection: gl.getUniformLocation(program, "uProjection"),
uTexture: gl.getUniformLocation(program, "uTexture"),
uColor: gl.getUniformLocation(program, "uColor"),
};
const whiteTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, whiteTexture);
gl.texImage2D(
gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
new Uint8Array([255, 255, 255, 255]),
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
// Terrain/mesh winding isn't guaranteed consistent relative to this
// preview's fixed camera angle, so backface culling stays off - this
// is an authoring preview, not a performance-sensitive renderer, and
// an invisible mesh is a worse failure mode than a visible backface.
// Uploads interleaved [u, v, x, y, z] float data (DMF/terrain layout)
// into a GL buffer. Returns { buffer, vertexCount }.
function createMesh(floats) {
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, floats, gl.STATIC_DRAW);
return { buffer, vertexCount: floats.length / 5 };
}
function createTextureFromImage(image) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return texture;
}
function drawMesh(mesh, model, texture, color, depthWrite, mode) {
gl.depthMask(depthWrite !== false);
gl.bindBuffer(gl.ARRAY_BUFFER, mesh.buffer);
gl.enableVertexAttribArray(attribs.aUV);
gl.vertexAttribPointer(attribs.aUV, 2, gl.FLOAT, false, 20, 0);
gl.enableVertexAttribArray(attribs.aPos);
gl.vertexAttribPointer(attribs.aPos, 3, gl.FLOAT, false, 20, 8);
gl.uniformMatrix4fv(uniforms.uModel, false, model);
gl.uniform4f(uniforms.uColor, color[0], color[1], color[2], color[3]);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture || whiteTexture);
gl.uniform1i(uniforms.uTexture, 0);
gl.drawArrays(mode || gl.TRIANGLES, 0, mesh.vertexCount);
}
// Builds a 4-vertex outline of the tile at (x, y, z), lifted slightly
// to avoid z-fighting with the terrain surface beneath it.
function buildHighlightMesh(x, y, z) {
const eps = 0.02;
return createMesh(new Float32Array([
0, 0, x, y, z + eps,
0, 0, x + 1, y, z + eps,
0, 0, x + 1, y + 1, z + eps,
0, 0, x, y + 1, z + eps,
]));
}
// Neighboring chunks are drawn dimmer and semi-transparent, so they
// read as context rather than part of the chunk being edited.
const NEIGHBOR_ALPHA = 0.35;
const NEIGHBOR_DARKEN = 0.5;
// scene = {
// target: [x, y, z], worldH: number,
// terrain: { mesh, texture } | null,
// gridLines: { mesh } | null,
// models: [{ mesh, texture, color: [r,g,b,a in 0..1], offset: [x,y,z] }],
// neighbors: [{
// offset: [x,y,z],
// terrain: { mesh, texture } | null,
// models: [{ mesh, texture, color, offset }],
// }],
// highlight: { x, y, z } | null,
// }
function render(scene) {
const width = canvas.width, height = canvas.height;
gl.viewport(0, 0, width, height);
gl.clearColor(0.16, 0.18, 0.22, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.useProgram(program);
gl.depthMask(true);
const { view, fov } = computeCamera(scene.target, scene.worldH);
const projection = mat4Perspective(new Float32Array(16), fov, width / height, 0.1, 1000);
gl.uniformMatrix4fv(uniforms.uProjection, false, projection);
gl.uniformMatrix4fv(uniforms.uView, false, view);
const identity = mat4Identity(new Float32Array(16));
if(scene.terrain) {
drawMesh(scene.terrain.mesh, identity, scene.terrain.texture, [1, 1, 1, 1], true);
}
if(scene.gridLines) {
drawMesh(scene.gridLines.mesh, identity, null, [0, 0, 0, 0.35], false, gl.LINES);
}
for(const model of scene.models) {
const modelMatrix = mat4Translation(new Float32Array(16), model.offset);
drawMesh(model.mesh, modelMatrix, model.texture, model.color, true);
}
for(const neighbor of scene.neighbors || []) {
if(neighbor.terrain) {
const modelMatrix = mat4Translation(new Float32Array(16), neighbor.offset);
drawMesh(
neighbor.terrain.mesh, modelMatrix, neighbor.terrain.texture,
[NEIGHBOR_DARKEN, NEIGHBOR_DARKEN, NEIGHBOR_DARKEN, NEIGHBOR_ALPHA], false,
);
}
for(const model of neighbor.models) {
const worldOffset = [
neighbor.offset[0] + model.offset[0],
neighbor.offset[1] + model.offset[1],
neighbor.offset[2] + model.offset[2],
];
const modelMatrix = mat4Translation(new Float32Array(16), worldOffset);
const color = [
model.color[0] * NEIGHBOR_DARKEN,
model.color[1] * NEIGHBOR_DARKEN,
model.color[2] * NEIGHBOR_DARKEN,
model.color[3] * NEIGHBOR_ALPHA,
];
drawMesh(model.mesh, modelMatrix, model.texture, color, false);
}
}
if(scene.highlight) {
const { x, y, z } = scene.highlight;
const highlightMesh = buildHighlightMesh(x, y, z);
drawMesh(highlightMesh, identity, null, [1, 0.92, 0.23, 1], false, gl.LINE_LOOP);
}
}
return { gl, createMesh, createTextureFromImage, render };
}
return Object.freeze({ create, computeCamera });
})();
+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dusk Map Editor</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">Dusk Map Editor</a>
<ul class="navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/map">Map Editor</a>
</li>
</ul>
</div>
</nav>
<div id="editor" class="container-fluid py-3"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
+295
View File
@@ -0,0 +1,295 @@
"""
Map Editor HTTP Server
Serves editor/client/public/ as static files with smart routing:
/ -> index.html
/page -> page.html or page/index.html
/index -> index.html
API endpoints (all paths relative to project root):
GET /api/ls?path=<dir> directory listing
GET /api/read?path=<file> file contents
GET /api/find?path=<dir>&ext=<.json> recursive file listing by extension
POST /api/write?path=<file> write file (JSON body: {"content":"..."})
POST /api/mkdir?path=<dir> create directory
POST /api/delete?path=<file> delete a file
POST /api/compile-chunk?x=&y=&z= recompile a chunk JSON to .dcf
"""
import os
import re
import sys
import json
import mimetypes
import subprocess
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs, unquote
from pathlib import Path
CHUNK_COORD_RE = re.compile(r"^-?\d+$")
PORT = 3000
SCRIPT_DIR = Path(__file__).parent.resolve()
PUBLIC_DIR = SCRIPT_DIR.parent / "client" / "public"
PROJECT_ROOT = SCRIPT_DIR.parent.parent.resolve()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
path = unquote(parsed.path)
if path.startswith("/api/"):
params = parse_qs(parsed.query)
if path == "/api/ls":
self.api_ls(params)
elif path == "/api/read":
self.api_read(params)
elif path == "/api/find":
self.api_find(params)
else:
self.send_error(404)
else:
self.serve_static(path)
def do_POST(self):
parsed = urlparse(self.path)
params = parse_qs(parsed.query)
if parsed.path == "/api/write":
self.api_write(params)
elif parsed.path == "/api/mkdir":
self.api_mkdir(params)
elif parsed.path == "/api/delete":
self.api_delete(params)
elif parsed.path == "/api/compile-chunk":
self.api_compile_chunk(params)
else:
self.send_error(404)
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def resolve_project_path(self, rel):
rel = rel.lstrip("/")
target = (PROJECT_ROOT / rel).resolve()
if not str(target).startswith(str(PROJECT_ROOT)):
return None
return target
def send_json(self, data, code=200):
body = json.dumps(data, indent=2).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", len(body))
self.end_headers()
self.wfile.write(body)
def read_body(self):
length = int(self.headers.get("Content-Length", 0))
return self.rfile.read(length)
# ------------------------------------------------------------------
# API handlers
# ------------------------------------------------------------------
def api_ls(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if not target.exists():
self.send_json({"error": "path not found"}, 404)
return
if not target.is_dir():
self.send_json({"error": "not a directory"}, 400)
return
entries = []
for entry in sorted(target.iterdir(), key=lambda e: (e.is_file(), e.name)):
entries.append({
"name": entry.name,
"type": "dir" if entry.is_dir() else "file",
"size": entry.stat().st_size if entry.is_file() else None,
})
self.send_json({
"path": str(target.relative_to(PROJECT_ROOT)),
"entries": entries,
})
def api_read(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if not target.exists():
self.send_json({"error": "file not found"}, 404)
return
if not target.is_file():
self.send_json({"error": "not a file"}, 400)
return
try:
content = target.read_text(encoding="utf-8")
self.send_json({
"path": str(target.relative_to(PROJECT_ROOT)),
"content": content,
})
except UnicodeDecodeError:
import base64
content = base64.b64encode(target.read_bytes()).decode("ascii")
self.send_json({
"path": str(target.relative_to(PROJECT_ROOT)),
"content": content,
"encoding": "base64",
})
def api_write(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
body = self.read_body()
try:
data = json.loads(body)
content = data.get("content", "")
except (json.JSONDecodeError, UnicodeDecodeError):
content = body.decode("utf-8")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
self.send_json({"ok": True, "path": str(target.relative_to(PROJECT_ROOT))})
def api_mkdir(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
target.mkdir(parents=True, exist_ok=True)
self.send_json({"ok": True, "path": str(target.relative_to(PROJECT_ROOT))})
def api_delete(self, params):
rel = params.get("path", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if target.is_file():
target.unlink()
self.send_json({"ok": True, "path": str(target.relative_to(PROJECT_ROOT))})
def api_find(self, params):
rel = params.get("path", [""])[0]
ext = params.get("ext", [""])[0]
target = self.resolve_project_path(rel)
if target is None:
self.send_json({"error": "invalid path"}, 400)
return
if not target.is_dir():
self.send_json({"error": "not a directory"}, 400)
return
pattern = f"*{ext}" if ext else "*"
paths = sorted(
str(p.relative_to(target)).replace(os.sep, "/")
for p in target.rglob(pattern)
if p.is_file()
)
self.send_json({"path": str(target.relative_to(PROJECT_ROOT)), "files": paths})
def api_compile_chunk(self, params):
x = params.get("x", [""])[0]
y = params.get("y", [""])[0]
z = params.get("z", [""])[0]
if not (CHUNK_COORD_RE.match(x) and CHUNK_COORD_RE.match(y) and CHUNK_COORD_RE.match(z)):
self.send_json({"error": "invalid chunk coordinates"}, 400)
return
json_path = PROJECT_ROOT / "assetsraw" / "chunks" / f"chunk_{x}_{y}_{z}.json"
if not json_path.is_file():
self.send_json({"error": "chunk json not found"}, 404)
return
result = subprocess.run(
[sys.executable, "-m", "tools.asset.chunk", str(json_path)],
cwd=str(PROJECT_ROOT),
capture_output=True,
text=True,
)
self.send_json({
"ok": result.returncode == 0,
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
})
# ------------------------------------------------------------------
# Static file serving
# ------------------------------------------------------------------
def serve_static(self, path):
clean = path.lstrip("/")
candidates = []
if clean == "" or clean == "index" or clean == "index.html":
candidates = ["index.html"]
else:
candidates.append(clean)
if "." not in Path(clean).name:
candidates.append(clean + ".html")
candidates.append(clean + "/index.html")
for candidate in candidates:
file_path = PUBLIC_DIR / candidate
if file_path.is_file():
self.serve_file(file_path)
return
self.send_error(404)
def serve_file(self, file_path):
mime, _ = mimetypes.guess_type(str(file_path))
mime = mime or "application/octet-stream"
template = PUBLIC_DIR / "template.html"
if (
mime == "text/html"
and file_path.name != "template.html"
and template.is_file()
):
fragment = file_path.read_text(encoding="utf-8")
shell = template.read_text(encoding="utf-8")
marker = shell.find('id="editor"')
if marker == -1:
content = shell.encode("utf-8")
else:
tag_end = shell.index(">", marker) + 1
close_idx = shell.index("</div>", tag_end)
content = (shell[:tag_end] + fragment + shell[close_idx:]).encode("utf-8")
else:
content = file_path.read_bytes()
self.send_response(200)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", len(content))
self.end_headers()
self.wfile.write(content)
def log_message(self, fmt, *args):
print(f" {self.address_string()} {fmt % args}")
if __name__ == "__main__":
print(f"Map Editor")
print(f" http://localhost:{PORT}")
print(f" public : {PUBLIC_DIR}")
print(f" project: {PROJECT_ROOT}")
server = HTTPServer(("", PORT), Handler)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nStopped.")
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -e
cd "$(dirname "$0")"
python3 server/server.py
+1 -1
View File
@@ -1,3 +1,3 @@
#!/bin/bash
docker build -t dusk-psp -f docker/psp/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-psp /bin/bash -c "./scripts/build-psp.sh"
docker run --rm -v "$(pwd):/workdir" dusk-psp /bin/bash -c "./scripts/build-psp.sh"
+1 -1
View File
@@ -6,7 +6,7 @@ fi
mkdir -p build-psp
cd build-psp
psp-cmake -DDUSK_TARGET_SYSTEM=psp -DCMAKE_TOOLCHAIN_FILE=$PSPDEV/psp/share/pspdev.cmake -DBUILD_PRX=1 ..
psp-cmake -DDUSK_TARGET_SYSTEM=psp -DCMAKE_TOOLCHAIN_FILE=$PSPDEV/psp/share/pspdev.cmake -DBUILD_PRX=1 .. CMAKE_BUILD_TYPE=Release
make -j$(nproc)
# psp-cmake -DDUSK_TARGET_SYSTEM=psp -DCMAKE_TOOLCHAIN_FILE=$PSPDEV/psp/share/pspdev.cmake -DBUILD_PRX=1 -DCMAKE_BUILD_TYPE=Debug ..
# make
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker build -t dusk-dolphin-test -f docker/dolphin-test/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-dolphin-test /bin/bash -c "./scripts/test-gamecube-dolphin.sh"
+45
View File
@@ -0,0 +1,45 @@
#!/bin/bash
set -e
if [ -z "$DEVKITPRO" ]; then
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
exit 1
fi
DOLPHIN_BIN="${DOLPHIN_BIN:-dolphin-emu}"
if ! command -v "$DOLPHIN_BIN" >/dev/null 2>&1; then
echo "$DOLPHIN_BIN not found. Install Dolphin Emulator (e.g. 'apt install dolphin-emu')"
echo "or set DOLPHIN_BIN to its path."
exit 1
fi
if ! command -v xvfb-run >/dev/null 2>&1; then
echo "xvfb-run not found. Install it (e.g. 'apt install xvfb') -- Dolphin's"
echo "Qt frontend needs a display even in batch mode."
exit 1
fi
./scripts/build-gamecube-iso.sh
DUSK_TEST_DOLPHIN_SECONDS="${DUSK_TEST_DOLPHIN_SECONDS:-20}"
ISO="build-gamecube-iso/Dusk-NTSC-U.iso"
echo "Booting $ISO in Dolphin for up to ${DUSK_TEST_DOLPHIN_SECONDS}s (batch mode, headless via Xvfb)..."
# Dolphin's batch mode (-b -e) runs the disc until told to stop -- there's
# no "the game exited cleanly" signal to wait for, so we bound it with
# timeout and treat "still running when the clock ran out" as success.
set +e
xvfb-run -a timeout "${DUSK_TEST_DOLPHIN_SECONDS}" "$DOLPHIN_BIN" -b -e "$ISO"
status=$?
set -e
# timeout returns 124 when it had to kill Dolphin after the duration
# elapsed -- that means the disc booted and kept running, the expected
# smoke-test-passed outcome, not a failure. Any other non-zero status
# means Dolphin crashed or refused to boot the disc.
if [ "$status" -ne 0 ] && [ "$status" -ne 124 ]; then
echo "Dolphin exited with unexpected status $status -- treating as a failure."
exit "$status"
fi
echo "GameCube smoke test passed (Dolphin ran $ISO for ${DUSK_TEST_DOLPHIN_SECONDS}s without crashing)."
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker build -t dusk-psp-test -f docker/psp-test/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-psp-test /bin/bash -c "./scripts/test-psp-ppsspp.sh"
+42
View File
@@ -0,0 +1,42 @@
#!/bin/bash
set -e
if [ -z "$PSPDEV" ]; then
echo "PSPDEV environment variable is not set. Please set it to the path of your PSP development environment."
exit 1
fi
# PPSSPP doesn't ship a standard Linux package -- build its "PPSSPPHeadless"
# target from source (https://github.com/hrydgard/ppsspp) and either put it
# on PATH or point PPSSPP_HEADLESS_BIN at it. See docker/psp-test/Dockerfile
# for a from-scratch build.
PPSSPP_HEADLESS_BIN="${PPSSPP_HEADLESS_BIN:-PPSSPPHeadless}"
if ! command -v "$PPSSPP_HEADLESS_BIN" >/dev/null 2>&1; then
echo "$PPSSPP_HEADLESS_BIN not found. Build PPSSPP's 'PPSSPPHeadless' target"
echo "from source or set PPSSPP_HEADLESS_BIN to its path."
exit 1
fi
./scripts/build-psp.sh
DUSK_TEST_PPSSPP_SECONDS="${DUSK_TEST_PPSSPP_SECONDS:-20}"
EBOOT="build-psp/EBOOT.PBP"
echo "Booting $EBOOT in PPSSPPHeadless (timeout ${DUSK_TEST_PPSSPP_SECONDS}s)..."
# PPSSPPHeadless is purpose-built for automated/CI runs -- it renders
# without a window and is expected to exit on its own once --timeout
# elapses, unlike Dolphin's batch mode which has to be killed externally.
# Check `"$PPSSPP_HEADLESS_BIN" --help` if these flags don't match your
# PPSSPP checkout -- the headless CLI has changed across versions.
set +e
"$PPSSPP_HEADLESS_BIN" --timeout="${DUSK_TEST_PPSSPP_SECONDS}" "$EBOOT"
status=$?
set -e
if [ "$status" -ne 0 ]; then
echo "PPSSPPHeadless exited with status $status"
exit "$status"
fi
echo "PSP smoke test passed (PPSSPPHeadless ran EBOOT.PBP for ${DUSK_TEST_PPSSPP_SECONDS}s without crashing)."
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker build -t dusk-dolphin-test -f docker/dolphin-test/Dockerfile .
docker run --rm -v "$(pwd):/workdir" dusk-dolphin-test /bin/bash -c "./scripts/test-wii-dolphin.sh"
+45
View File
@@ -0,0 +1,45 @@
#!/bin/bash
set -e
if [ -z "$DEVKITPRO" ]; then
echo "DEVKITPRO environment variable is not set. Please set it to the path of your DEVKITPRO installation."
exit 1
fi
DOLPHIN_BIN="${DOLPHIN_BIN:-dolphin-emu}"
if ! command -v "$DOLPHIN_BIN" >/dev/null 2>&1; then
echo "$DOLPHIN_BIN not found. Install Dolphin Emulator (e.g. 'apt install dolphin-emu')"
echo "or set DOLPHIN_BIN to its path."
exit 1
fi
if ! command -v xvfb-run >/dev/null 2>&1; then
echo "xvfb-run not found. Install it (e.g. 'apt install xvfb') -- Dolphin's"
echo "Qt frontend needs a display even in batch mode."
exit 1
fi
./scripts/build-wii-iso.sh
DUSK_TEST_DOLPHIN_SECONDS="${DUSK_TEST_DOLPHIN_SECONDS:-20}"
ISO="build-wii-iso/Dusk-NTSC-U.iso"
echo "Booting $ISO in Dolphin for up to ${DUSK_TEST_DOLPHIN_SECONDS}s (batch mode, headless via Xvfb)..."
# Dolphin's batch mode (-b -e) runs the disc until told to stop -- there's
# no "the game exited cleanly" signal to wait for, so we bound it with
# timeout and treat "still running when the clock ran out" as success.
set +e
xvfb-run -a timeout "${DUSK_TEST_DOLPHIN_SECONDS}" "$DOLPHIN_BIN" -b -e "$ISO"
status=$?
set -e
# timeout returns 124 when it had to kill Dolphin after the duration
# elapsed -- that means the disc booted and kept running, the expected
# smoke-test-passed outcome, not a failure. Any other non-zero status
# means Dolphin crashed or refused to boot the disc.
if [ "$status" -ne 0 ] && [ "$status" -ne 124 ]; then
echo "Dolphin exited with unexpected status $status -- treating as a failure."
exit "$status"
fi
echo "Wii smoke test passed (Dolphin ran $ISO for ${DUSK_TEST_DOLPHIN_SECONDS}s without crashing)."
+4 -5
View File
@@ -4,6 +4,10 @@
# https://opensource.org/licenses/MIT
add_subdirectory(dusk)
if(DUSK_NETWORKING)
add_subdirectory(dusknetwork)
endif()
add_subdirectory(duskrpg)
if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
add_subdirectory(dusklinux)
@@ -15,11 +19,6 @@ elseif(DUSK_TARGET_SYSTEM STREQUAL "psp")
add_subdirectory(dusksdl2)
add_subdirectory(duskgl)
elseif(DUSK_TARGET_SYSTEM STREQUAL "vita")
add_subdirectory(duskvita)
add_subdirectory(dusksdl2)
add_subdirectory(duskgl)
elseif(DUSK_TARGET_SYSTEM STREQUAL "wii" OR DUSK_TARGET_SYSTEM STREQUAL "gamecube")
add_subdirectory(duskdolphin)
+13 -2
View File
@@ -32,6 +32,15 @@ if(NOT yyjson_FOUND)
endif()
endif()
if(NOT jerryscript_FOUND)
find_package(jerryscript REQUIRED)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
jerryscript::core
jerryscript::ext
jerryscript::port
)
endif()
if(DUSK_BACKTRACE)
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
@@ -58,17 +67,19 @@ add_subdirectory(assert)
add_subdirectory(asset)
add_subdirectory(console)
add_subdirectory(display)
add_subdirectory(entity)
add_subdirectory(log)
add_subdirectory(engine)
add_subdirectory(error)
add_subdirectory(game)
add_subdirectory(input)
add_subdirectory(locale)
add_subdirectory(rpg)
add_subdirectory(scene)
add_subdirectory(system)
add_subdirectory(time)
add_subdirectory(ui)
add_subdirectory(network)
add_subdirectory(physics)
add_subdirectory(save)
add_subdirectory(script)
add_subdirectory(util)
add_subdirectory(thread)
+2
View File
@@ -6,5 +6,7 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
easing.c
keyframe.c
keyframeset.c
animation.c
)
+54 -32
View File
@@ -5,48 +5,70 @@
#include "animation.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/math.h"
#include "time/time.h"
void animationInit(
animation_t *anim,
keyframe_t *keyframes,
uint16_t keyframeCount
keyframe_t **tracks,
uint16_t *trackCounts,
uint16_t trackCount
) {
assertNotNull(anim, "Animation pointer cannot be null.");
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
anim->keyframes = keyframes;
anim->keyframeCount = keyframeCount;
keyframeSetInit(
&anim->keyframes, tracks, trackCounts, NULL, NULL, trackCount, NULL
);
anim->time = 0.0f;
anim->speed = 1.0f;
anim->loop = false;
anim->playing = false;
anim->eventTime = 0.0f;
anim->eventCallback = NULL;
anim->eventUser = NULL;
}
float_t animationGetValue(animation_t *anim, const float_t time) {
void animationUpdate(animation_t *anim) {
assertNotNull(anim, "Animation pointer cannot be null.");
assertNotNull(anim->keyframes, "Keyframes pointer cannot be null.");
assertTrue(anim->keyframeCount > 0, "Keyframe count invalid.");
assertTrue(time >= 0, "Time must be non-negative.");
keyframe_t *start;
keyframe_t *end;
keyframe_t *last = anim->keyframes + anim->keyframeCount - 1;
keyframe_t *current = anim->keyframes;
start = current;
if(!anim->playing) return;
do {
if(current->time > time) {
end = current;
break;
}
start = current;
current++;
float_t duration = keyframeSetGetDuration(&anim->keyframes);
float_t prevTime = anim->time;
anim->time += TIME.delta * anim->speed;
if(current > last) {
end = start;
break;
}
} while(true);
// Loops that overshoot duration wrap back into [0, duration) -- an event
// near the end must still be checked across that wrap, as two segments:
// (prevTime, duration] then [0, newTime].
bool_t wrapped = anim->loop && duration > 0.0f && anim->time >= duration;
float_t t = (time - start->time) / (end->time - start->time);
return mathLerp(start->value, end->value, easingApply(start->easing, t));
}
if(anim->loop) {
if(duration > 0.0f) anim->time = mathModFloat(anim->time, duration);
} else if(anim->time >= duration) {
anim->time = duration;
anim->playing = false;
}
if(!anim->eventCallback) return;
bool_t crossed = wrapped
? (prevTime < anim->eventTime || anim->time >= anim->eventTime)
: (prevTime < anim->eventTime && anim->time >= anim->eventTime);
if(crossed) anim->eventCallback(anim, anim->eventUser);
}
void animationSetEvent(
animation_t *anim,
const float_t time,
const animationeventcallback_t callback,
void *user
) {
assertNotNull(anim, "Animation pointer cannot be null.");
anim->eventTime = time;
anim->eventCallback = callback;
anim->eventUser = user;
}
float_t animationGetValue(animation_t *anim, const uint16_t trackIndex) {
assertNotNull(anim, "Animation pointer cannot be null.");
return keyframeSetGetValue(&anim->keyframes, trackIndex, anim->time);
}
+84 -16
View File
@@ -4,31 +4,99 @@
// https://opensource.org/licenses/MIT
#pragma once
#include "keyframe.h"
#include "keyframeset.h"
typedef struct {
keyframe_t *keyframes;
uint16_t keyframeCount;
typedef struct animation_t animation_t;
/**
* Callback fired once when animationUpdate() advances time past
* eventTime (see animationSetEvent()).
*
* @param anim The animation whose event fired.
* @param user The user pointer passed to animationSetEvent().
*/
typedef void (*animationeventcallback_t)(animation_t *anim, void *user);
typedef struct animation_t {
/** The animation's tracks/channels and their raw keyframe data. */
keyframeset_t keyframes;
/** Current playback position, in seconds. */
float_t time;
/** Playback rate multiplier; 1.0 = normal speed. */
float_t speed;
/** True if animationUpdate() should wrap time back to 0 on reaching the
* final keyframe, rather than holding there and clearing playing. */
bool_t loop;
/** True while animationUpdate() should advance time each call. */
bool_t playing;
/** Time (seconds) at which eventCallback fires; see animationSetEvent(). */
float_t eventTime;
/** Callback fired once when time advances past eventTime, or NULL. */
animationeventcallback_t eventCallback;
/** User pointer passed to eventCallback unchanged. */
void *eventUser;
} animation_t;
/**
* Initializes an animation.
*
* Initializes an animation: time 0, speed 1.0, not looping, not playing.
* See keyframeSetInit() -- tracks/trackCounts and the keyframe_t arrays
* they point to are not copied, and must outlive this animation.
*
* @param anim The animation to initialize.
* @param keyframes The keyframes to use for the animation.
* @param keyframeCount The number of keyframes in the animation.
* @param tracks Array of trackCount keyframe_t arrays.
* @param trackCounts Array of trackCount keyframe counts, matching tracks.
* @param trackCount The number of tracks/channels in this animation.
*/
void animationInit(
animation_t *anim,
keyframe_t *keyframes,
uint16_t keyframeCount
keyframe_t **tracks,
uint16_t *trackCounts,
uint16_t trackCount
);
/**
* Gets the value of the animation at a given time.
*
* @param anim The animation to get the value from.
* @param time The time at which to get the value, in seconds.
* @return The value of the animation at the given time.
* Advances an animation's time by TIME.delta * speed. No-op if not
* playing. Duration is the latest of every track's final keyframe time
* (see keyframeSetGetDuration()). If loop is set, time wraps back into
* [0, duration) on reaching it; otherwise time is clamped there and
* playing is cleared.
*
* If eventCallback is set, it fires once when this call advances time
* from at or before eventTime to after it (checked across the loop wrap
* point too, so an event near the end of a looping animation still fires
* every loop).
*
* @param anim The animation to update.
*/
float_t animationGetValue(animation_t *anim, const float_t time);
void animationUpdate(animation_t *anim);
/**
* Sets (or clears, with callback NULL) the single time-triggered event
* fired by animationUpdate().
*
* @param anim The animation to set the event on.
* @param time The time, in seconds, at which callback fires.
* @param callback The callback to invoke, or NULL to clear any event.
* @param user Arbitrary pointer forwarded to callback unchanged.
*/
void animationSetEvent(
animation_t *anim,
const float_t time,
const animationeventcallback_t callback,
void *user
);
/**
* Gets the value of one of the animation's tracks at its current
* playback time.
*
* @param anim The animation to get the value from.
* @param trackIndex The track to evaluate, in [0, trackCount).
* @return The interpolated value of that track at the current time.
*/
float_t animationGetValue(animation_t *anim, const uint16_t trackIndex);
+43
View File
@@ -0,0 +1,43 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include "keyframe.h"
#include "assert/assert.h"
#include "util/math.h"
float_t keyframeGetValue(
keyframe_t *keyframes,
const uint16_t keyframeCount,
const float_t time
) {
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
assertTrue(time >= 0, "Time must be non-negative.");
keyframe_t *first = keyframes;
keyframe_t *last = keyframes + keyframeCount - 1;
// Clamp to the boundary keyframes' values directly rather than
// interpolating -- start == end at either boundary would otherwise
// divide by zero.
if(time <= first->time) return first->value;
if(time >= last->time) return last->value;
keyframe_t *start = first;
keyframe_t *end;
keyframe_t *current = first;
do {
if(current->time > time) {
end = current;
break;
}
start = current;
current++;
} while(true);
float_t t = (time - start->time) / (end->time - start->time);
return mathLerp(start->value, end->value, easingApply(start->easing, t));
}
+15 -1
View File
@@ -10,4 +10,18 @@ typedef struct {
float_t time;
float_t value;
easingtype_t easing;
} keyframe_t;
} keyframe_t;
/**
* Gets the eased, interpolated value of a keyframe array at a given time.
*
* @param keyframes The keyframes to evaluate, ascending by time.
* @param keyframeCount The number of keyframes.
* @param time The time at which to get the value, in seconds.
* @return The interpolated value at the given time.
*/
float_t keyframeGetValue(
keyframe_t *keyframes,
const uint16_t keyframeCount,
const float_t time
);
+76
View File
@@ -0,0 +1,76 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include "keyframeset.h"
#include "assert/assert.h"
void keyframeSetInit(
keyframeset_t *set,
keyframe_t **tracks,
uint16_t *trackCounts,
keyframesetcallback_t *callbacks,
void **users,
uint16_t trackCount,
void *user
) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertNotNull(tracks, "Tracks pointer cannot be null.");
assertNotNull(trackCounts, "Track counts pointer cannot be null.");
assertTrue(trackCount > 0, "Track count must be more than 0.");
set->tracks = tracks;
set->trackCounts = trackCounts;
set->trackCount = trackCount;
set->callbacks = callbacks;
set->users = users;
set->user = user;
}
float_t keyframeSetGetValue(
keyframeset_t *set,
const uint16_t trackIndex,
const float_t time
) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertTrue(trackIndex < set->trackCount, "Track index out of bounds.");
return keyframeGetValue(
set->tracks[trackIndex], set->trackCounts[trackIndex], time
);
}
void keyframeSetGetValues(
keyframeset_t *set,
const float_t time,
float_t *outValues
) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertNotNull(outValues, "Output values pointer cannot be null.");
for(uint16_t i = 0; i < set->trackCount; i++) {
outValues[i] = keyframeGetValue(set->tracks[i], set->trackCounts[i], time);
}
}
float_t keyframeSetGetDuration(keyframeset_t *set) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
float_t duration = 0.0f;
for(uint16_t i = 0; i < set->trackCount; i++) {
float_t trackDuration = set->tracks[i][set->trackCounts[i] - 1].time;
if(trackDuration > duration) duration = trackDuration;
}
return duration;
}
void keyframeSetFireCallback(keyframeset_t *set, const uint16_t trackIndex) {
assertNotNull(set, "Keyframe set pointer cannot be null.");
assertTrue(trackIndex < set->trackCount, "Track index out of bounds.");
if(!set->callbacks || !set->callbacks[trackIndex]) return;
set->callbacks[trackIndex](
set, trackIndex, set->users ? set->users[trackIndex] : NULL
);
}
+116
View File
@@ -0,0 +1,116 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#pragma once
#include "keyframe.h"
typedef struct keyframeset_t keyframeset_t;
/**
* Callback associated with one track of a keyframe set (see
* keyframeSetFireCallback()).
*
* @param set The keyframe set the track belongs to.
* @param trackIndex The track this callback is registered for.
* @param user The per-track user pointer passed to keyframeSetInit().
*/
typedef void (*keyframesetcallback_t)(
keyframeset_t *set,
const uint16_t trackIndex,
void *user
);
/**
* A group of N parallel keyframe tracks (e.g. one per animated channel --
* position.x/y/z, bone rotations, etc.) sharing a single timeline. Each
* track is independent: its own keyframe array and count, evaluated at
* whatever time is asked for.
*/
typedef struct keyframeset_t {
/** Caller-owned array of trackCount keyframe_t arrays. */
keyframe_t **tracks;
/** Caller-owned array of trackCount counts, one per entry in tracks. */
uint16_t *trackCounts;
uint16_t trackCount;
/** Caller-owned array of trackCount callbacks, one per track. Entries
* (or the whole array) may be NULL for tracks with no callback. */
keyframesetcallback_t *callbacks;
/** Caller-owned array of trackCount user pointers, one per track,
* passed to that track's callbacks[] entry. May be NULL. */
void **users;
/** Extra user data for the set as a whole, not tied to any one track. */
void *user;
} keyframeset_t;
/**
* Initializes a keyframe set. None of the passed-in arrays (or the
* keyframe_t arrays tracks points to) are copied -- they must outlive
* this keyframeset_t.
*
* @param set The keyframe set to initialize.
* @param tracks Array of trackCount keyframe_t arrays.
* @param trackCounts Array of trackCount keyframe counts, matching tracks.
* @param callbacks Array of trackCount callbacks, one per track, or NULL
* if no track has one.
* @param users Array of trackCount user pointers, matching callbacks, or
* NULL.
* @param trackCount The number of tracks.
* @param user Extra user data for the set as a whole; may be NULL.
*/
void keyframeSetInit(
keyframeset_t *set,
keyframe_t **tracks,
uint16_t *trackCounts,
keyframesetcallback_t *callbacks,
void **users,
uint16_t trackCount,
void *user
);
/**
* Gets the value of a single track at a given time.
*
* @param set The keyframe set to evaluate.
* @param trackIndex The track to evaluate, in [0, set->trackCount).
* @param time The time at which to get the value, in seconds.
* @return The interpolated value of that track at the given time.
*/
float_t keyframeSetGetValue(
keyframeset_t *set,
const uint16_t trackIndex,
const float_t time
);
/**
* Gets the value of every track at a given time.
*
* @param set The keyframe set to evaluate.
* @param time The time at which to get the values, in seconds.
* @param outValues Destination array of at least set->trackCount floats.
*/
void keyframeSetGetValues(
keyframeset_t *set,
const float_t time,
float_t *outValues
);
/**
* Gets the set's duration: the latest final-keyframe time across every
* track, i.e. how long it takes for every track to finish.
*
* @param set The keyframe set to measure.
* @return The set's duration, in seconds.
*/
float_t keyframeSetGetDuration(keyframeset_t *set);
/**
* Invokes a track's callback, if it (and its callbacks array) is set.
* No-op otherwise.
*
* @param set The keyframe set the track belongs to.
* @param trackIndex The track whose callback to invoke.
*/
void keyframeSetFireCallback(keyframeset_t *set, const uint16_t trackIndex);
+7
View File
@@ -8,6 +8,13 @@
#pragma once
#include "dusk.h"
// Release-style CMake configs (Release, RelWithDebInfo, MinSizeRel) define
// NDEBUG automatically; fake assertions there rather than requiring every
// platform's CMakeLists to set DUSK_ASSERTIONS_FAKED itself.
#if defined(NDEBUG) && !defined(DUSK_ASSERTIONS_FAKED)
#define DUSK_ASSERTIONS_FAKED
#endif
#ifdef DUSK_TEST_ASSERT
#include <cmocka.h>
+51 -48
View File
@@ -59,20 +59,28 @@ assetentry_t * assetGetEntry(
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
// We did not find one existing, Find first available slot.
entry = ASSET.entries;
do {
if(entry->type != ASSET_LOADER_TYPE_NULL) {
entry++;
continue;
}
// We did not find one existing. Find first available slot, reaping
// zero-ref entries to make room if none are immediately available.
bool_t reaped = false;
for(;;) {
entry = ASSET.entries;
do {
if(entry->type != ASSET_LOADER_TYPE_NULL) {
entry++;
continue;
}
if(entry->state == ASSET_ENTRY_STATE_NOT_STARTED) {
assetEntryInit(entry, name, type, input);
return entry;
}
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
if(entry->state == ASSET_ENTRY_STATE_NOT_STARTED) {
assetEntryInit(entry, name, type, input);
return entry;
}
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
if(reaped) break;
reaped = true;
errorCatch(assetReapUnused());
}
assertUnreachable("No available asset entry slots.");
return NULL;
@@ -191,6 +199,32 @@ void assetUnlockEntry(assetentry_t *entry) {
assetEntryUnlock(entry);
}
errorret_t assetReapUnused(void) {
assertIsMainThread("assetReapUnused must be called from the main thread.");
// Repeatedly find and dispose zero-ref LOADED entries until none remain.
// This handles dependency chains where an entry (e.g. a model) holds refs
// on child entries (mesh, texture): dispose parents first so child ref
// counts drop to zero, then pick up the children on the next pass. Without
// this, a forward-only scan fails when a shared child entry appears before
// a parent that still holds a ref to it.
bool_t any;
do {
any = false;
assetentry_t *entry = ASSET.entries;
do {
if(entry->type == ASSET_LOADER_TYPE_NULL) { entry++; continue; }
if(entry->state != ASSET_ENTRY_STATE_LOADED) { entry++; continue; }
if(entry->refs.count > 0) { entry++; continue; }
errorChain(assetEntryDispose(entry));
any = true;
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
} while(any);
errorOk();
}
errorret_t assetUpdate(void) {
assertIsMainThread("assetUpdate must be called from the main thread.");
@@ -286,7 +320,9 @@ errorret_t assetUpdate(void) {
"Loader did not set entry state to error on failed load."
);
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
eventInvoke(&loading->entry->onLoaded, loading->entry);
assetentry_t *loadedEntry = loading->entry;
loading->entry = NULL;
eventInvoke(&loadedEntry->onLoaded, loadedEntry);
}
loading++;
@@ -322,30 +358,6 @@ errorret_t assetUpdate(void) {
}
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
// Reap unused entries.
entry = ASSET.entries;
do {
if(entry->state != ASSET_ENTRY_STATE_LOADED) {
entry++;
continue;
}
if(entry->type == ASSET_LOADER_TYPE_NULL) {
entry++;
continue;
}
if(entry->refs.count > 0) {
entry++;
continue;
}
consolePrint("Reaping asset %s", entry->name);
errorChain(assetEntryDispose(entry));
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
errorOk();
}
@@ -411,16 +423,7 @@ errorret_t assetDispose(void) {
assertIsMainThread("Must be called from the main thread.");
threadStop(&ASSET.loadThread);
// Dispose every non-null entry so type-specific dispose callbacks
// (e.g. assetScriptDispose freeing jerry values) run before the
// scripting engine is torn down.
assetentry_t *entry = ASSET.entries;
do {
if(entry->type != ASSET_LOADER_TYPE_NULL) {
errorChain(assetEntryDispose(entry));
}
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
errorChain(assetReapUnused());
// Cleanup zip file.
if(ASSET.zip != NULL) {
+12 -2
View File
@@ -23,8 +23,8 @@
#define ASSET_FILE_NAME "dusk.dsk"
#define ASSET_HEADER_SIZE 3
#define ASSET_LOADING_COUNT_MAX 4
#define ASSET_ENTRY_COUNT_MAX 128
#define ASSET_LOADING_COUNT_MAX 10
#define ASSET_ENTRY_COUNT_MAX 64
typedef struct asset_s {
zip_t *zip;
@@ -112,6 +112,16 @@ void assetUnlock(const char_t *name);
*/
void assetUnlockEntry(assetentry_t *entry);
/**
* Frees every currently unreferenced (zero-ref) loaded asset entry. Repeats
* until a full pass frees nothing further, since disposing a parent entry
* (e.g. a model) may drop a child entry's (e.g. a mesh) ref count to zero,
* making it eligible for reaping too.
*
* @return An error code if any entry could not be disposed properly.
*/
errorret_t assetReapUnused(void);
/**
* Requires an asset entry to be loaded. This will block until the asset entry
* is fully loaded.
+2 -2
View File
@@ -128,8 +128,8 @@ void assetBatchDispose(assetbatch_t *batch) {
for(uint16_t i = 0; i < batch->count; i++) {
if(batch->entries[i]) {
// Unsubscribe while we still hold a lock so the entry is live.
eventUnsubscribe(&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb);
eventUnsubscribe(&batch->entries[i]->onError, assetBatchEntryOnErrorCb);
eventUnsubscribe(&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb, batch);
eventUnsubscribe(&batch->entries[i]->onError, assetBatchEntryOnErrorCb, batch);
assetUnlockEntry(batch->entries[i]);
}
}
+2 -1
View File
@@ -79,8 +79,9 @@ errorret_t assetFileRead(
uint8_t tempBuffer[256];
while(bytesRemaining > 0) {
size_t chunkSize = mathMin(bytesRemaining, sizeof(tempBuffer));
// The recursive call below already advances file->position (real
// read branch does that itself) -- don't double-count it here.
errorChain(assetFileRead(file, tempBuffer, chunkSize));
file->position += chunkSize;
bytesRemaining -= chunkSize;
}
file->lastRead = bufferSize;
+3 -1
View File
@@ -14,4 +14,6 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
# Subdirs
add_subdirectory(display)
add_subdirectory(locale)
add_subdirectory(json)
add_subdirectory(json)
add_subdirectory(dmf)
add_subdirectory(animation)
@@ -0,0 +1,9 @@
# 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
assetanimationloader.c
)
@@ -0,0 +1,234 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetanimationloader.h"
#include "util/memory.h"
#include "util/string.h"
#include "assert/assert.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
errorret_t assetAnimationLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(
loading->loading.animation.state != ASSET_ANIMATION_LOADING_STATE_READ_FILE
) {
errorOk();
}
assertNull(loading->loading.animation.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.animation.file;
assetLoaderErrorChain(
loading, assetFileInit(file, loading->entry->name, NULL, NULL)
);
if(file->size > ASSET_ANIMATION_FILE_SIZE_MAX) {
assetLoaderErrorThrow(
loading, "Animation JSON exceeds maximum allowed size"
);
}
uint8_t *buffer;
size_t size;
assetLoaderErrorChain(loading, assetFileReadEntire(file, &buffer, &size));
assetLoaderErrorChain(loading, assetFileDispose(file));
loading->loading.animation.buffer = buffer;
loading->loading.animation.size = size;
loading->loading.animation.state = ASSET_ANIMATION_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetAnimationLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_ANIMATION, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.animation.state) {
case ASSET_ANIMATION_LOADING_STATE_INITIAL:
loading->loading.animation.state =
ASSET_ANIMATION_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
break;
case ASSET_ANIMATION_LOADING_STATE_PARSE:
break;
default:
errorOk();
}
uint8_t *buffer = loading->loading.animation.buffer;
assertNotNull(buffer, "Animation buffer should have been loaded by now.");
yyjson_doc *doc = yyjson_read(
(char *)buffer,
loading->loading.animation.size,
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
);
memoryFree(buffer);
loading->loading.animation.buffer = NULL;
if(!doc) assetLoaderErrorThrow(loading, "Failed to parse animation JSON");
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *channelsVal = yyjson_obj_get(root, "channels");
if(!channelsVal || !yyjson_is_arr(channelsVal)) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(loading, "Animation JSON missing 'channels' array");
}
uint16_t channelCount = (uint16_t)yyjson_arr_size(channelsVal);
if(channelCount == 0) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(loading, "Animation must have at least one channel");
}
keyframe_t **tracks = memoryAllocate(channelCount * sizeof(keyframe_t *));
uint16_t *trackCounts = memoryAllocate(channelCount * sizeof(uint16_t));
size_t idx, max;
yyjson_val *channelJson;
uint16_t parsed = 0;
yyjson_arr_foreach(channelsVal, idx, max, channelJson) {
keyframe_t *keyframes;
uint16_t count;
errorret_t ret =
assetAnimationParseChannel(channelJson, &keyframes, &count);
if(errorIsNotOk(ret)) {
assetAnimationFreeChannels(tracks, parsed);
memoryFree(trackCounts);
yyjson_doc_free(doc);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorChain(ret);
}
tracks[idx] = keyframes;
trackCounts[idx] = count;
parsed++;
}
animationInit(
&loading->entry->data.animation, tracks, trackCounts, channelCount
);
yyjson_val *loopVal = yyjson_obj_get(root, "loop");
if(loopVal) loading->entry->data.animation.loop = yyjson_get_bool(loopVal);
yyjson_val *speedVal = yyjson_obj_get(root, "speed");
if(speedVal) {
loading->entry->data.animation.speed = (float_t)yyjson_get_num(speedVal);
}
yyjson_doc_free(doc);
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetAnimationDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_ANIMATION, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
// A load that failed before animationInit() ran (e.g. a parse error)
// never populated these -- nothing to free in that case.
keyframeset_t *set = &entry->data.animation.keyframes;
if(set->tracks) {
assetAnimationFreeChannels(set->tracks, set->trackCount);
memoryFree(set->trackCounts);
set->tracks = NULL;
set->trackCounts = NULL;
set->trackCount = 0;
}
errorOk();
}
errorret_t assetAnimationParseEasing(
const char_t *name,
easingtype_t *outEasing
) {
if(stringEquals(name, "LINEAR")) *outEasing = EASING_LINEAR;
else if(stringEquals(name, "IN_SINE")) *outEasing = EASING_IN_SINE;
else if(stringEquals(name, "OUT_SINE")) *outEasing = EASING_OUT_SINE;
else if(stringEquals(name, "IN_OUT_SINE")) *outEasing = EASING_IN_OUT_SINE;
else if(stringEquals(name, "IN_QUAD")) *outEasing = EASING_IN_QUAD;
else if(stringEquals(name, "OUT_QUAD")) *outEasing = EASING_OUT_QUAD;
else if(stringEquals(name, "IN_OUT_QUAD")) *outEasing = EASING_IN_OUT_QUAD;
else if(stringEquals(name, "IN_CUBIC")) *outEasing = EASING_IN_CUBIC;
else if(stringEquals(name, "OUT_CUBIC")) *outEasing = EASING_OUT_CUBIC;
else if(stringEquals(name, "IN_OUT_CUBIC")) *outEasing = EASING_IN_OUT_CUBIC;
else if(stringEquals(name, "IN_QUART")) *outEasing = EASING_IN_QUART;
else if(stringEquals(name, "OUT_QUART")) *outEasing = EASING_OUT_QUART;
else if(stringEquals(name, "IN_OUT_QUART")) *outEasing = EASING_IN_OUT_QUART;
else if(stringEquals(name, "IN_BACK")) *outEasing = EASING_IN_BACK;
else if(stringEquals(name, "OUT_BACK")) *outEasing = EASING_OUT_BACK;
else if(stringEquals(name, "IN_OUT_BACK")) *outEasing = EASING_IN_OUT_BACK;
else errorThrow("Unknown easing type '%s'", name);
errorOk();
}
errorret_t assetAnimationParseChannel(
yyjson_val *channelJson,
keyframe_t **outKeyframes,
uint16_t *outCount
) {
if(!yyjson_is_arr(channelJson)) {
errorThrow("Animation channel must be an array");
}
size_t count = yyjson_arr_size(channelJson);
if(count == 0) {
errorThrow("Animation channel must have at least one keyframe");
}
keyframe_t *keyframes = memoryAllocate(count * sizeof(keyframe_t));
size_t idx, max;
yyjson_val *keyframeJson;
yyjson_arr_foreach(channelJson, idx, max, keyframeJson) {
yyjson_val *timeVal = yyjson_obj_get(keyframeJson, "time");
yyjson_val *valueVal = yyjson_obj_get(keyframeJson, "value");
if(!timeVal || !valueVal) {
memoryFree(keyframes);
errorThrow("Animation keyframe missing 'time' or 'value'");
}
keyframes[idx].time = (float_t)yyjson_get_num(timeVal);
keyframes[idx].value = (float_t)yyjson_get_num(valueVal);
yyjson_val *easingVal = yyjson_obj_get(keyframeJson, "easing");
if(!easingVal) {
keyframes[idx].easing = EASING_LINEAR;
continue;
}
errorret_t ret = assetAnimationParseEasing(
yyjson_get_str(easingVal), &keyframes[idx].easing
);
if(errorIsNotOk(ret)) {
memoryFree(keyframes);
errorChain(ret);
}
}
*outKeyframes = keyframes;
*outCount = (uint16_t)count;
errorOk();
}
void assetAnimationFreeChannels(keyframe_t **tracks, const uint16_t count) {
for(uint16_t i = 0; i < count; i++) memoryFree(tracks[i]);
memoryFree(tracks);
}
@@ -0,0 +1,101 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "asset/assetfile.h"
#include "animation/animation.h"
#include "yyjson.h"
#define ASSET_ANIMATION_FILE_SIZE_MAX 1024*256
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
/**
* JSON animation file format:
* {
* "loop": false,
* "speed": 1.0,
* "channels": [
* [
* { "time": 0.0, "value": 0.0, "easing": "LINEAR" },
* { "time": 1.0, "value": 10.0 }
* ]
* ]
* }
*
* "loop" and "speed" are optional, defaulting to false and 1.0 (see
* animationInit()). "channels" is required and must have at least one
* entry; each entry is itself a non-empty array of keyframes, ascending
* by "time", sharing one timeline with every other channel (see
* keyframeset_t). Each keyframe requires "time" and "value"; "easing" is
* optional and defaults to "LINEAR" (see easingtype_t for the full set of
* names, e.g. "IN_QUAD", "OUT_BACK", "IN_OUT_CUBIC").
*/
typedef enum {
ASSET_ANIMATION_LOADING_STATE_INITIAL,
ASSET_ANIMATION_LOADING_STATE_READ_FILE,
ASSET_ANIMATION_LOADING_STATE_PARSE,
ASSET_ANIMATION_LOADING_STATE_DONE
} assetanimationloadingstate_t;
typedef struct {
assetfile_t file;
assetanimationloadingstate_t state;
uint8_t *buffer;
size_t size;
} assetanimationloaderloading_t;
typedef animation_t assetanimationoutput_t;
errorret_t assetAnimationLoaderAsync(assetloading_t *loading);
errorret_t assetAnimationLoaderSync(assetloading_t *loading);
errorret_t assetAnimationDispose(assetentry_t *entry);
/**
* Internal. Maps a JSON easing name (e.g. "IN_OUT_QUAD") to its
* easingtype_t.
*
* @param name The easing name to parse.
* @param outEasing Destination for the parsed easing type.
* @return Error state; fails if name doesn't match any easingtype_t.
*/
errorret_t assetAnimationParseEasing(
const char_t *name,
easingtype_t *outEasing
);
/**
* Internal. Parses one "channels" array entry into a heap-allocated
* keyframe_t array (memoryAllocate) -- freed later by
* assetAnimationFreeChannels() (on a parse failure) or
* assetAnimationDispose() (once loaded).
*
* @param channelJson The channel's JSON array of keyframe objects.
* @param outKeyframes Destination for the newly allocated keyframe array.
* @param outCount Destination for the number of keyframes parsed.
* @return Error state.
*/
errorret_t assetAnimationParseChannel(
yyjson_val *channelJson,
keyframe_t **outKeyframes,
uint16_t *outCount
);
/**
* Internal. Frees the first count entries of tracks (each a
* memoryAllocate'd keyframe_t array from assetAnimationParseChannel()),
* then frees tracks itself. Used both to unwind a partially-parsed
* channel list on failure and to free a fully-loaded animation's
* channels in assetAnimationDispose().
*
* @param tracks The channel array to free.
* @param count The number of entries in tracks to free.
*/
void assetAnimationFreeChannels(keyframe_t **tracks, const uint16_t count);
+12
View File
@@ -16,6 +16,12 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
.dispose = assetMeshDispose
},
[ASSET_LOADER_TYPE_MODEL] = {
.loadSync = assetModelLoaderSync,
.loadAsync = assetModelLoaderAsync,
.dispose = assetModelDispose
},
[ASSET_LOADER_TYPE_TEXTURE] = {
.loadSync = assetTextureLoaderSync,
.loadAsync = assetTextureLoaderAsync,
@@ -39,4 +45,10 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
.loadAsync = assetJsonLoaderAsync,
.dispose = assetJsonDispose
},
[ASSET_LOADER_TYPE_ANIMATION] = {
.loadSync = assetAnimationLoaderSync,
.loadAsync = assetAnimationLoaderAsync,
.dispose = assetAnimationDispose
},
};
+28 -21
View File
@@ -1,53 +1,60 @@
/**
* Copyright (c) 2026 Dominic Masters
*
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/loader/display/assetmeshloader.h"
#include "asset/loader/dmf/assetmeshloader.h"
#include "asset/loader/dmf/assetmodelloader.h"
#include "asset/loader/display/assettextureloader.h"
#include "asset/loader/display/assettilesetloader.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "asset/loader/json/assetjsonloader.h"
#include "asset/loader/animation/assetanimationloader.h"
typedef enum {
ASSET_LOADER_TYPE_NULL,
ASSET_LOADER_TYPE_MESH,
ASSET_LOADER_TYPE_MODEL,
ASSET_LOADER_TYPE_TEXTURE,
ASSET_LOADER_TYPE_TILESET,
ASSET_LOADER_TYPE_LOCALE,
ASSET_LOADER_TYPE_JSON,
ASSET_LOADER_TYPE_ANIMATION,
ASSET_LOADER_TYPE_COUNT
} assetloadertype_t;
typedef union {
assetmeshloaderinput_t mesh;
assetmeshloaderloading_t mesh;
assetmodelloaderloading_t model;
assettextureloaderloading_t texture;
assettilesetloaderloading_t tileset;
assetlocaleloaderloading_t locale;
assetjsonloaderloading_t json;
assetanimationloaderloading_t animation;
} assetloaderloading_t;
typedef union {
assetmeshoutput_t mesh;
assetmodeloutput_t model;
assettextureoutput_t texture;
assettilesetoutput_t tileset;
assetlocaleoutput_t locale;
assetjsonoutput_t json;
assetanimationoutput_t animation;
} assetloaderoutput_t;
typedef union {
assettextureloaderinput_t texture;
assettilesetloaderinput_t tileset;
assetlocaleloaderinput_t locale;
assetjsonloaderinput_t json;
} assetloaderinput_t;
typedef union {
assetmeshloaderloading_t mesh;
assettextureloaderloading_t texture;
assettilesetloaderloading_t tileset;
assetlocaleloaderloading_t locale;
assetjsonloaderloading_t json;
} assetloaderloading_t;
typedef union {
assetmeshoutput_t mesh;
assettextureoutput_t texture;
assettilesetoutput_t tileset;
assetlocaleoutput_t locale;
assetjsonoutput_t json;
} assetloaderoutput_t;
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
@@ -66,7 +73,7 @@ extern assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT];
/**
* Shorthand method to both chain an error (against the loader state) and to
* set the asset entry state to error.
*
*
* @param loading The asset loading slot.
* @param ret The error return value to check and chain if it's an error.
*/
@@ -81,7 +88,7 @@ extern assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT];
/**
* Shorthand method to both throw an error (against the loader state) and to
* set the asset entry state to error.
*
*
* @param loading The asset loading slot.
* @param ... Format string and arguments for the error message.
*/
@@ -6,7 +6,6 @@
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
assetmeshloader.c
assettextureloader.c
assettilesetloader.c
)
@@ -1,180 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetmeshloader.h"
#include "assert/assert.h"
#include "util/endian.h"
#include "util/memory.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
if(loading->loading.mesh.state != ASSET_MESH_LOADING_STATE_READ_FILE) {
errorOk();
}
assetmeshoutput_t *out = &loading->entry->data.mesh;
assetfile_t *file = &loading->loading.mesh.file;
assetmeshinputaxis_t axis = loading->entry->inputData.mesh;
assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
assetLoaderErrorChain(loading, assetFileOpen(file));
// Skip the 80-byte STL header.
assetLoaderErrorChain(loading, assetFileRead(file, NULL, 80));
if(file->lastRead != 80) {
assetLoaderErrorThrow(loading, "Failed to skip STL header.");
}
uint32_t triangleCount;
assetLoaderErrorChain(loading,
assetFileRead(file, &triangleCount, sizeof(uint32_t))
);
if(file->lastRead != sizeof(uint32_t)) {
assetLoaderErrorThrow(loading, "Failed to read tri count");
}
triangleCount = endianLittleToHost32(triangleCount);
out->vertices = memoryAllocate(sizeof(meshvertex_t) * triangleCount * 3);
meshvertex_t *verts = out->vertices;
errorret_t ret;
for(uint32_t i = 0; i < triangleCount; i++) {
assetmeshstltriangle_t triData;
ret = assetFileRead(file, &triData, sizeof(triData));
if(errorIsNotOk(ret)) {
memoryFree(verts);
out->vertices = NULL;
assetLoaderErrorChain(loading, ret);
}
if(file->lastRead != sizeof(triData)) {
memoryFree(verts);
out->vertices = NULL;
assetLoaderErrorThrow(loading, "Failed to read triangle data");
}
for(uint8_t j = 0; j < 3; j++) {
#if MESH_ENABLE_COLOR
verts[i * 3 + j].color.r = (
(uint8_t)(endianLittleToHostFloat(triData.normal[0]) * 255.0f)
);
verts[i * 3 + j].color.g = (
(uint8_t)(endianLittleToHostFloat(triData.normal[1]) * 255.0f)
);
verts[i * 3 + j].color.b = (
(uint8_t)(endianLittleToHostFloat(triData.normal[2]) * 255.0f)
);
verts[i * 3 + j].color.a = 0xFF;
#endif
verts[i * 3 + j].uv[0] = 0.0f;
verts[i * 3 + j].uv[1] = 0.0f;
for(uint8_t k = 0; k < 3; k++) {
verts[i * 3 + j].pos[k] = endianLittleToHostFloat(
triData.positions[j][k]
);
}
switch(axis) {
case MESH_INPUT_AXIS_Z_UP: {
float_t temp = verts[i * 3 + j].pos[1];
verts[i * 3 + j].pos[1] = verts[i * 3 + j].pos[2];
verts[i * 3 + j].pos[2] = temp;
break;
}
case MESH_INPUT_AXIS_X_UP: {
float_t temp = verts[i * 3 + j].pos[0];
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
verts[i * 3 + j].pos[1] = temp;
break;
}
case MESH_INPUT_AXIS_Y_DOWN:
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[1];
break;
case MESH_INPUT_AXIS_Z_DOWN: {
float_t temp = verts[i * 3 + j].pos[1];
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[2];
verts[i * 3 + j].pos[2] = temp;
break;
}
case MESH_INPUT_AXIS_X_DOWN: {
float_t temp = verts[i * 3 + j].pos[0];
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
verts[i * 3 + j].pos[1] = -temp;
break;
}
case MESH_INPUT_AXIS_Y_UP:
default:
break;
}
}
}
ret = assetFileClose(file);
if(errorIsNotOk(ret)) {
memoryFree(verts);
out->vertices = NULL;
assetLoaderErrorChain(loading, ret);
}
assetFileDispose(file);
loading->loading.mesh.triangleCount = triangleCount;
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_CREATE_MESH;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetMeshLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
switch(loading->loading.mesh.state) {
case ASSET_MESH_LOADING_STATE_INITIAL:
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
break;
case ASSET_MESH_LOADING_STATE_CREATE_MESH:
break;
default:
errorOk();
}
assetmeshoutput_t *out = &loading->entry->data.mesh;
assertNotNull(out->vertices, "Mesh vertices should have been loaded by now.");
errorret_t ret = meshInit(
&out->mesh,
MESH_PRIMITIVE_TYPE_TRIANGLES,
loading->loading.mesh.triangleCount * 3,
out->vertices
);
if(errorIsNotOk(ret)) {
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
memoryFree(out->vertices);
out->vertices = NULL;
assetLoaderErrorChain(loading, ret);
}
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetMeshDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
errorChain(meshDispose(&entry->data.mesh.mesh));
memoryFree(entry->data.mesh.vertices);
errorOk();
}
@@ -1,58 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/assetfile.h"
#include "display/mesh/mesh.h"
#include "assert/assert.h"
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
typedef enum {
MESH_INPUT_AXIS_Y_UP,
MESH_INPUT_AXIS_Z_UP,
MESH_INPUT_AXIS_X_UP,
MESH_INPUT_AXIS_Y_DOWN,
MESH_INPUT_AXIS_Z_DOWN,
MESH_INPUT_AXIS_X_DOWN,
} assetmeshinputaxis_t;
typedef assetmeshinputaxis_t assetmeshloaderinput_t;
typedef enum {
ASSET_MESH_LOADING_STATE_INITIAL,
ASSET_MESH_LOADING_STATE_READ_FILE,
ASSET_MESH_LOADING_STATE_CREATE_MESH,
ASSET_MESH_LOADING_STATE_DONE
} assetmeshloadingstate_t;
typedef struct {
assetfile_t file;
assetmeshloadingstate_t state;
uint32_t triangleCount;
} assetmeshloaderloading_t;
typedef struct {
mesh_t mesh;
meshvertex_t *vertices;
} assetmeshoutput_t;
#pragma pack(push, 1)
typedef struct {
vec3 normal;
float_t positions[3][3];
uint16_t attributeByteCount;
} assetmeshstltriangle_t;
#pragma pack(pop)
assertStructSize(assetmeshstltriangle_t, 50);
errorret_t assetMeshLoaderAsync(assetloading_t *loading);
errorret_t assetMeshLoaderSync(assetloading_t *loading);
errorret_t assetMeshDispose(assetentry_t *entry);
+10
View File
@@ -0,0 +1,10 @@
# 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
assetmeshloader.c
assetmodelloader.c
)
+149
View File
@@ -0,0 +1,149 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetmeshloader.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/endian.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread.");
if(loading->loading.mesh.state != ASSET_MESH_LOADING_STATE_READ_FILE) {
errorOk();
}
assertNull(loading->loading.mesh.data, "Data already defined?");
assetfile_t *file = &loading->loading.mesh.file;
assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *raw = memoryAllocate(file->size);
assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, raw, file->size));
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
assertTrue(file->lastRead == file->size, "Failed to read entire DMF file.");
if(raw[0] != 'D' || raw[1] != 'M' || raw[2] != 'F') {
memoryFree(raw);
assetLoaderErrorThrow(loading, "Invalid DMF file header");
}
uint32_t version = endianLittleToHost32(*(uint32_t *)(raw + 4));
if(version != ASSET_MESH_FILE_VERSION) {
memoryFree(raw);
assetLoaderErrorThrow(loading, "Unsupported DMF version %u", version);
}
uint32_t vertCount = endianLittleToHost32(*(uint32_t *)(raw + 8));
meshvertex_t *vertices = NULL;
if(vertCount > 0) {
// 32-byte (cache-line) aligned: GX_SetArray + DCFlushRange on Dolphin
// require this for the DMA'd vertex data to actually reach the GPU
// coherently. Static compiled-in vertex arrays happen to get this from
// the linker; a plain memoryAllocate here would not.
vertices = memoryAlign(32, vertCount * sizeof(meshvertex_t));
memoryCopy(vertices, raw + 12, vertCount * sizeof(meshvertex_t));
for(uint32_t v = 0; v < vertCount; v++) {
vertices[v].uv[0] = endianLittleToHostFloat(vertices[v].uv[0]);
vertices[v].uv[1] = endianLittleToHostFloat(vertices[v].uv[1]);
vertices[v].pos[0] = endianLittleToHostFloat(vertices[v].pos[0]);
vertices[v].pos[1] = endianLittleToHostFloat(vertices[v].pos[1]);
vertices[v].pos[2] = endianLittleToHostFloat(vertices[v].pos[2]);
}
}
memoryFree(raw);
loading->loading.mesh.vertCount = vertCount;
loading->loading.mesh.data = (uint8_t *)vertices;
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_CREATE_MESH;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetMeshLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.mesh.state) {
case ASSET_MESH_LOADING_STATE_INITIAL:
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
break;
case ASSET_MESH_LOADING_STATE_CREATE_MESH:
break;
default:
errorOk();
}
uint32_t vertCount = loading->loading.mesh.vertCount;
meshvertex_t *vertices = (meshvertex_t *)loading->loading.mesh.data;
loading->loading.mesh.data = NULL;
assetmeshoutput_t *out = &loading->entry->data.mesh;
out->vertices = vertices;
if(vertCount == 0) {
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t ret = meshInit(
&out->mesh,
MESH_PRIMITIVE_TYPE_TRIANGLES,
(int32_t)vertCount,
out->vertices
);
if(errorIsNotOk(ret)) {
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
memoryFree(out->vertices);
out->vertices = NULL;
errorChain(ret);
}
out->meshInitialized = true;
ret = meshFlush(&out->mesh, 0, (int32_t)vertCount);
if(errorIsNotOk(ret)) {
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
meshDispose(&out->mesh);
out->meshInitialized = false;
memoryFree(out->vertices);
out->vertices = NULL;
errorChain(ret);
}
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetMeshDispose(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
assetmeshoutput_t *out = &entry->data.mesh;
if(out->meshInitialized) {
errorChain(meshDispose(&out->mesh));
out->meshInitialized = false;
}
if(out->vertices != NULL) {
memoryFree(out->vertices);
out->vertices = NULL;
}
errorOk();
}
@@ -0,0 +1,63 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/assetfile.h"
#include "display/mesh/mesh.h"
#define ASSET_MESH_FILE_VERSION 1
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
typedef enum {
ASSET_MESH_LOADING_STATE_INITIAL,
ASSET_MESH_LOADING_STATE_READ_FILE,
ASSET_MESH_LOADING_STATE_CREATE_MESH,
ASSET_MESH_LOADING_STATE_DONE
} assetmeshloadingstate_t;
typedef struct {
assetfile_t file;
assetmeshloadingstate_t state;
uint32_t vertCount;
uint8_t *data;
} assetmeshloaderloading_t;
typedef struct {
mesh_t mesh;
bool_t meshInitialized;
meshvertex_t *vertices;
} assetmeshoutput_t;
/**
* Asynchronous loader for DMF mesh assets. Reads the file, validates the
* header, and prepares a ready-to-use vertex buffer so the sync phase only
* needs to upload to the GPU.
*
* @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure.
*/
errorret_t assetMeshLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader for DMF mesh assets. Initializes the mesh from the
* vertex buffer prepared by the async phase and flushes it to the GPU.
*
* @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure.
*/
errorret_t assetMeshLoaderSync(assetloading_t *loading);
/**
* Disposer for DMF mesh assets. Disposes the mesh and frees the vertex
* buffer.
*
* @param entry Asset entry containing the mesh data to dispose.
* @return Error code indicating success or failure.
*/
errorret_t assetMeshDispose(assetentry_t *entry);
@@ -0,0 +1,171 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetmodelloader.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "asset/asset.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/json/assetjsonloader.h"
#include "display/texture/texture.h"
#include "yyjson.h"
errorret_t assetModelLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread.");
errorOk();
}
errorret_t assetModelLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_MODEL, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.model.state) {
case ASSET_MODEL_LOADING_STATE_INITIAL:
loading->loading.model.state = ASSET_MODEL_LOADING_STATE_LOCK_ASSETS;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
break;
case ASSET_MODEL_LOADING_STATE_LOCK_ASSETS: {
// Lock the model's JSON descriptor as a JSON sub-asset. The entry
// key is prefixed with "json:" to avoid a type-collision with the
// model entry itself (both share the same filename). The JSON loader
// reads the real file path supplied in the input.
char_t jsonKey[ASSET_FILE_NAME_MAX];
stringFormat(
jsonKey, sizeof(jsonKey), "json:%s", loading->entry->name
);
assetloaderinput_t jsonInput;
memoryZero(&jsonInput, sizeof(jsonInput));
stringCopy(
jsonInput.json.path, loading->entry->name, ASSET_FILE_NAME_MAX
);
assetentry_t *jsonEntry = assetLock(
jsonKey, ASSET_LOADER_TYPE_JSON, &jsonInput
);
errorret_t ret = assetRequireLoaded(jsonEntry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorChain(ret);
}
yyjson_val *root = yyjson_doc_get_root(jsonEntry->data.json);
// Parse required mesh path.
yyjson_val *meshVal = yyjson_obj_get(root, "mesh");
if(!meshVal || !yyjson_is_str(meshVal)) {
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow("Model JSON missing 'mesh' string");
}
const char *meshStr = yyjson_get_str(meshVal);
size_t meshLen = yyjson_get_len(meshVal);
if(meshLen >= ASSET_FILE_NAME_MAX) {
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow("Model mesh path exceeds max length");
}
char_t meshName[ASSET_FILE_NAME_MAX];
memoryCopy(meshName, meshStr, meshLen + 1);
// Parse optional texture path (absent = color only, no texture).
char_t textureName[ASSET_FILE_NAME_MAX];
textureName[0] = '\0';
yyjson_val *texVal = yyjson_obj_get(root, "texture");
if(texVal && yyjson_is_str(texVal)) {
const char *texStr = yyjson_get_str(texVal);
size_t texLen = yyjson_get_len(texVal);
if(texLen >= ASSET_FILE_NAME_MAX) {
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow("Model texture path exceeds max length");
}
memoryCopy(textureName, texStr, texLen + 1);
}
// Parse optional color (RGBA array 0-255, default white).
color_t color = COLOR_WHITE;
yyjson_val *colorVal = yyjson_obj_get(root, "color");
if(colorVal && yyjson_is_arr(colorVal)) {
uint8_t ch[4] = {255, 255, 255, 255};
size_t colorIdx, colorLen;
yyjson_val *colorElem;
yyjson_arr_foreach(colorVal, colorIdx, colorLen, colorElem) {
if(colorIdx >= 4) break;
if(yyjson_is_int(colorElem)) {
ch[colorIdx] = (uint8_t)yyjson_get_int(colorElem);
}
}
color.r = ch[0];
color.g = ch[1];
color.b = ch[2];
color.a = ch[3];
}
// Release JSON entry; all needed fields are now in local variables.
assetUnlockEntry(jsonEntry);
// Lock and load the mesh sub-asset.
assetentry_t *meshEntry = assetLock(meshName, ASSET_LOADER_TYPE_MESH, NULL);
ret = assetRequireLoaded(meshEntry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(meshEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorChain(ret);
}
// Lock and load the optional texture sub-asset.
assetentry_t *texEntry = NULL;
if(textureName[0] != '\0') {
assetloaderinput_t texInput = { .texture = TEXTURE_FORMAT_RGBA };
texEntry = assetLock(textureName, ASSET_LOADER_TYPE_TEXTURE, &texInput);
ret = assetRequireLoaded(texEntry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(texEntry);
assetUnlockEntry(meshEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorChain(ret);
}
}
assetmodeloutput_t *out = &loading->entry->data.model;
out->meshEntry = meshEntry;
out->texEntry = texEntry;
out->color = color;
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
break;
}
default:
errorOk();
}
errorOk();
}
errorret_t assetModelDispose(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_MODEL, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
assetmodeloutput_t *out = &entry->data.model;
if(out->meshEntry != NULL) {
assetUnlockEntry(out->meshEntry);
out->meshEntry = NULL;
}
if(out->texEntry != NULL) {
assetUnlockEntry(out->texEntry);
out->texEntry = NULL;
}
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 "error/error.h"
#include "display/color.h"
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
typedef enum {
ASSET_MODEL_LOADING_STATE_INITIAL,
ASSET_MODEL_LOADING_STATE_LOCK_ASSETS
} assetmodelloadingstate_t;
typedef struct {
assetmodelloadingstate_t state;
} assetmodelloaderloading_t;
typedef struct {
assetentry_t *meshEntry;
assetentry_t *texEntry;
color_t color;
} assetmodeloutput_t;
/**
* Async loader stub for model assets. Model loading is performed entirely
* on the main thread; this callback is never reached.
*
* @param loading Loading information for the asset being loaded.
* @returns Always success.
*/
errorret_t assetModelLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader for model assets. Locks the JSON descriptor file as
* a sub-asset, waits for it to load, parses the mesh path, optional
* texture path, and color tint, then releases the JSON entry. Locks and
* waits for mesh and optional texture sub-assets sequentially to stay
* within ASSET_LOADING_COUNT_MAX slot limits.
*
* @param loading Loading information for the asset being loaded.
* @returns Error code indicating success or failure.
*/
errorret_t assetModelLoaderSync(assetloading_t *loading);
/**
* Disposer for model assets. Releases the locks on the mesh and texture
* sub-asset entries.
*
* @param entry Asset entry containing the model to dispose.
* @returns Error code indicating success or failure.
*/
errorret_t assetModelDispose(assetentry_t *entry);
+5 -3
View File
@@ -22,9 +22,11 @@ errorret_t assetJsonLoaderAsync(assetloading_t *loading) {
assertNull(loading->loading.json.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.json.file;
assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
const char_t *filePath = (
loading->entry->input != NULL &&
loading->entry->input->json.path[0] != '\0'
) ? loading->entry->input->json.path : loading->entry->name;
assetLoaderErrorChain(loading, assetFileInit(file, filePath, NULL, NULL));
if(file->size > ASSET_JSON_FILE_SIZE_MAX) {
assetLoaderErrorThrow(loading, "JSON exceeds maximum allowed size");
+10 -1
View File
@@ -14,7 +14,16 @@
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
typedef struct { void *nothing; } assetjsonloaderinput_t;
/**
* Optional file path override. When path[0] is non-zero the JSON loader
* reads this path from the archive instead of loading->entry->name. Use
* this to decouple the asset pool key from the actual file location (e.g.
* when a parent loader locks a JSON entry under a synthetic key to avoid
* a type-collision with an entry of the same name but different type).
*/
typedef struct {
char_t path[ASSET_FILE_NAME_MAX];
} assetjsonloaderinput_t;
typedef enum {
ASSET_JSON_LOADING_STATE_INITIAL,
@@ -506,12 +506,17 @@ errorret_t assetLocaleGetString(
sizeof(lineBuffer)
);
// Prime the reader with the first line before scanning; outBuffer holds
// uninitialized memory until the first Next() call fills it.
errorChain(assetFileLineReaderNext(&reader));
// Skip blanks, comments, etc and start looking for msgid's
errorChain(assetLocaleLineSkipBlanks(&reader, lineBuffer));
while(!reader.eof) {
while(true) {
// Is this msgid?
if(memoryCompare(lineBuffer, "msgid", 5) != 0) {
if(reader.eof) break;
errorChain(assetFileLineReaderNext(&reader));
msgidBuffer[0] = '\0';
continue;
@@ -535,7 +540,7 @@ errorret_t assetLocaleGetString(
}
// We are either going to see a msgstr or a msgid_plural
while(!reader.eof) {
while(true) {
errorChain(assetLocaleLineSkipBlanks(&reader, lineBuffer));
// Is msgid_plural?
+7 -14
View File
@@ -17,11 +17,9 @@ console_t CONSOLE;
void consoleInit(void) {
memoryZero(&CONSOLE, sizeof(console_t));
CONSOLE.visible = true;
CONSOLE.visible = false;
#ifdef DUSK_CONSOLE_POSIX
threadMutexInit(&CONSOLE.printMutex);
#endif
threadMutexInit(&CONSOLE.printMutex);
}
void consolePrint(const char_t *message, ...) {
@@ -32,9 +30,7 @@ void consolePrint(const char_t *message, ...) {
int32_t len = stringFormatVA(buffer, CONSOLE_LINE_MAX, message, args);
va_end(args);
#ifdef DUSK_CONSOLE_POSIX
threadMutexLock(&CONSOLE.printMutex);
#endif
threadMutexLock(&CONSOLE.printMutex);
memoryMove(
CONSOLE.line[0],
@@ -42,10 +38,9 @@ void consolePrint(const char_t *message, ...) {
(CONSOLE_HISTORY_MAX - 1) * CONSOLE_LINE_MAX
);
memoryCopy(CONSOLE.line[CONSOLE_HISTORY_MAX - 1], buffer, len + 1);
CONSOLE.dirty = true;
#ifdef DUSK_CONSOLE_POSIX
threadMutexUnlock(&CONSOLE.printMutex);
#endif
threadMutexUnlock(&CONSOLE.printMutex);
logDebug("%s\n", buffer);
}
@@ -55,13 +50,11 @@ void consoleUpdate(void) {
if(TIME.dynamicUpdate) return;
#endif
if(inputPressed(INPUT_ACTION_CONSOLE)) {
if(inputPressed(INPUT_BIND_CONSOLE)) {
CONSOLE.visible = !CONSOLE.visible;
}
}
void consoleDispose(void) {
#ifdef DUSK_CONSOLE_POSIX
threadMutexDispose(&CONSOLE.printMutex);
#endif
threadMutexDispose(&CONSOLE.printMutex);
}
+7 -10
View File
@@ -9,21 +9,18 @@
#include "consoledefs.h"
#include "error/error.h"
#include "dusk.h"
#ifdef DUSK_CONSOLE_POSIX
#include "thread/thread.h"
#include <poll.h>
#include <unistd.h>
#define CONSOLE_POSIX_POLL_RATE 75
#endif
#include "thread/thread.h"
typedef struct {
char_t line[CONSOLE_HISTORY_MAX][CONSOLE_LINE_MAX];
bool_t visible;
#ifdef DUSK_CONSOLE_POSIX
threadmutex_t printMutex;
#endif
// Set whenever the history changes; consumers rendering the console
// (e.g. uiConsoleDraw) check and clear this to know when their own
// cached representation of the history needs rebuilding.
bool_t dirty;
threadmutex_t printMutex;
} console_t;
extern console_t CONSOLE;
+7 -1
View File
@@ -21,7 +21,13 @@ add_subdirectory(texture)
# Color definitions
dusk_run_python(
dusk_color_defs
tools.color.csv
tools.color
OUTPUT ${DUSK_GENERATED_HEADERS_DIR}/display/color.h
DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/color.csv
${DUSK_TOOLS_DIR}/color.py
${DUSK_TOOLS_DIR}/writeifchanged.py
ARGS
--csv ${CMAKE_CURRENT_SOURCE_DIR}/color.csv
--output ${DUSK_GENERATED_HEADERS_DIR}/display/color.h
)
+8
View File
@@ -33,6 +33,14 @@
#endif
#endif
#ifndef DUSK_DISPLAY_SCALE_UI
#define DUSK_DISPLAY_SCALE_UI 1
#endif
#ifndef DUSK_DISPLAY_SCALE_3D
#define DUSK_DISPLAY_SCALE_3D 1
#endif
// Main Display Struct, platform-speicifc
typedef displayplatform_t display_t;
+7 -25
View File
@@ -20,9 +20,6 @@ errorret_t capsuleInit() {
0.5f,
CAPSULE_CAP_RINGS,
CAPSULE_SECTORS
#if MESH_ENABLE_COLOR
, COLOR_WHITE_4B
#endif
);
errorChain(meshInit(
&CAPSULE_MESH_SIMPLE,
@@ -40,9 +37,6 @@ void capsuleBuffer(
const float_t halfHeight,
const int32_t capRings,
const int32_t sectors
#if MESH_ENABLE_COLOR
, const color_t color
#endif
) {
assertNotNull(vertices, "Vertices cannot be NULL");
assertNotNull(center, "Center vector cannot be NULL");
@@ -53,25 +47,13 @@ void capsuleBuffer(
const float_t sectorStep = 2.0f * (float_t)GLM_PI / (float_t)sectors;
int32_t vi = 0;
/* Helper macro: write one vertex. */
#if MESH_ENABLE_COLOR
#define CAP_VERT(px, py, pz, u, v) \
vertices[vi].color = color; \
vertices[vi].pos[0] = (px); \
vertices[vi].pos[1] = (py); \
vertices[vi].pos[2] = (pz); \
vertices[vi].uv[0] = (u); \
vertices[vi].uv[1] = (v); \
vi++;
#else
#define CAP_VERT(px, py, pz, u, v) \
vertices[vi].pos[0] = (px); \
vertices[vi].pos[1] = (py); \
vertices[vi].pos[2] = (pz); \
vertices[vi].uv[0] = (u); \
vertices[vi].uv[1] = (v); \
vi++;
#endif
#define CAP_VERT(px, py, pz, u, v) \
vertices[vi].pos[0] = (px); \
vertices[vi].pos[1] = (py); \
vertices[vi].pos[2] = (pz); \
vertices[vi].uv[0] = (u); \
vertices[vi].uv[1] = (v); \
vi++;
/* ---- Top hemisphere ---- */
/* phi ranges from PI/2 (top pole) down to 0 (equator). */
-4
View File
@@ -7,7 +7,6 @@
#pragma once
#include "display/mesh/mesh.h"
#include "display/color.h"
#define CAPSULE_CAP_RINGS 4
#define CAPSULE_SECTORS 16
@@ -46,7 +45,4 @@ void capsuleBuffer(
const float_t halfHeight,
const int32_t capRings,
const int32_t sectors
#if MESH_ENABLE_COLOR
, const color_t color
#endif
);
+9 -28
View File
@@ -12,14 +12,9 @@ mesh_t CUBE_MESH_SIMPLE;
meshvertex_t CUBE_MESH_SIMPLE_VERTICES[CUBE_VERTEX_COUNT];
errorret_t cubeInit() {
vec3 min = { 0.0f, 0.0f, 0.0f };
vec3 max = { 1.0f, 1.0f, 1.0f };
cubeBuffer(
CUBE_MESH_SIMPLE_VERTICES, min, max
#if MESH_ENABLE_COLOR
, COLOR_WHITE_4B
#endif
);
vec3 min = { -0.5f, -0.5f, -0.5f };
vec3 max = { 0.5f, 0.5f, 0.5f };
cubeBuffer(CUBE_MESH_SIMPLE_VERTICES, min, max);
errorChain(meshInit(
&CUBE_MESH_SIMPLE,
CUBE_PRIMITIVE_TYPE,
@@ -29,31 +24,17 @@ errorret_t cubeInit() {
errorOk();
}
// Helper macro: set one vertex position, UV and color.
#if MESH_ENABLE_COLOR
#define CUBE_VERT(i, px, py, pz, u, v) \
vertices[i].color = color; \
vertices[i].pos[0] = (px); \
vertices[i].pos[1] = (py); \
vertices[i].pos[2] = (pz); \
vertices[i].uv[0] = (u); \
vertices[i].uv[1] = (v);
#else
#define CUBE_VERT(i, px, py, pz, u, v) \
vertices[i].pos[0] = (px); \
vertices[i].pos[1] = (py); \
vertices[i].pos[2] = (pz); \
vertices[i].uv[0] = (u); \
vertices[i].uv[1] = (v);
#endif
#define CUBE_VERT(i, px, py, pz, u, v) \
vertices[i].pos[0] = (px); \
vertices[i].pos[1] = (py); \
vertices[i].pos[2] = (pz); \
vertices[i].uv[0] = (u); \
vertices[i].uv[1] = (v);
void cubeBuffer(
meshvertex_t *vertices,
const vec3 min,
const vec3 max
#if MESH_ENABLE_COLOR
, const color_t color
#endif
) {
assertNotNull(vertices, "Vertices cannot be NULL");
assertNotNull(min, "Min vector cannot be NULL");
+3 -5
View File
@@ -7,7 +7,6 @@
#pragma once
#include "display/mesh/mesh.h"
#include "display/color.h"
#define CUBE_FACE_COUNT 6
#define CUBE_VERTICES_PER_FACE 6
@@ -18,7 +17,9 @@ extern mesh_t CUBE_MESH_SIMPLE;
extern meshvertex_t CUBE_MESH_SIMPLE_VERTICES[CUBE_VERTEX_COUNT];
/**
* Initializes the simple unit cube mesh (0,0,0) to (1,1,1).
* Initializes the simple unit cube mesh, centered at (0,0,0), spanning
* (-0.5,-0.5,-0.5) to (0.5,0.5,0.5) -- matching the centered convention
* physics shapes and the sphere mesh use (position = center).
*
* @return Error for initialization of the cube mesh.
*/
@@ -37,7 +38,4 @@ void cubeBuffer(
meshvertex_t *vertices,
const vec3 min,
const vec3 max
#if MESH_ENABLE_COLOR
, const color_t color
#endif
);
+2 -11
View File
@@ -1,26 +1,17 @@
/**
* Copyright (c) 2026 Dominic Masters
*
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "display/color.h"
#ifndef MESH_ENABLE_COLOR
#define MESH_ENABLE_COLOR 0
#endif
#define MESH_VERTEX_UV_SIZE 2
#define MESH_VERTEX_POS_SIZE 3
typedef struct {
#if MESH_ENABLE_COLOR
color_t color;
#endif
float_t uv[MESH_VERTEX_UV_SIZE];
float_t pos[MESH_VERTEX_POS_SIZE];
} meshvertex_t;
} meshvertex_t;
+23 -34
View File
@@ -20,11 +20,8 @@ errorret_t planeInit() {
PLANE_MESH_SIMPLE_VERTICES,
PLANE_AXIS_XZ,
min,
max
#if MESH_ENABLE_COLOR
, COLOR_WHITE_4B
#endif
, uvMin,
max,
uvMin,
uvMax
);
errorChain(meshInit(
@@ -36,33 +33,19 @@ errorret_t planeInit() {
errorOk();
}
/* Helper macro to write one vertex. */
#if MESH_ENABLE_COLOR
#define PLANE_VERT(i, px, py, pz, u, v) \
vertices[i].color = color; \
vertices[i].pos[0] = (px); \
vertices[i].pos[1] = (py); \
vertices[i].pos[2] = (pz); \
vertices[i].uv[0] = (u); \
vertices[i].uv[1] = (v);
#else
#define PLANE_VERT(i, px, py, pz, u, v) \
vertices[i].pos[0] = (px); \
vertices[i].pos[1] = (py); \
vertices[i].pos[2] = (pz); \
vertices[i].uv[0] = (u); \
vertices[i].uv[1] = (v);
#endif
#define PLANE_VERT(i, px, py, pz, u, v) \
vertices[i].pos[0] = (px); \
vertices[i].pos[1] = (py); \
vertices[i].pos[2] = (pz); \
vertices[i].uv[0] = (u); \
vertices[i].uv[1] = (v);
void planeBuffer(
meshvertex_t *vertices,
const planeaxis_t axis,
const vec3 min,
const vec3 max
#if MESH_ENABLE_COLOR
, const color_t color
#endif
, const vec2 uvMin,
const vec3 max,
const vec2 uvMin,
const vec2 uvMax
) {
assertNotNull(vertices, "Vertices cannot be NULL");
@@ -76,7 +59,8 @@ void planeBuffer(
switch(axis) {
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.
// +Z normal: CCW when viewed from +Z (matches cube.c's front face).
const float_t z = min[2];
PLANE_VERT(0, min[0], min[1], z, u0, v0)
PLANE_VERT(1, max[0], min[1], z, u1, v0)
@@ -88,19 +72,24 @@ void planeBuffer(
}
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.
// +Y normal: CCW when viewed from +Y (matches cube.c's top face).
// X and Z swap handedness relative to XY/YZ (right-hand rule with Y
// up), so the corner order here is deliberately not a straight copy
// of the XY/YZ pattern -- copying it as-is would flip this to -Y.
const float_t y = min[1];
PLANE_VERT(0, min[0], y, min[2], u0, v0)
PLANE_VERT(1, max[0], y, min[2], u1, v0)
PLANE_VERT(2, max[0], y, max[2], u1, v1)
PLANE_VERT(1, max[0], y, max[2], u1, v1)
PLANE_VERT(2, max[0], y, min[2], u1, v0)
PLANE_VERT(3, min[0], y, min[2], u0, v0)
PLANE_VERT(4, max[0], y, max[2], u1, v1)
PLANE_VERT(5, min[0], y, max[2], u0, v1)
PLANE_VERT(4, min[0], y, max[2], u0, v1)
PLANE_VERT(5, max[0], y, max[2], u1, v1)
break;
}
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.
// +X normal: CCW when viewed from +X (matches cube.c's right face).
const float_t x = min[0];
PLANE_VERT(0, x, min[1], min[2], u0, v0)
PLANE_VERT(1, x, max[1], min[2], u1, v0)
+2 -6
View File
@@ -7,7 +7,6 @@
#pragma once
#include "display/mesh/mesh.h"
#include "display/color.h"
#define PLANE_VERTEX_COUNT 6
#define PLANE_PRIMITIVE_TYPE MESH_PRIMITIVE_TYPE_TRIANGLES
@@ -52,10 +51,7 @@ void planeBuffer(
meshvertex_t *vertices,
const planeaxis_t axis,
const vec3 min,
const vec3 max
#if MESH_ENABLE_COLOR
, const color_t color
#endif
, const vec2 uvMin,
const vec3 max,
const vec2 uvMin,
const vec2 uvMax
);
+31 -150
View File
@@ -10,55 +10,12 @@
mesh_t QUAD_MESH_SIMPLE;
meshvertex_t QUAD_MESH_SIMPLE_VERTICES[QUAD_VERTEX_COUNT] = {
{
#if MESH_ENABLE_COLOR
.color = COLOR_WHITE_4B,
#endif
.uv = { 0.0f, 0.0f },
.pos = { 0.0f, 0.0f, 0.0f }
},
{
#if MESH_ENABLE_COLOR
.color = COLOR_WHITE_4B,
#endif
.uv = { 1.0f, 0.0f },
.pos = { 1.0f, 0.0f, 0.0f }
},
{
#if MESH_ENABLE_COLOR
.color = COLOR_WHITE_4B,
#endif
.uv = { 1.0f, 1.0f },
.pos = { 1.0f, 1.0f, 0.0f }
},
{
#if MESH_ENABLE_COLOR
.color = COLOR_WHITE_4B,
#endif
.uv = { 0.0f, 0.0f },
.pos = { 0.0f, 0.0f, 0.0f }
},
{
#if MESH_ENABLE_COLOR
.color = COLOR_WHITE_4B,
#endif
.uv = { 1.0f, 1.0f },
.pos = { 1.0f, 1.0f, 0.0f }
},
{
#if MESH_ENABLE_COLOR
.color = COLOR_WHITE_4B,
#endif
.uv = { 0.0f, 1.0f },
.pos = { 0.0f, 1.0f, 0.0f }
}
{ .uv = { 0.0f, 0.0f }, .pos = { 0.0f, 0.0f, 0.0f } },
{ .uv = { 1.0f, 0.0f }, .pos = { 1.0f, 0.0f, 0.0f } },
{ .uv = { 1.0f, 1.0f }, .pos = { 1.0f, 1.0f, 0.0f } },
{ .uv = { 0.0f, 0.0f }, .pos = { 0.0f, 0.0f, 0.0f } },
{ .uv = { 1.0f, 1.0f }, .pos = { 1.0f, 1.0f, 0.0f } },
{ .uv = { 0.0f, 1.0f }, .pos = { 0.0f, 1.0f, 0.0f } }
};
errorret_t quadInit() {
@@ -81,68 +38,27 @@ void quadBuffer(
const float_t v0,
const float_t u1,
const float_t v1
#if MESH_ENABLE_COLOR
, const color_t color
#endif
) {
const float_t z = 0.0f; // Z coordinate for 2D rendering
const float_t z = 0.0f;
assertNotNull(vertices, "Vertices cannot be NULL");
// First triangle
#if MESH_ENABLE_COLOR
vertices[0].color = color;
#endif
vertices[0].uv[0] = u0;
vertices[0].uv[1] = v1;
vertices[0].pos[0] = minX;
vertices[0].pos[1] = maxY;
vertices[0].pos[2] = z;
vertices[0].uv[0] = u0; vertices[0].uv[1] = v1;
vertices[0].pos[0] = minX; vertices[0].pos[1] = maxY; vertices[0].pos[2] = z;
#if MESH_ENABLE_COLOR
vertices[1].color = color;
#endif
vertices[1].uv[0] = u1;
vertices[1].uv[1] = v0;
vertices[1].pos[0] = maxX;
vertices[1].pos[1] = minY;
vertices[1].pos[2] = z;
vertices[1].uv[0] = u1; vertices[1].uv[1] = v0;
vertices[1].pos[0] = maxX; vertices[1].pos[1] = minY; vertices[1].pos[2] = z;
#if MESH_ENABLE_COLOR
vertices[2].color = color;
#endif
vertices[2].uv[0] = u0;
vertices[2].uv[1] = v0;
vertices[2].pos[0] = minX;
vertices[2].pos[1] = minY;
vertices[2].pos[2] = z;
vertices[2].uv[0] = u0; vertices[2].uv[1] = v0;
vertices[2].pos[0] = minX; vertices[2].pos[1] = minY; vertices[2].pos[2] = z;
// Second triangle
#if MESH_ENABLE_COLOR
vertices[3].color = color;
#endif
vertices[3].uv[0] = u0;
vertices[3].uv[1] = v1;
vertices[3].pos[0] = minX;
vertices[3].pos[1] = maxY;
vertices[3].pos[2] = z;
vertices[3].uv[0] = u0; vertices[3].uv[1] = v1;
vertices[3].pos[0] = minX; vertices[3].pos[1] = maxY; vertices[3].pos[2] = z;
#if MESH_ENABLE_COLOR
vertices[4].color = color;
#endif
vertices[4].uv[0] = u1;
vertices[4].uv[1] = v1;
vertices[4].pos[0] = maxX;
vertices[4].pos[1] = maxY;
vertices[4].pos[2] = z;
vertices[4].uv[0] = u1; vertices[4].uv[1] = v1;
vertices[4].pos[0] = maxX; vertices[4].pos[1] = maxY; vertices[4].pos[2] = z;
#if MESH_ENABLE_COLOR
vertices[5].color = color;
#endif
vertices[5].uv[0] = u1;
vertices[5].uv[1] = v0;
vertices[5].pos[0] = maxX;
vertices[5].pos[1] = minY;
vertices[5].pos[2] = z;
vertices[5].uv[0] = u1; vertices[5].uv[1] = v0;
vertices[5].pos[0] = maxX; vertices[5].pos[1] = minY; vertices[5].pos[2] = z;
}
void quadBuffer3D(
@@ -151,9 +67,6 @@ void quadBuffer3D(
const vec3 max,
const vec2 uvMin,
const vec2 uvMax
#if MESH_ENABLE_COLOR
, const color_t color
#endif
) {
assertNotNull(vertices, "Vertices cannot be NULL");
assertNotNull(min, "Min vector cannot be NULL");
@@ -161,59 +74,27 @@ void quadBuffer3D(
assertNotNull(uvMin, "UV Min vector cannot be NULL");
assertNotNull(uvMax, "UV Max vector cannot be NULL");
// First triangle
#if MESH_ENABLE_COLOR
vertices[0].color = color;
#endif
vertices[0].uv[0] = uvMin[0];
vertices[0].uv[1] = uvMin[1];
vertices[0].pos[0] = min[0];
vertices[0].pos[1] = min[1];
vertices[0].uv[0] = uvMin[0]; vertices[0].uv[1] = uvMin[1];
vertices[0].pos[0] = min[0]; vertices[0].pos[1] = min[1];
vertices[0].pos[2] = min[2];
#if MESH_ENABLE_COLOR
vertices[1].color = color;
#endif
vertices[1].uv[0] = uvMax[0];
vertices[1].uv[1] = uvMin[1];
vertices[1].pos[0] = max[0];
vertices[1].pos[1] = min[1];
vertices[1].uv[0] = uvMax[0]; vertices[1].uv[1] = uvMin[1];
vertices[1].pos[0] = max[0]; vertices[1].pos[1] = min[1];
vertices[1].pos[2] = min[2];
#if MESH_ENABLE_COLOR
vertices[2].color = color;
#endif
vertices[2].uv[0] = uvMax[0];
vertices[2].uv[1] = uvMax[1];
vertices[2].pos[0] = max[0];
vertices[2].pos[1] = max[1];
vertices[2].uv[0] = uvMax[0]; vertices[2].uv[1] = uvMax[1];
vertices[2].pos[0] = max[0]; vertices[2].pos[1] = max[1];
vertices[2].pos[2] = min[2];
// Second triangle
#if MESH_ENABLE_COLOR
vertices[3].color = color;
#endif
vertices[3].uv[0] = uvMin[0];
vertices[3].uv[1] = uvMin[1];
vertices[3].pos[0] = min[0];
vertices[3].pos[1] = min[1];
vertices[3].uv[0] = uvMin[0]; vertices[3].uv[1] = uvMin[1];
vertices[3].pos[0] = min[0]; vertices[3].pos[1] = min[1];
vertices[3].pos[2] = min[2];
#if MESH_ENABLE_COLOR
vertices[4].color = color;
#endif
vertices[4].uv[0] = uvMax[0];
vertices[4].uv[1] = uvMax[1];
vertices[4].pos[0] = max[0];
vertices[4].pos[1] = max[1];
vertices[4].uv[0] = uvMax[0]; vertices[4].uv[1] = uvMax[1];
vertices[4].pos[0] = max[0]; vertices[4].pos[1] = max[1];
vertices[4].pos[2] = min[2];
#if MESH_ENABLE_COLOR
vertices[5].color = color;
#endif
vertices[5].uv[0] = uvMin[0];
vertices[5].uv[1] = uvMax[1];
vertices[5].pos[0] = min[0];
vertices[5].pos[1] = max[1];
vertices[5].uv[0] = uvMin[0]; vertices[5].uv[1] = uvMax[1];
vertices[5].pos[0] = min[0]; vertices[5].pos[1] = max[1];
vertices[5].pos[2] = min[2];
}
+1 -9
View File
@@ -7,7 +7,6 @@
#pragma once
#include "mesh.h"
#include "display/color.h"
#define QUAD_VERTEX_COUNT 6
#define QUAD_PRIMITIVE_TYPE MESH_PRIMITIVE_TYPE_TRIANGLES
@@ -46,18 +45,14 @@ void quadBuffer(
const float_t v0,
const float_t u1,
const float_t v1
#if MESH_ENABLE_COLOR
, const color_t color
#endif
);
/**
* Buffers a 3D quad into the provided vertex array.
*
*
* @param vertices The vertex array to buffer into.
* @param min The minimum XYZ coordinates of the quad.
* @param max The maximum XYZ coordinates of the quad.
* @param color The color of the quad.
* @param uvMin The minimum UV coordinates of the quad.
* @param uvMax The maximum UV coordinates of the quad.
*/
@@ -67,7 +62,4 @@ void quadBuffer3D(
const vec3 max,
const vec2 uvMin,
const vec2 uvMax
#if MESH_ENABLE_COLOR
, const color_t color
#endif
);
+12 -56
View File
@@ -19,9 +19,6 @@ errorret_t sphereInit() {
0.5f,
SPHERE_STACKS,
SPHERE_SECTORS
#if MESH_ENABLE_COLOR
, COLOR_WHITE_4B
#endif
);
errorChain(meshInit(
&SPHERE_MESH_SIMPLE,
@@ -38,9 +35,6 @@ void sphereBuffer(
const float_t radius,
const int32_t stacks,
const int32_t sectors
#if MESH_ENABLE_COLOR
, const color_t color
#endif
) {
assertNotNull(vertices, "Vertices cannot be NULL");
assertNotNull(center, "Center vector cannot be NULL");
@@ -79,67 +73,29 @@ void sphereBuffer(
const float_t u1 = (float_t)j / (float_t)sectors;
const float_t u2 = (float_t)(j + 1) / (float_t)sectors;
/* Triangle 1: top-left, bottom-left, top-right */
#if MESH_ENABLE_COLOR
vertices[vi].color = color;
#endif
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].uv[0] = u1;
vertices[vi].uv[1] = v1;
vi++;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v1; vi++;
#if MESH_ENABLE_COLOR
vertices[vi].color = color;
#endif
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].uv[0] = u1;
vertices[vi].uv[1] = v2;
vi++;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
#if MESH_ENABLE_COLOR
vertices[vi].color = color;
#endif
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].uv[0] = u2;
vertices[vi].uv[1] = v1;
vi++;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
/* Triangle 2: top-right, bottom-left, bottom-right */
#if MESH_ENABLE_COLOR
vertices[vi].color = color;
#endif
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].uv[0] = u2;
vertices[vi].uv[1] = v1;
vi++;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v1; vi++;
#if MESH_ENABLE_COLOR
vertices[vi].color = color;
#endif
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].uv[0] = u1;
vertices[vi].uv[1] = v2;
vi++;
vertices[vi].uv[0] = u1; vertices[vi].uv[1] = v2; vi++;
#if MESH_ENABLE_COLOR
vertices[vi].color = color;
#endif
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].uv[0] = u2;
vertices[vi].uv[1] = v2;
vi++;
vertices[vi].uv[0] = u2; vertices[vi].uv[1] = v2; vi++;
}
}
}
-4
View File
@@ -7,7 +7,6 @@
#pragma once
#include "display/mesh/mesh.h"
#include "display/color.h"
#define SPHERE_STACKS 8
#define SPHERE_SECTORS 16
@@ -41,7 +40,4 @@ void sphereBuffer(
const float_t radius,
const int32_t stacks,
const int32_t sectors
#if MESH_ENABLE_COLOR
, const color_t color
#endif
);
+11 -29
View File
@@ -14,13 +14,10 @@ meshvertex_t TRIPRISM_MESH_SIMPLE_VERTICES[TRIPRISM_VERTEX_COUNT];
errorret_t triPrismInit() {
triPrismBuffer(
TRIPRISM_MESH_SIMPLE_VERTICES,
0.0f, 0.0f, /* p0: bottom-left */
1.0f, 0.0f, /* p1: bottom-right */
0.5f, 1.0f, /* p2: apex */
0.0f, 1.0f /* minZ, maxZ */
#if MESH_ENABLE_COLOR
, COLOR_WHITE_4B
#endif
0.0f, 0.0f,
1.0f, 0.0f,
0.5f, 1.0f,
0.0f, 1.0f
);
errorChain(meshInit(
&TRIPRISM_MESH_SIMPLE,
@@ -38,32 +35,17 @@ void triPrismBuffer(
const float_t x2, const float_t y2,
const float_t minZ,
const float_t maxZ
#if MESH_ENABLE_COLOR
, const color_t color
#endif
) {
assertNotNull(vertices, "Vertices cannot be NULL");
/* Helper macro: write one vertex then advance index. */
int32_t vi = 0;
#if MESH_ENABLE_COLOR
#define PRISM_VERT(px, py, pz, u, v) \
vertices[vi].color = color; \
vertices[vi].pos[0] = (px); \
vertices[vi].pos[1] = (py); \
vertices[vi].pos[2] = (pz); \
vertices[vi].uv[0] = (u); \
vertices[vi].uv[1] = (v); \
vi++;
#else
#define PRISM_VERT(px, py, pz, u, v) \
vertices[vi].pos[0] = (px); \
vertices[vi].pos[1] = (py); \
vertices[vi].pos[2] = (pz); \
vertices[vi].uv[0] = (u); \
vertices[vi].uv[1] = (v); \
vi++;
#endif
#define PRISM_VERT(px, py, pz, u, v) \
vertices[vi].pos[0] = (px); \
vertices[vi].pos[1] = (py); \
vertices[vi].pos[2] = (pz); \
vertices[vi].uv[0] = (u); \
vertices[vi].uv[1] = (v); \
vi++;
/* --- Front face (z = maxZ), CCW from +Z --- */
PRISM_VERT(x0, y0, maxZ, 0.0f, 0.0f)
-4
View File
@@ -7,7 +7,6 @@
#pragma once
#include "display/mesh/mesh.h"
#include "display/color.h"
#define TRIPRISM_VERTEX_COUNT 24
#define TRIPRISM_PRIMITIVE_TYPE MESH_PRIMITIVE_TYPE_TRIANGLES
@@ -44,7 +43,4 @@ void triPrismBuffer(
const float_t x2, const float_t y2,
const float_t minZ,
const float_t maxZ
#if MESH_ENABLE_COLOR
, const color_t color
#endif
);
+4 -8
View File
@@ -23,6 +23,8 @@ const screencropaspectinfo_t SCREEN_CROP_ASPECTS[SCREEN_CROP_ASPECT_COUNT] = {
errorret_t screenInit() {
memoryZero(&SCREEN, sizeof(screen_t));
SCREEN.scaleUi = DUSK_DISPLAY_SCALE_UI;
SCREEN.scale3d = DUSK_DISPLAY_SCALE_3D;
SCREEN.background = COLOR_CORNFLOWER_BLUE;
#ifdef DUSK_DISPLAY_SIZE_DYNAMIC
@@ -35,9 +37,6 @@ errorret_t screenInit() {
1.0f, 1.0f,
0.0f, 0.0f,
1.0f, 1.0f
#if MESH_ENABLE_COLOR
, COLOR_WHITE
#endif
);
errorChain(meshInit(
&SCREEN.frameBufferMesh,
@@ -381,13 +380,10 @@ errorret_t screenRender() {
quadBuffer(
SCREEN.frameBufferMeshVertices,
centerX - fbWidth * 0.5f, centerY + fbHeight * 0.5f, // top-left
centerX + fbWidth * 0.5f, centerY - fbHeight * 0.5f, // bottom-right
centerX - fbWidth * 0.5f, centerY + fbHeight * 0.5f,
centerX + fbWidth * 0.5f, centerY - fbHeight * 0.5f,
0.0f, 0.0f,
1.0f, 1.0f
#if MESH_ENABLE_COLOR
, COLOR_WHITE
#endif
);
frameBufferClear(
+3
View File
@@ -7,6 +7,7 @@
#pragma once
#include "dusk.h"
#include "display/display.h"
#include "display/framebuffer/framebuffer.h"
#include "display/mesh/quad.h"
#include "display/color.h"
@@ -58,6 +59,8 @@ typedef enum {
// } screenscalemode_t;
typedef struct {
int32_t scaleUi;
int32_t scale3d;
screenmode_t mode;
// screenscalemode_t scaleMode;
+1
View File
@@ -21,6 +21,7 @@ errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) {
errorret_t shaderBind(shader_t *shader) {
assertNotNull(shader, "Shader cannot be null");
if(bound == shader) errorOk();
errorChain(shaderBindPlatform(shader));
bound = shader;
errorOk();
@@ -39,3 +39,16 @@ spritebatchsprite_t spriteBatchSpriteTilesetPosition(
sprite.uvMax[1] = uv[3];
return sprite;
}
spritebatchsprite_t spriteBatchSpriteTranslate(
const spritebatchsprite_t *sprite,
const float_t x,
const float_t y
) {
spritebatchsprite_t out = *sprite;
out.min[0] += x;
out.min[1] += y;
out.max[0] += x;
out.max[1] += y;
return out;
}
@@ -38,3 +38,19 @@ spritebatchsprite_t spriteBatchSpriteTilesetPosition(
const float_t width,
const float_t height
);
/**
* Returns a copy of sprite translated by (x, y). Used to reposition a
* sprite cached relative to origin (0,0) at draw time, instead of
* re-deriving its geometry from scratch every frame.
*
* @param sprite The cached sprite, relative to origin (0,0).
* @param x X offset to translate by.
* @param y Y offset to translate by.
* @returns The translated sprite.
*/
spritebatchsprite_t spriteBatchSpriteTranslate(
const spritebatchsprite_t *sprite,
const float_t x,
const float_t y
);
+1
View File
@@ -6,5 +6,6 @@
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
font.c
text.c
)
+168
View File
@@ -0,0 +1,168 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "font.h"
#include "util/memory.h"
#include "util/math.h"
#include "display/color.h"
font_t FONT_DEFAULT;
static texture_t FONT_DEFAULT_TEXTURE;
static tileset_t FONT_DEFAULT_TILESET;
const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
FONT_DEFAULT_TILE_HEIGHT
] = {
{ 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x00, 0x00 }, // !
{ 0x00, 0x14, 0x14, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // "
{ 0x00, 0x14, 0x14, 0x3E, 0x14, 0x3E, 0x14, 0x14, 0x00, 0x00 }, // #
{ 0x00, 0x08, 0x1E, 0x28, 0x1C, 0x0A, 0x3C, 0x08, 0x00, 0x00 }, // $
{ 0x00, 0x00, 0x22, 0x24, 0x08, 0x12, 0x22, 0x00, 0x00, 0x00 }, // %
{ 0x00, 0x08, 0x14, 0x14, 0x1A, 0x24, 0x24, 0x1A, 0x00, 0x00 }, // &
{ 0x00, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // '
{ 0x00, 0x04, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x00, 0x00 }, // (
{ 0x00, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x10, 0x00, 0x00 }, // )
{ 0x00, 0x00, 0x08, 0x2A, 0x1C, 0x2A, 0x08, 0x00, 0x00, 0x00 }, // *
{ 0x00, 0x00, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00, 0x00, 0x00 }, // +
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x20, 0x00 }, // ,
{ 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00 }, // -
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00 }, // .
{ 0x00, 0x04, 0x04, 0x08, 0x08, 0x08, 0x10, 0x10, 0x00, 0x00 }, // /
{ 0x00, 0x1C, 0x22, 0x26, 0x2A, 0x32, 0x22, 0x1C, 0x00, 0x00 }, // 0
{ 0x00, 0x08, 0x18, 0x08, 0x08, 0x08, 0x08, 0x3E, 0x00, 0x00 }, // 1
{ 0x00, 0x1C, 0x22, 0x02, 0x04, 0x08, 0x10, 0x3E, 0x00, 0x00 }, // 2
{ 0x00, 0x1C, 0x22, 0x02, 0x0C, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // 3
{ 0x00, 0x22, 0x22, 0x22, 0x3E, 0x02, 0x02, 0x02, 0x00, 0x00 }, // 4
{ 0x00, 0x3E, 0x20, 0x20, 0x3C, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // 5
{ 0x00, 0x1C, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // 6
{ 0x00, 0x3E, 0x02, 0x02, 0x04, 0x08, 0x08, 0x08, 0x00, 0x00 }, // 7
{ 0x00, 0x1C, 0x22, 0x22, 0x1C, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // 8
{ 0x00, 0x1C, 0x22, 0x22, 0x1E, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // 9
{ 0x00, 0x00, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00 }, // :
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ;
{ 0x00, 0x04, 0x08, 0x10, 0x20, 0x10, 0x08, 0x04, 0x00, 0x00 }, // <
{ 0x00, 0x00, 0x00, 0x3E, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00 }, // =
{ 0x00, 0x10, 0x08, 0x04, 0x02, 0x04, 0x08, 0x10, 0x00, 0x00 }, // >
{ 0x00, 0x1C, 0x22, 0x02, 0x04, 0x08, 0x00, 0x08, 0x00, 0x00 }, // ?
{ 0x00, 0x1C, 0x26, 0x2A, 0x2A, 0x26, 0x20, 0x1C, 0x00, 0x00 }, // @
{ 0x00, 0x1C, 0x22, 0x22, 0x22, 0x3E, 0x22, 0x22, 0x00, 0x00 }, // A
{ 0x00, 0x3C, 0x22, 0x22, 0x3C, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // B
{ 0x00, 0x1C, 0x22, 0x20, 0x20, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // C
{ 0x00, 0x3C, 0x22, 0x22, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // D
{ 0x00, 0x3E, 0x20, 0x20, 0x3C, 0x20, 0x20, 0x3E, 0x00, 0x00 }, // E
{ 0x00, 0x3E, 0x20, 0x20, 0x3C, 0x20, 0x20, 0x20, 0x00, 0x00 }, // F
{ 0x00, 0x1C, 0x22, 0x20, 0x2E, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // G
{ 0x00, 0x22, 0x22, 0x22, 0x3E, 0x22, 0x22, 0x22, 0x00, 0x00 }, // H
{ 0x00, 0x3E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x3E, 0x00, 0x00 }, // I
{ 0x00, 0x02, 0x02, 0x02, 0x02, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // J
{ 0x00, 0x22, 0x24, 0x28, 0x30, 0x28, 0x24, 0x22, 0x00, 0x00 }, // K
{ 0x00, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3E, 0x00, 0x00 }, // L
{ 0x00, 0x22, 0x36, 0x2A, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00 }, // M
{ 0x00, 0x22, 0x22, 0x32, 0x2A, 0x26, 0x22, 0x22, 0x00, 0x00 }, // N
{ 0x00, 0x1C, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // O
{ 0x00, 0x3C, 0x22, 0x22, 0x3C, 0x20, 0x20, 0x20, 0x00, 0x00 }, // P
{ 0x00, 0x1C, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1C, 0x06, 0x00 }, // Q
{ 0x00, 0x3C, 0x22, 0x22, 0x3C, 0x22, 0x22, 0x22, 0x00, 0x00 }, // R
{ 0x00, 0x1C, 0x22, 0x20, 0x1C, 0x02, 0x22, 0x1C, 0x00, 0x00 }, // S
{ 0x00, 0x3E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00 }, // T
{ 0x00, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // U
{ 0x00, 0x22, 0x22, 0x22, 0x22, 0x14, 0x14, 0x08, 0x00, 0x00 }, // V
{ 0x00, 0x22, 0x22, 0x22, 0x22, 0x2A, 0x36, 0x22, 0x00, 0x00 }, // W
{ 0x00, 0x22, 0x22, 0x14, 0x08, 0x14, 0x22, 0x22, 0x00, 0x00 }, // X
{ 0x00, 0x22, 0x22, 0x14, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00 }, // Y
{ 0x00, 0x3E, 0x02, 0x04, 0x08, 0x10, 0x20, 0x3E, 0x00, 0x00 }, // Z
{ 0x00, 0x0C, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0C, 0x00, 0x00 }, // [
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // backslash (not drawn in source font)
{ 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)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // _ (not drawn in source font)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ` (not drawn in source font)
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // a
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x00, 0x00 }, // b
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x20, 0x22, 0x1C, 0x00, 0x00 }, // c
{ 0x00, 0x02, 0x02, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // d
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x3E, 0x20, 0x1C, 0x00, 0x00 }, // e
{ 0x00, 0x0C, 0x12, 0x10, 0x3C, 0x10, 0x10, 0x10, 0x00, 0x00 }, // f
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x1C }, // g
{ 0x00, 0x20, 0x20, 0x3C, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00 }, // h
{ 0x00, 0x08, 0x00, 0x18, 0x08, 0x08, 0x08, 0x3E, 0x00, 0x00 }, // i
{ 0x00, 0x02, 0x00, 0x06, 0x02, 0x02, 0x02, 0x02, 0x22, 0x1C }, // j
{ 0x00, 0x20, 0x20, 0x22, 0x24, 0x38, 0x24, 0x22, 0x00, 0x00 }, // k
{ 0x00, 0x30, 0x10, 0x10, 0x10, 0x10, 0x10, 0x0E, 0x00, 0x00 }, // l
{ 0x00, 0x00, 0x00, 0x3C, 0x2A, 0x2A, 0x2A, 0x2A, 0x00, 0x00 }, // m
{ 0x00, 0x00, 0x00, 0x3C, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00 }, // n
{ 0x00, 0x00, 0x00, 0x1C, 0x22, 0x22, 0x22, 0x1C, 0x00, 0x00 }, // o
{ 0x00, 0x00, 0x00, 0x3C, 0x22, 0x22, 0x22, 0x3C, 0x20, 0x20 }, // p
{ 0x00, 0x00, 0x00, 0x1E, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x02 }, // q
{ 0x00, 0x00, 0x00, 0x2C, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00 }, // r
{ 0x00, 0x00, 0x00, 0x1E, 0x20, 0x1C, 0x02, 0x3C, 0x00, 0x00 }, // s
{ 0x00, 0x10, 0x10, 0x3C, 0x10, 0x10, 0x10, 0x0E, 0x00, 0x00 }, // t
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x1E, 0x00, 0x00 }, // u
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x14, 0x08, 0x00, 0x00 }, // v
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x2A, 0x2A, 0x14, 0x00, 0x00 }, // w
{ 0x00, 0x00, 0x00, 0x22, 0x14, 0x08, 0x14, 0x22, 0x00, 0x00 }, // x
{ 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x1E, 0x02, 0x1C }, // y
{ 0x00, 0x00, 0x00, 0x3E, 0x04, 0x08, 0x10, 0x3E, 0x00, 0x00 }, // z
{ 0x00, 0x04, 0x08, 0x08, 0x10, 0x08, 0x08, 0x04, 0x00, 0x00 }, // {
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // | (not drawn in source font)
{ 0x00, 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10, 0x00, 0x00 }, // }
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ~ (not drawn in source font)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // unused trailing tile
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // unused trailing tile
};
errorret_t fontInitDefault(void) {
const int32_t width = (int32_t)mathNextPowTwo(
FONT_DEFAULT_COLUMNS * FONT_DEFAULT_TILE_WIDTH
);
const int32_t height = (int32_t)mathNextPowTwo(
FONT_DEFAULT_ROWS * FONT_DEFAULT_TILE_HEIGHT
);
color_t *pixels = memoryAllocate(sizeof(color_t) * width * height);
memoryZero(pixels, sizeof(color_t) * width * height);
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 tileY = (i / FONT_DEFAULT_COLUMNS) * FONT_DEFAULT_TILE_HEIGHT;
for(uint8_t row = 0; row < FONT_DEFAULT_TILE_HEIGHT; row++) {
const uint8_t bits = FONT_DEFAULT_GLYPHS[i][row];
for(uint8_t col = 0; col < FONT_DEFAULT_TILE_WIDTH; col++) {
if(!((bits >> (FONT_DEFAULT_TILE_WIDTH - 1 - col)) & 1)) continue;
pixels[((tileY + row) * width) + (tileX + col)] = COLOR_WHITE;
}
}
}
FONT_DEFAULT_TILESET.tileWidth = FONT_DEFAULT_TILE_WIDTH;
FONT_DEFAULT_TILESET.tileHeight = FONT_DEFAULT_TILE_HEIGHT;
FONT_DEFAULT_TILESET.columns = FONT_DEFAULT_COLUMNS;
FONT_DEFAULT_TILESET.rows = FONT_DEFAULT_ROWS;
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[1] = (float_t)FONT_DEFAULT_TILE_HEIGHT / (float_t)height;
const texturedata_t data = { .rgbaColors = pixels };
errorret_t textureResult = textureInit(
&FONT_DEFAULT_TEXTURE, width, height, TEXTURE_FORMAT_RGBA, data
);
memoryFree(pixels);
errorChain(textureResult);
FONT_DEFAULT.texture = &FONT_DEFAULT_TEXTURE;
FONT_DEFAULT.tileset = &FONT_DEFAULT_TILESET;
errorOk();
}
errorret_t fontDisposeDefault(void) {
errorChain(textureDispose(&FONT_DEFAULT_TEXTURE));
FONT_DEFAULT.texture = NULL;
FONT_DEFAULT.tileset = NULL;
errorOk();
}
+51
View File
@@ -6,6 +6,7 @@
*/
#pragma once
#include "error/error.h"
#include "display/texture/texture.h"
#include "display/texture/tileset.h"
@@ -13,3 +14,53 @@ typedef struct {
texture_t *texture;
tileset_t *tileset;
} font_t;
/**
* Pixel width/height of a single default-font glyph tile. Matches the
* glyph grid baked into the (now retired) ui/minogram.png + .dtf asset
* pair this data was extracted from.
*/
#define FONT_DEFAULT_TILE_WIDTH 6
#define FONT_DEFAULT_TILE_HEIGHT 10
/** Grid layout of the generated default-font texture, in tiles. */
#define FONT_DEFAULT_COLUMNS 16
#define FONT_DEFAULT_ROWS 6
/**
* Number of glyphs defined in FONT_DEFAULT_GLYPHS (FONT_DEFAULT_COLUMNS *
* FONT_DEFAULT_ROWS), covering the printable ASCII range starting at
* TEXT_CHAR_START ('!') plus a couple of unused trailing tiles.
*/
#define FONT_DEFAULT_TILE_COUNT (FONT_DEFAULT_COLUMNS * FONT_DEFAULT_ROWS)
extern font_t FONT_DEFAULT;
/**
* Hard coded bitmap data for the built-in default font, extracted
* pixel-for-pixel from the original ui/minogram.png glyph atlas (alpha
* >= 128 counts as set). Indexed [glyph][row], where glyph 0 corresponds
* to TEXT_CHAR_START ('!') and glyphs run consecutively through the
* printable ASCII range. Each row byte holds FONT_DEFAULT_TILE_WIDTH bit
* flags, one per pixel column: bit (FONT_DEFAULT_TILE_WIDTH - 1) is the
* leftmost pixel and bit 0 is the rightmost; 1 means the pixel is set,
* 0 means it is not.
*/
extern const uint8_t FONT_DEFAULT_GLYPHS[FONT_DEFAULT_TILE_COUNT][
FONT_DEFAULT_TILE_HEIGHT
];
/**
* Builds the built-in default font (texture + tileset) directly from
* FONT_DEFAULT_GLYPHS, without going through the asset system.
*
* @return Either an error or success result.
*/
errorret_t fontInitDefault(void);
/**
* Disposes of the built-in default font created by fontInitDefault.
*
* @return Either an error or success result.
*/
errorret_t fontDisposeDefault(void);

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