159 Commits

Author SHA1 Message Date
YourWishes b639bc6c4f Reimplement the archived UI widget stack on the new element-tree system
The old widget system (archive/dusk/ui/) depended on infrastructure this
rewrite deleted -- a static X-macro element list, a 9-slice UI_FRAME, and
a global gamepad/keyboard focus stack -- so everything below is rebuilt
on top of the new native uielement_t pool + parent/child tree instead,
gamepad/keyboard-only (no mouse support exists in the input system).

New JS widgets (assets/scripts/), all pure composites of Label/Rectangle
following the Button.js pattern: Checkbox, Tab, Slider, Dropdown. Slider/
Dropdown expose a directionInput(dx, dy) hook so a menu can hand them
LEFT/RIGHT before falling back to cursor movement.

New Menu.js replaces the old global uifocus_t stack: a small push/pop
stack of Menu instances where only the topmost consumes CANCEL/ACCEPT/
direction input each tick (needed for nested modals -- a Settings
sub-page menu plus a "discard changes?" Confirm can be open at once).
Held-direction repeat timing matches the old 0.5s delay / 0.1s repeat.

New overlay composites (added via a new UI.addOverlay()/UI.removeOverlay(),
always drawn/updated after normal roots): FpsCounter, ConsoleOverlay
(one Label per console history line, driven directly rather than via
add() since History (16) exceeds the 8-children-per-element cap), Crop
(letterbox/pillarbox bars), and Fullbox (a reusable tweened full-screen
fade covering both the old fullbox and transition effects -- reuses
shared instances rather than allocate-and-dispose, since disposing an
element from inside its own render() callback risks the same JerryScript
refcount corruption hit earlier in this rewrite).

New Confirm.js (Yes/No dialog) and Settings.js (+ SettingsGeneral/
SettingsInput sub-pages) built on Menu. Display/Audio settings pages are
intentionally not ported -- neither had a real backing engine system
even in the old code. Frame is a flat Rectangle for now, not real 9-slice
(a genuinely bigger native lift, deliberately deferred).

Small native binding additions needed by the above, each with its own
unit test: Time.renderDelta, Console.lineCount/getLine/visible/
consumeDirty, a new Screen module, a new Locale module, Input.deadzone,
a new Save module, and Label.color (was missing entirely). Also fixes
a real gap from the UI.addOverlay() work: uiElementDispose() wasn't
removing disposed elements from the new overlay root array, which would
have left dangling ids behind.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 09:05:11 -05:00
YourWishes 7ee04c78cd Rebuild UI as a scriptable element tree, archive the old system
The old UI system (X-macro static element list, hand-authored C
screens/widgets/focus stack) is archived under archive/ rather than
deleted, since it's a useful reference during the rewrite.

New native UI element pool (src/dusk/ui): a flat UI_ELEMENTS[128] pool
of tagged-union elements (Label, Rectangle, Scripted), a real
persistent parent/child tree (children[8] per element, cycle- and
capacity-checked uiElementSetParent), always-fresh worldX/worldY
(cheap enough to recompute on every read, no dirty-flag cache needed),
and cascading dispose. Rendering stays manual/immediate: a scripted
element with no render() override auto-renders its children by
default, but overriding render() takes full control (an override must
call renderChildren() itself to opt back in) -- this is deliberately
preserved end to end via a render()-shadow trampoline so overriding
render() always keeps working the same way regardless of how a node
is reached.

New scripting layer (src/dusk/script/module/ui): UIElement/Label/
Rectangle JS classes (Label/Rectangle share UIElement's prototype via
manual chaining, not JS `extends`), exposing x/y/worldX/worldY/parent/
add()/remove()/render()/renderChildren()/dispose(). UI.add()/
UI.remove() manage top-level render roots, mutually exclusive with
being someone's child.

Also: Scene gains a lateUpdate() hook (called once per frame after
every other update, for things like camera-follow that need to react
to where everything else ended up); several duskrpg call sites
(cutscene items, entityinteractable, entityplayer) that depended on
the now-archived RPG textbox are stubbed to console output instead of
a dialogue box, pending the new UI reaching that far.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 11:13:23 -05:00
YourWishes 7b58addf7e Prepping UI overhaul 2026-08-11 23:33:29 -05:00
YourWishes ae52be591b Add Input/InputBind/InputButton JS bindings, move default binds to JS
Adds a new script module exposing Input.bind/value/lastValue/isDown/
wasDown/pressed/released, InputBind.* (the inputbind_t action enum),
and InputButton.* (every named button in the compiled platform's
INPUT_BUTTON_DATA table, e.g. InputButton.SELECT on PSP).

Renames the PLATFORM global to Platform.current for consistency with
Time/Console/Input.

Uppercases every INPUT_BUTTON_DATA .name across inputlinux.c/
inputpsp.c/inputdolphin.c to match the InputButton.* JS constants
(inputButtonGetByName was already case-insensitive, so this doesn't
change matching behavior).

Moves the default key/button-to-action bindings out of
src/duskrpg/input/inputbindmap.h (deleted) and into
assets/scripts/input.js, branching on Platform.current instead of the
old per-platform #ifdefs. Wired in via require('./input.js') from
init.js.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 16:03:32 -05:00
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
YourWishes 556111c00a Merge pull request 'Gitea actions' (#5) from gitea-actions into main
Build Dusk / run-tests (push) Successful in 5m39s
Build Dusk / build-linux (push) Successful in 5m20s
Build Dusk / build-psp (push) Successful in 1m22s
Build Dusk / build-knulli (push) Successful in 3m51s
Build Dusk / build-gamecube (push) Successful in 3m27s
Build Dusk / build-gamecube-iso (push) Successful in 3m25s
Build Dusk / build-wii (push) Successful in 3m2s
Build Dusk / build-wii-iso (push) Successful in 3m7s
Reviewed-on: #5
2026-06-26 13:39:21 -05:00
YourWishes ebc7110e63 Restrict CI trigger to tags only
Remove gitea-actions branch trigger now that the runner setup is stable.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 13:37:28 -05:00
YourWishes af49d1c8bb Restore all builds; update gamecube/wii/wii-iso to use container
Build Dusk / run-tests (push) Successful in 5m44s
Build Dusk / build-linux (push) Successful in 5m10s
Build Dusk / build-psp (push) Successful in 1m27s
Build Dusk / build-knulli (push) Successful in 3m51s
Build Dusk / build-gamecube (push) Successful in 3m15s
Build Dusk / build-gamecube-iso (push) Successful in 3m25s
Build Dusk / build-wii (push) Successful in 3m5s
Build Dusk / build-wii-iso (push) Successful in 3m1s
All jobs re-enabled except vita. gamecube, wii, and wii-iso now use
the ghcr.io/extremscorner/libogc2 container with Node.js pre-installed,
matching the working gamecube-iso pattern.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:49:33 -05:00
YourWishes c71dbb1dfc Enable build-knulli using debian:trixie container
Build Dusk / build-knulli (push) Successful in 3m59s
Build Dusk / build-gamecube-iso (push) Successful in 3m11s
Runs the job inside debian:trixie (same as the Dockerfile) with
Node.js pre-installed before checkout. Installs arm64 cross-compilation
deps and runs build-knulli.sh directly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:43:13 -05:00
YourWishes 432aa3c4fa Fix gamecube-iso container: install Node.js before checkout
Build Dusk / build-gamecube-iso (push) Successful in 3m36s
actions/checkout requires Node.js. Install it via apt as a plain shell
step (no Node needed) before the checkout action runs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:17:30 -05:00
YourWishes 5c93503710 Fix gamecube-iso: use docker run instead of job container
Build Dusk / build-gamecube-iso (push) Failing after 5s
actions/checkout requires Node.js which the libogc2 container lacks.
Checkout on the runner, then run the full build inside the container
via docker run with the workspace mounted.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:16:21 -05:00
YourWishes 0d58050def Switch gamecube-iso to run inside extremscorner/libogc2 container
Build Dusk / build-gamecube-iso (push) Failing after 4m0s
Avoids devkitPro apt server rate-limiting in CI by using the pre-built
ghcr.io/extremscorner/libogc2 container (same base as the Dockerfile).
Toolchain is already installed; only apt/dkp extras are added per-run.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:10:43 -05:00
YourWishes 27bb78209a Debug devkitPro install: print installer script before running
Build Dusk / build-gamecube-iso (push) Failing after 1m11s
Print the installer script contents in CI log so we can see what URLs
it tries to fetch. Also add /etc/mtab symlink as the devkitPro base
Docker image does.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:04:00 -05:00
YourWishes 3201f5a25b Fix devkitPro install by setting up apt repo manually
Build Dusk / build-gamecube-iso (push) Failing after 1m14s
The installer script exits with code 8 on Ubuntu. Replace with manual
GPG key + apt source setup followed by apt-get install devkitpro-pacman.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 11:53:26 -05:00
YourWishes d3df8a96d3 Add setup-pspdev and setup-devkitpro composite actions; enable gamecube-iso
Build Dusk / build-gamecube-iso (push) Failing after 1m9s
Extracts toolchain setup into reusable composite actions under
.github/actions/. Comments out build-psp, adds build-gamecube-iso
job using the new setup-devkitpro action directly on the runner.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 11:51:06 -05:00
YourWishes 7ec5266b1f Disabled other actions for now
Build Dusk / build-psp (push) Successful in 1m27s
2026-06-26 11:42:50 -05:00
YourWishes e74ff7c805 Add cmake to PSP runner dependencies
Build Dusk / build-linux (push) Has been cancelled
Build Dusk / build-psp (push) Has been cancelled
Build Dusk / build-knulli (push) Has been cancelled
Build Dusk / build-gamecube (push) Has been cancelled
Build Dusk / build-gamecube-iso (push) Has been cancelled
Build Dusk / build-wii (push) Has been cancelled
Build Dusk / build-wii-iso (push) Has been cancelled
Build Dusk / run-tests (push) Has been cancelled
The pspdev/pspdev base image bundles cmake; the bare runner needs it
installed explicitly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 11:40:18 -05:00
YourWishes 1d5f3c2959 Update PSP job to build directly on runner
Build Dusk / run-tests (push) Successful in 5m20s
Build Dusk / build-linux (push) Successful in 5m6s
Build Dusk / build-psp (push) Failing after 53s
Build Dusk / build-knulli (push) Failing after 51s
Build Dusk / build-gamecube (push) Failing after 43s
Build Dusk / build-gamecube-iso (push) Failing after 43s
Build Dusk / build-wii (push) Failing after 45s
Build Dusk / build-wii-iso (push) Failing after 48s
Replaces Docker build with direct pspdev toolchain installation from
GitHub releases and runs build-psp.sh natively on the Ubuntu runner.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:55:52 -05:00
YourWishes 469034b223 Fix action versions for Gitea compatibility
Build Dusk / run-tests (push) Successful in 5m43s
Build Dusk / build-linux (push) Successful in 5m25s
Build Dusk / build-knulli (push) Has been cancelled
Build Dusk / build-gamecube (push) Has been cancelled
Build Dusk / build-gamecube-iso (push) Has been cancelled
Build Dusk / build-wii (push) Has been cancelled
Build Dusk / build-wii-iso (push) Has been cancelled
Build Dusk / build-psp (push) Has been cancelled
Downgrade upload-artifact to v3 (v4+ not supported on GHES/Gitea).
Fix checkout from non-existent v6 to v4.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:55:00 -05:00
YourWishes f3a394de21 Update CI to build tests and Linux directly on runner
Build Dusk / run-tests (push) Successful in 5m41s
Build Dusk / build-linux (push) Failing after 5m10s
Build Dusk / build-psp (push) Failing after 44s
Build Dusk / build-knulli (push) Failing after 45s
Build Dusk / build-gamecube (push) Failing after 57s
Build Dusk / build-gamecube-iso (push) Failing after 1m3s
Build Dusk / build-wii (push) Failing after 39s
Build Dusk / build-wii-iso (push) Failing after 35s
Replaces Docker-based builds for run-tests and build-linux jobs with
direct apt-get dependency installation and inner build scripts.
Also triggers on pushes to gitea-actions branch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:41:38 -05:00
YourWishes cb23d4c11b Add missing assert on backpack 2026-06-26 10:38:57 -05:00
YourWishes bbf5b706f0 Cutscene combined 2026-06-26 10:24:39 -05:00
YourWishes 1e890f6d86 Backpack changes 2026-06-26 09:04:57 -05:00
YourWishes 2fe543a603 UI Transition 2026-06-26 08:44:26 -05:00
YourWishes 24631990bd Fixed dolphin aspect ratio 2026-06-25 22:47:23 -05:00
YourWishes 0c8c0d24ba fix chunk loading based on player position 2026-06-25 22:29:13 -05:00
YourWishes 454b8a91ba Fixed dolphin ratioing 2026-06-25 22:21:12 -05:00
YourWishes a74f1568e9 Small improvements to performance 2026-06-25 21:30:44 -05:00
YourWishes 3f35d56be4 UI Frame finally doing things 2026-06-25 20:58:44 -05:00
YourWishes 722fe2ccfb Some label fixes 2026-06-25 19:56:14 -05:00
YourWishes d85737cc08 UI menu 2026-06-25 19:35:33 -05:00
YourWishes ce29435831 Example settings more or less done, showing full ui example basically. 2026-06-25 18:34:49 -05:00
YourWishes d3715eece8 Time and tick helpers 2026-06-25 18:16:46 -05:00
YourWishes 335d79f2c4 NUked archive 2026-06-25 18:01:11 -05:00
YourWishes a9e33660cb UI Frame 2026-06-25 15:33:17 -05:00
YourWishes 8faf881399 Bit if UI cleanup 2026-06-25 14:56:48 -05:00
YourWishes c4969a36cc Add UI cropping 2026-06-25 12:13:04 -05:00
YourWishes 26fcaf6e75 Restored some stuff 2026-06-25 11:53:15 -05:00
897 changed files with 44044 additions and 16680 deletions
@@ -0,0 +1,49 @@
name: Setup devkitPro
description: Install devkitPro with GameCube/Wii packages on an Ubuntu runner
runs:
using: composite
steps:
- name: Install apt dependencies
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y \
cmake \
python3 \
python3-pip \
python3-polib \
python3-pil \
python3-dotenv \
python3-pyqt5 \
python3-opengl \
xorriso
- name: Install devkitPro pacman
shell: bash
run: |
sudo ln -sf /proc/self/mounts /etc/mtab
wget https://apt.devkitpro.org/install-devkitpro-pacman \
-O /tmp/install-devkitpro-pacman
echo "=== installer script contents ==="
cat /tmp/install-devkitpro-pacman
echo "================================="
chmod +x /tmp/install-devkitpro-pacman
sudo /tmp/install-devkitpro-pacman
echo "DEVKITPRO=/opt/devkitpro" >> $GITHUB_ENV
echo "DEVKITPPC=/opt/devkitpro/devkitPPC" >> $GITHUB_ENV
echo "/opt/devkitpro/tools/bin" >> $GITHUB_PATH
echo "/opt/devkitpro/devkitPPC/bin" >> $GITHUB_PATH
- name: Install devkitPro GameCube/Wii packages
shell: bash
run: |
sudo dkp-pacman -S --needed --noconfirm \
gamecube-dev \
gamecube-sdl2 \
ppc-liblzma \
ppc-libzip \
libogc2 \
gamecube-tools \
ppc-libmad \
ppc-zlib-ng \
ppc-bzip2 \
ppc-zstd
+20
View File
@@ -0,0 +1,20 @@
name: Setup pspdev
description: Install the pspdev PSP toolchain on an Ubuntu runner
runs:
using: composite
steps:
- name: Install dependencies
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y cmake python3 python3-pip python3-dotenv
- name: Install pspdev toolchain
shell: bash
run: |
wget -q \
https://github.com/pspdev/pspdev/releases/latest/download/pspdev-ubuntu-latest-x86_64.tar.gz \
-O /tmp/pspdev.tar.gz
sudo tar -xzf /tmp/pspdev.tar.gz -C /usr/local
echo "PSPDEV=/usr/local/pspdev" >> $GITHUB_ENV
echo "/usr/local/pspdev/bin" >> $GITHUB_PATH
+142 -69
View File
@@ -4,27 +4,37 @@ on:
tags:
- '*'
jobs:
run-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
- name: Run tests in Docker
run: ./scripts/test-linux-docker.sh
build-linux:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
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: Build Linux
run: ./scripts/build-linux-docker.sh
run: ./scripts/build-linux.sh
- name: Upload Linux binary
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v3
with:
name: dusk-linux
path: build-linux/Dusk
@@ -34,53 +44,72 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
- name: Build psp
run: ./scripts/build-psp-docker.sh
uses: actions/checkout@v4
- name: Setup pspdev
uses: ./.github/actions/setup-pspdev
- name: Build PSP
run: ./scripts/build-psp.sh
- name: Move EBOOT.PBP to Dusk subfolder
run: |
mkdir -p ./git-artifcats/Dusk/PSP/GAME/Dusk
cp build-psp/EBOOT.PBP ./git-artifcats/Dusk/PSP/GAME/Dusk/EBOOT.PBP
- name: Upload psp binary
uses: actions/upload-artifact@v6
- name: Upload PSP binary
uses: actions/upload-artifact@v3
with:
name: dusk-psp
path: ./git-artifcats/Dusk
if-no-files-found: error
# build-vita:
# runs-on: ubuntu-latest
# steps:
# - name: Checkout repository
# uses: actions/checkout@v6
# - name: Set up Docker
# uses: docker/setup-docker-action@v5
# - name: Build Vita
# run: ./scripts/build-vita-docker.sh
# - name: Upload Vita binary
# uses: actions/upload-artifact@v6
# with:
# name: dusk-vita
# path: build-vita/Dusk.vpk
# if-no-files-found: error
build-knulli:
runs-on: ubuntu-latest
container:
image: debian:trixie
steps:
- name: Install Node.js
run: apt-get update && apt-get install -y nodejs
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
- name: Build knulli
run: ./scripts/build-knulli-docker.sh
uses: actions/checkout@v4
- name: Install dependencies
run: |
dpkg --add-architecture arm64
apt-get update
apt-get install -y --no-install-recommends \
crossbuild-essential-arm64 \
ca-certificates \
pkg-config \
cmake \
make \
ninja-build \
git \
file \
python3 \
python3-pip \
python3-polib \
python3-pil \
python3-dotenv \
python3-pyqt5 \
python3-opengl \
liblua5.4-dev:arm64 \
xz-utils:arm64 \
libbz2-dev:arm64 \
zlib1g-dev:arm64 \
libzip-dev:arm64 \
libssl-dev:arm64 \
libsdl2-dev:arm64 \
liblzma-dev:arm64 \
libopengl0:arm64 \
libgl1:arm64 \
libegl1:arm64 \
libgles2:arm64 \
libgl1-mesa-dev:arm64
- name: Build Knulli
run: ./scripts/build-knulli.sh
- name: Move output to Dusk subfolder
run: |
mkdir -p ./git-artifcats/Dusk
cp -r build-knulli/dusk ./git-artifcats/Dusk
- name: Upload knulli binary
uses: actions/upload-artifact@v6
- name: Upload Knulli binary
uses: actions/upload-artifact@v3
with:
name: dusk-knulli
path: ./git-artifcats/Dusk
@@ -88,20 +117,31 @@ jobs:
build-gamecube:
runs-on: ubuntu-latest
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@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
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
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
run: ./scripts/build-gamecube-docker.sh
- name: Copy output files.
run: ./scripts/build-gamecube.sh
- name: Copy output files
run: |
mkdir -p ./git-artifcats/Dusk
cp build-gamecube/Dusk.dol ./git-artifcats/Dusk/Dusk.dol
cp build-gamecube/dusk.dsk ./git-artifcats/Dusk/dusk.dsk
- name: Upload GameCube binary
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v3
with:
name: dusk-gamecube
path: ./git-artifcats/Dusk
@@ -109,21 +149,32 @@ jobs:
build-gamecube-iso:
runs-on: ubuntu-latest
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@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
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
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
run: ./scripts/build-gamecube-iso-docker.sh
- name: Copy output files.
run: ./scripts/build-gamecube-iso.sh
- name: Copy output files
run: |
mkdir -p ./git-artifcats/Dusk
cp build-gamecube-iso/Dusk-NTSC-J.iso ./git-artifcats/Dusk/Dusk-NTSC-J.iso
cp build-gamecube-iso/Dusk-NTSC-U.iso ./git-artifcats/Dusk/Dusk-NTSC-U.iso
cp build-gamecube-iso/Dusk-PAL.iso ./git-artifcats/Dusk/Dusk-PAL.iso
- name: Upload GameCube ISO
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v3
with:
name: dusk-gamecube-iso
path: ./git-artifcats/Dusk
@@ -131,21 +182,32 @@ jobs:
build-wii:
runs-on: ubuntu-latest
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@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
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
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
run: ./scripts/build-wii-docker.sh
- name: Copy output files.
run: ./scripts/build-wii.sh
- name: Copy output files
run: |
mkdir -p ./git-artifcats/Dusk/apps/Dusk
cp build-wii/boot.dol ./git-artifcats/Dusk/apps/Dusk/boot.dol
cp build-wii/dusk.dsk ./git-artifcats/Dusk/apps/Dusk/dusk.dsk
cp build-wii/meta.xml ./git-artifcats/Dusk/apps/Dusk/meta.xml
- name: Upload Wii binary
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v3
with:
name: dusk-wii
path: ./git-artifcats/Dusk
@@ -153,21 +215,32 @@ jobs:
build-wii-iso:
runs-on: ubuntu-latest
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@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
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
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
run: ./scripts/build-wii-iso-docker.sh
- name: Copy output files.
run: ./scripts/build-wii-iso.sh
- name: Copy output files
run: |
mkdir -p ./git-artifcats/Dusk
cp build-wii-iso/Dusk-NTSC-J.iso ./git-artifcats/Dusk/Dusk-NTSC-J.iso
cp build-wii-iso/Dusk-NTSC-U.iso ./git-artifcats/Dusk/Dusk-NTSC-U.iso
cp build-wii-iso/Dusk-PAL.iso ./git-artifcats/Dusk/Dusk-PAL.iso
- name: Upload Wii ISO
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v3
with:
name: dusk-wii-iso
path: ./git-artifcats/Dusk
+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`.
+13 -3
View File
@@ -13,10 +13,10 @@ cmake_policy(SET CMP0079 NEW)
# set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
option(DUSK_BUILD_TESTS "Enable tests" OFF)
option(DUSK_NETWORKING "Enable networking support" OFF)
# Game identity — override these per-project
set(DUSK_GAME_NAME "Dusk" CACHE STRING "Game display name")
set(DUSK_GAME_AUTHOR "YouWish" CACHE STRING "Game author / coder")
set(DUSK_GAME_AUTHOR "YourWishes" CACHE STRING "Game author / coder")
set(DUSK_GAME_SHORT_DESCRIPTION "Dusk game" CACHE STRING "One-line description")
set(DUSK_GAME_LONG_DESCRIPTION "No description yet." CACHE STRING "Full description")
@@ -91,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)
@@ -117,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}"
-12
View File
@@ -1,12 +0,0 @@
import sys, os
import argparse
# Check if the script is run with the correct arguments
parser = argparse.ArgumentParser(description="Generate chunk header files")
parser.add_argument('--assets', required=True, help='Dir to output built assets')
parser.add_argument('--headers-dir', required=True, help='Directory to output individual asset headers (required for header build)')
parser.add_argument('--output-headers', help='Output header file for built assets (required for header build)')
parser.add_argument('--output-assets', required=True, help='Output directory for built assets')
parser.add_argument('--output-file', required=True, help='Output file for built assets (required for wad build)')
parser.add_argument('--input', required=True, help='Input assets to process', nargs='+')
args = parser.parse_args()
-66
View File
@@ -1,66 +0,0 @@
import sys, os
from tools.asset.args import args
from tools.asset.process.asset import processAsset
from tools.asset.process.palette import processPaletteList
from tools.asset.process.tileset import processTilesetList
from tools.asset.process.language import processLanguageList
from tools.asset.path import getBuiltAssetsRelativePath
import zipfile
# Parse input file args.
inputAssets = []
for inputArg in args.input:
files = inputArg.split('$')
for file in files:
if str(file).strip() == '':
continue
pieces = file.split('#')
if len(pieces) < 2:
print(f"Error: Invalid input asset format '{file}'. Expected format: type#path[#option1%option2...]")
sys.exit(1)
options = {}
if len(pieces) > 2:
optionParts = pieces[2].split('%')
for part in optionParts:
partSplit = part.split('=')
if len(partSplit) < 1:
continue
if len(partSplit) == 2:
options[partSplit[0]] = partSplit[1]
else:
options[partSplit[0]] = True
inputAssets.append({
'type': pieces[0],
'path': pieces[1],
'options': options
})
if not inputAssets:
print("Error: No input assets provided.")
sys.exit(1)
# Process each asset.
files = []
for asset in inputAssets:
asset = processAsset(asset)
files.extend(asset['files'])
# Generate additional files
files.extend(processLanguageList()['files'])
# Take assets and add to a zip archive.
outputFileName = args.output_file
print(f"Creating output file: {outputFileName}")
with zipfile.ZipFile(outputFileName, 'w') as zipf:
for file in files:
relativeOutputPath = getBuiltAssetsRelativePath(file)
zipf.write(file, arcname=relativeOutputPath)
# Generate additional headers.
processPaletteList()
processTilesetList()
-12
View File
@@ -1,12 +0,0 @@
processedAssets = {}
def assetGetCache(assetPath):
if assetPath in processedAssets:
return processedAssets[assetPath]
return None
def assetCache(assetPath, processedData):
if assetPath in processedAssets:
return processedAssets[assetPath]
processedAssets[assetPath] = processedData
return processedData
-10
View File
@@ -1,10 +0,0 @@
import os
from tools.asset.args import args
def getAssetRelativePath(fullPath):
# Get the relative path to the asset
return os.path.relpath(fullPath, start=args.assets).replace('\\', '/')
def getBuiltAssetsRelativePath(fullPath):
# Get the relative path to the built asset
return os.path.relpath(fullPath, start=args.output_assets).replace('\\', '/')
-33
View File
@@ -1,33 +0,0 @@
import sys
# from processtileset import processTileset
from tools.asset.process.image import processImage
from tools.asset.process.palette import processPalette
from tools.asset.process.tileset import processTileset
from tools.asset.process.map import processMap
from tools.asset.process.language import processLanguage
from tools.asset.process.script import processScript
processedAssets = []
def processAsset(asset):
if asset['path'] in processedAssets:
return
processedAssets.append(asset['path'])
# Handle tiled tilesets
t = asset['type'].lower()
if t == 'palette':
return processPalette(asset)
elif t == 'image':
return processImage(asset)
elif t == 'tileset':
return processTileset(asset)
elif t == 'map':
return processMap(asset)
elif t == 'language':
return processLanguage(asset)
elif t == 'script':
return processScript(asset)
else:
print(f"Error: Unknown asset type '{asset['type']}' for path '{asset['path']}'")
sys.exit(1)
-134
View File
@@ -1,134 +0,0 @@
import os
import sys
from PIL import Image
from tools.asset.process.palette import extractPaletteFromImage, palettes
from tools.asset.args import args
from tools.asset.path import getAssetRelativePath
from tools.asset.cache import assetGetCache, assetCache
images = []
def processImage(asset):
cache = assetGetCache(asset['path'])
if cache is not None:
return cache
type = None
if 'type' in asset['options']:
type = asset['options'].get('type', 'PALETTIZED').upper()
if type == 'PALETTIZED' or type is None:
return assetCache(asset['path'], processPalettizedImage(asset))
elif type == 'ALPHA':
return assetCache(asset['path'], processAlphaImage(asset))
else:
print(f"Error: Unknown image type {type} for asset {asset['path']}")
sys.exit(1)
def processPalettizedImage(asset):
assetPath = asset['path']
cache = assetGetCache(assetPath)
if cache is not None:
return cache
image = Image.open(assetPath)
imagePalette = extractPaletteFromImage(image)
# Find palette that contains every color
palette = None
for p in palettes:
hasAllColors = True
for color in imagePalette:
for palColor in p['pixels']:
if color[0] == palColor[0] and color[1] == palColor[1] and color[2] == palColor[2] and color[3] == palColor[3]:
break
elif color[3] == 0 and palColor[3] == 0:
break
else:
print('Pallete {} does not contain color #{}'.format(p['paletteName'], '{:02x}{:02x}{:02x}{:02x}'.format(color[0], color[1], color[2], color[3])))
hasAllColors = False
break
if hasAllColors:
palette = p
break
if palette is None:
palette = palettes[0] # Just to avoid reference error
print(f"No matching palette found for {assetPath}!")
# Find which pixel is missing
for color in imagePalette:
if color in palette['pixels']:
continue
# Convert to hex (with alpha)
hexColor = '#{:02x}{:02x}{:02x}{:02x}'.format(color[0], color[1], color[2], color[3])
print(f"Missing color: {hexColor} in palette {palette['paletteName']}")
sys.exit(1)
print(f"Converting image {assetPath} to use palette")
paletteIndexes = []
for pixel in list(image.getdata()):
if pixel[3] == 0:
pixel = (0, 0, 0, 0)
paletteIndex = palette['pixels'].index(pixel)
paletteIndexes.append(paletteIndex)
data = bytearray()
data.extend(b"DPI") # Dusk Palettized Image
data.extend(image.width.to_bytes(4, 'little')) # Width
data.extend(image.height.to_bytes(4, 'little')) # Height
data.append(palette['paletteIndex']) # Palette index
for paletteIndex in paletteIndexes:
if paletteIndex > 255 or paletteIndex < 0:
print(f"Error: Palette index {paletteIndex} exceeds 255!")
sys.exit(1)
data.append(paletteIndex.to_bytes(1, 'little')[0]) # Pixel index
relative = getAssetRelativePath(assetPath)
fileNameWithoutExt = os.path.splitext(os.path.basename(assetPath))[0]
outputFileRelative = os.path.join(os.path.dirname(relative), f"{fileNameWithoutExt}.dpi")
outputFilePath = os.path.join(args.output_assets, outputFileRelative)
os.makedirs(os.path.dirname(outputFilePath), exist_ok=True)
with open(outputFilePath, "wb") as f:
f.write(data)
outImage = {
"imagePath": outputFileRelative,
"files": [ outputFilePath ],
'width': image.width,
'height': image.height,
}
return assetCache(assetPath, outImage)
def processAlphaImage(asset):
assetPath = asset['path']
cache = assetGetCache(assetPath)
if cache is not None:
return cache
print(f"Processing alpha image: {assetPath}")
data = bytearray()
data.extend(b"DAI") # Dusk Alpha Image
image = Image.open(assetPath).convert("RGBA")
data.extend(image.width.to_bytes(4, 'little')) # Width
data.extend(image.height.to_bytes(4, 'little')) # Height
for pixel in list(image.getdata()):
# Only write alpha channel
data.append(pixel[3].to_bytes(1, 'little')[0]) # Pixel alpha
relative = getAssetRelativePath(assetPath)
fileNameWithoutExt = os.path.splitext(os.path.basename(assetPath))[0]
outputFileRelative = os.path.join(os.path.dirname(relative), f"{fileNameWithoutExt}.dai")
outputFilePath = os.path.join(args.output_assets, outputFileRelative)
os.makedirs(os.path.dirname(outputFilePath), exist_ok=True)
with open(outputFilePath, "wb") as f:
f.write(data)
outImage = {
"imagePath": outputFileRelative,
"files": [ outputFilePath ],
'width': image.width,
'height': image.height,
}
return assetCache(assetPath, outImage)
-228
View File
@@ -1,228 +0,0 @@
import sys
import os
from tools.asset.args import args
from tools.asset.cache import assetCache, assetGetCache
from tools.asset.path import getAssetRelativePath
from tools.dusk.defs import defs
import polib
import re
LANGUAGE_CHUNK_CHAR_COUNT = int(defs.get('ASSET_LANG_CHUNK_CHAR_COUNT'))
LANGUAGE_DATA = {}
LANGUAGE_KEYS = []
def processLanguageList():
# Language keys header data
headerKeys = "// Auto-generated language keys header file.\n"
headerKeys += "#pragma once\n"
headerKeys += "#include \"dusk.h\"\n\n"
# This is the desired chunk groups list.. if a language key STARTS with any
# of the keys in this list we would "like to" put it in that chunk group.
# If there is no match, or the list is full then we will add it to the next
# available chunk group (that isn't a 'desired' one). If the chunk becomes
# full, then we attempt to make another chunk with the same prefix so that
# a second batching can occur.
desiredChunkGroups = {
'ui': 0
}
# Now, for each language key, create the header reference and index.
keyIndex = 0
languageKeyIndexes = {}
languageKeyChunk = {}
languageKeyChunkIndexes = {}
languageKeyChunkOffsets = {}
for key in LANGUAGE_KEYS:
headerKeys += f"#define {getLanguageVariableName(key)} {keyIndex}\n"
languageKeyIndexes[key] = keyIndex
keyIndex += 1
# Find desired chunk group
assignedChunk = None
for desiredKey in desiredChunkGroups:
if key.lower().startswith(desiredKey):
assignedChunk = desiredChunkGroups[desiredKey]
break
# If no desired chunk group matched, assign to -1
if assignedChunk is None:
assignedChunk = -1
languageKeyChunk[key] = assignedChunk
# Setup header.
for lang in LANGUAGE_DATA:
if key not in LANGUAGE_DATA[lang]:
print(f"Warning: Missing translation for key '{key}' in language '{lang}'")
sys.exit(1)
# Seal the header.
headerKeys += f"\n#define LANG_KEY_COUNT {len(LANGUAGE_KEYS)}\n"
# Now we can generate the language string chunks.
nextChunkIndex = max(desiredChunkGroups.values()) + 1
files = []
for lang in LANGUAGE_DATA:
langData = LANGUAGE_DATA[lang]
# Key = chunkIndex, value = chunkInfo
languageChunks = {}
for key in LANGUAGE_KEYS:
keyIndex = languageKeyIndexes[key]
chunkIndex = languageKeyChunk[key]
wasSetChunk = chunkIndex != -1
# This will keep looping until we find a chunk
while True:
# Determine the next chunkIndex IF chunkIndex is -1
if chunkIndex == -1:
chunkIndex = nextChunkIndex
# Is the chunk full?
curLen = languageChunks.get(chunkIndex, {'len': 0})['len']
newLen = curLen + len(langData[key])
if newLen > LANGUAGE_CHUNK_CHAR_COUNT:
# Chunk is full, need to create a new chunk.
chunkIndex = -1
if wasSetChunk:
wasSetChunk = False
else:
nextChunkIndex += 1
continue
# Chunk is not full, we can use it.
if chunkIndex not in languageChunks:
languageChunks[chunkIndex] = {
'len': 0,
'keys': []
}
languageChunks[chunkIndex]['len'] = newLen
languageChunks[chunkIndex]['keys'].append(key)
languageKeyChunkIndexes[key] = chunkIndex
languageKeyChunkOffsets[key] = curLen
break
# We have now chunked all the keys for this language!
langBuffer = b""
# Write header info
langBuffer += b'DLF' # Dusk Language File
for key in LANGUAGE_KEYS:
# Write the chunk that this key belongs to as uint32_t
chunkIndex = languageKeyChunkIndexes[key]
langBuffer += chunkIndex.to_bytes(4, byteorder='little')
# Write the offset for this key as uint32_t
offset = languageKeyChunkOffsets[key]
langBuffer += offset.to_bytes(4, byteorder='little')
# Write the length of the string as uint32_t
strData = langData[key].encode('utf-8')
langBuffer += len(strData).to_bytes(4, byteorder='little')
# Now write out each chunk's string data, packed tight and no null term.
for chunkIndex in sorted(languageChunks.keys()):
chunkInfo = languageChunks[chunkIndex]
for key in chunkInfo['keys']:
strData = langData[key].encode('utf-8')
langBuffer += strData
# Now pad the chunk to full size
curLen = chunkInfo['len']
if curLen < LANGUAGE_CHUNK_CHAR_COUNT:
padSize = LANGUAGE_CHUNK_CHAR_COUNT - curLen
langBuffer += b'\0' * padSize
# Write out the language data file
outputFile = os.path.join(args.output_assets, "language", f"{lang}.dlf")
files.append(outputFile)
os.makedirs(os.path.dirname(outputFile), exist_ok=True)
with open(outputFile, "wb") as f:
f.write(langBuffer)
# Write out the language keys header file
outputFile = os.path.join(args.headers_dir, "locale", "language", "keys.h")
os.makedirs(os.path.dirname(outputFile), exist_ok=True)
with open(outputFile, "w") as f:
f.write(headerKeys)
# Generate language list.
langValues = {}
headerLocale = "#pragma once\n#include \"locale/localeinfo.h\"\n\n"
headerLocale += "typedef enum {\n"
count = 0
headerLocale += f" DUSK_LOCALE_NULL = {count},\n"
count += 1
for lang in LANGUAGE_DATA:
langKey = lang.replace('-', '_').replace(' ', '_').upper()
langValues[lang] = count
headerLocale += f" DUSK_LOCALE_{langKey} = {count},\n"
count += 1
headerLocale += f" DUSK_LOCALE_COUNT = {count}\n"
headerLocale += "} dusklocale_t;\n\n"
headerLocale += f"static const localeinfo_t LOCALE_INFOS[DUSK_LOCALE_COUNT] = {{\n"
for lang in LANGUAGE_DATA:
langKey = lang.replace('-', '_').replace(' ', '_').upper()
headerLocale += f" [DUSK_LOCALE_{langKey}] = {{\n"
headerLocale += f" .file = \"{lang}\"\n"
headerLocale += f" }},\n"
headerLocale += "};\n"
headerLocale += f"static const char_t *LOCALE_SCRIPT = \n"
for lang in LANGUAGE_DATA:
langKey = lang.replace('-', '_').replace(' ', '_').upper()
langValue = langValues[lang]
headerLocale += f" \"DUSK_LOCALE_{langKey} = {langValue}\\n\"\n"
headerLocale += ";\n"
# Write out the locale enum header file
outputFile = os.path.join(args.headers_dir, "locale", "locale.h")
os.makedirs(os.path.dirname(outputFile), exist_ok=True)
with open(outputFile, "w") as f:
f.write(headerLocale)
return {
'files': files
}
def getLanguageVariableName(languageKey):
# Take the language key, prepend LANG_, uppercase, replace any non symbols
# with _
key = languageKey.strip().upper()
key = re.sub(r'[^A-Z0-9]', '_', key)
return f"LANG_{key}"
def processLanguage(asset):
cache = assetGetCache(asset['path'])
if cache is not None:
return cache
# Load PO File
po = polib.pofile(asset['path'])
langName = po.metadata.get('Language')
if langName not in LANGUAGE_DATA:
LANGUAGE_DATA[langName] = {}
for entry in po:
key = entry.msgid
val = entry.msgstr
if key not in LANGUAGE_KEYS:
LANGUAGE_KEYS.append(key)
if key not in LANGUAGE_DATA[langName]:
LANGUAGE_DATA[langName][key] = val
else:
print(f"Error: Duplicate translation key '{key}' in language '{langName}'")
sys.exit(1)
outLanguageData = {
'data': po,
'path': asset['path'],
'files': []
}
return assetCache(asset['path'], outLanguageData)
-154
View File
@@ -1,154 +0,0 @@
import struct
import sys
import os
import json
from tools.asset.args import args
from tools.asset.cache import assetCache, assetGetCache
from tools.asset.path import getAssetRelativePath
from tools.dusk.defs import TILE_WIDTH, TILE_HEIGHT, TILE_DEPTH, CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH, CHUNK_TILE_COUNT
from tools.dusk.map import Map
from tools.dusk.chunk import Chunk
def convertModelData(modelData):
# TLDR; Model data stores things efficiently with indices, but we buffer it
# out to 6 vertex quads for simplicity.
outVertices = []
outUVs = []
outColors = []
for indice in modelData['indices']:
vertex = modelData['vertices'][indice]
uv = modelData['uvs'][indice]
color = modelData['colors'][indice]
outVertices.append(vertex)
outUVs.append(uv)
outColors.append(color)
return {
'vertices': outVertices,
'uvs': outUVs,
'colors': outColors
}
def processChunk(chunk):
cache = assetGetCache(chunk.getFilename())
if cache:
return cache
baseModel = {
'vertices': [],
'colors': [],
'uvs': []
}
models = [ baseModel ]
for tileIndex, tile in chunk.tiles.items():
tileBase = tile.getBaseTileModel()
convertedBase = convertModelData(tileBase)
baseModel['vertices'].extend(convertedBase['vertices'])
baseModel['colors'].extend(convertedBase['colors'])
baseModel['uvs'].extend(convertedBase['uvs'])
# Generate binary buffer for efficient output
buffer = bytearray()
buffer.extend(b'DMC')# Header
buffer.extend(len(chunk.tiles).to_bytes(4, 'little')) # Number of tiles
buffer.extend(len(models).to_bytes(1, 'little')) # Number of models
buffer.extend(len(chunk.entities).to_bytes(1, 'little')) # Number of entities
# Buffer tile data as array of uint8_t
for tileIndex, tile in chunk.tiles.items():
buffer.extend(tile.shape.to_bytes(1, 'little'))
# # For each model
for model in models:
vertexCount = len(model['vertices'])
buffer.extend(vertexCount.to_bytes(4, 'little'))
for i in range(vertexCount):
vertex = model['vertices'][i]
uv = model['uvs'][i]
color = model['colors'][i]
buffer.extend(color[0].to_bytes(1, 'little'))
buffer.extend(color[1].to_bytes(1, 'little'))
buffer.extend(color[2].to_bytes(1, 'little'))
buffer.extend(color[3].to_bytes(1, 'little'))
buffer.extend(bytearray(struct.pack('<f', uv[0])))
buffer.extend(bytearray(struct.pack('<f', uv[1])))
buffer.extend(bytearray(struct.pack('<f', vertex[0])))
buffer.extend(bytearray(struct.pack('<f', vertex[1])))
buffer.extend(bytearray(struct.pack('<f', vertex[2])))
# For each entity
for entity in chunk.entities.values():
buffer.extend(entity.type.to_bytes(1, 'little'))
buffer.extend(entity.localX.to_bytes(1, 'little'))
buffer.extend(entity.localY.to_bytes(1, 'little'))
buffer.extend(entity.localZ.to_bytes(1, 'little'))
pass
# Write out map file
relative = getAssetRelativePath(chunk.getFilename())
fileNameWithoutExt = os.path.splitext(os.path.basename(relative))[0]
outputFileRelative = os.path.join(os.path.dirname(relative), f"{fileNameWithoutExt}.dmc")
outputFilePath = os.path.join(args.output_assets, outputFileRelative)
os.makedirs(os.path.dirname(outputFilePath), exist_ok=True)
with open(outputFilePath, "wb") as f:
f.write(buffer)
outChunk = {
'files': [ outputFilePath ],
'chunk': chunk
}
return assetCache(chunk.getFilename(), outChunk)
def processMap(asset):
cache = assetGetCache(asset['path'])
if cache is not None:
return cache
map = Map(None)
map.load(asset['path'])
chunksDir = map.getChunkDirectory()
files = os.listdir(chunksDir)
if len(files) == 0:
print(f"Error: No chunk files found in {chunksDir}.")
sys.exit(1)
chunkFiles = []
for fileName in files:
if not fileName.endswith('.json'):
continue
fNameNoExt = os.path.splitext(fileName)[0]
fnPieces = fNameNoExt.split('_')
if len(fnPieces) != 3:
print(f"Error: Chunk filename {fileName} does not contain valid chunk coordinates.")
sys.exit(1)
chunk = Chunk(map, int(fnPieces[0]), int(fnPieces[1]), int(fnPieces[2]))
chunk.load()
result = processChunk(chunk)
chunkFiles.extend(result['files'])
# Map file
outBuffer = bytearray()
outBuffer.extend(b'DMF')
outBuffer.extend(len(chunkFiles).to_bytes(4, 'little'))
# DMF (Dusk Map file)
fileRelative = getAssetRelativePath(asset['path'])
fileNameWithoutExt = os.path.splitext(os.path.basename(fileRelative))[0]
outputMapRelative = os.path.join(os.path.dirname(fileRelative), f"{fileNameWithoutExt}.dmf")
outputMapPath = os.path.join(args.output_assets, outputMapRelative)
os.makedirs(os.path.dirname(outputMapPath), exist_ok=True)
with open(outputMapPath, "wb") as f:
f.write(outBuffer)
outMap = {
'files': chunkFiles
}
outMap['files'].append(outputMapPath)
return assetCache(asset['path'], outMap)
-96
View File
@@ -1,96 +0,0 @@
import json
import os
from PIL import Image
import datetime
from tools.asset.args import args
from tools.asset.cache import assetCache, assetGetCache
palettes = []
def extractPaletteFromImage(image):
# goes through and finds all unique colors in the image
if image.mode != 'RGBA':
image = image.convert('RGBA')
pixels = list(image.getdata())
uniqueColors = []
for color in pixels:
# We treat all alpha 0 as rgba(0,0,0,0) for palette purposes
if color[3] == 0:
color = (0, 0, 0, 0)
if color not in uniqueColors:
uniqueColors.append(color)
return uniqueColors
def processPalette(asset):
print(f"Processing palette: {asset['path']}")
cache = assetGetCache(asset['path'])
if cache is not None:
return cache
paletteIndex = len(palettes)
image = Image.open(asset['path'])
pixels = extractPaletteFromImage(image)
fileNameWithoutExt = os.path.splitext(os.path.basename(asset['path']))[0]
fileNameWithoutPalette = os.path.splitext(fileNameWithoutExt)[0]
# PSP requires that the palette size be a power of two, so we will pad the
# palette with transparent colors if needed.
def mathNextPowTwo(x):
return 1 << (x - 1).bit_length()
nextPowTwo = mathNextPowTwo(len(pixels))
while len(pixels) < nextPowTwo:
pixels.append((0, 0, 0, 0))
# Header
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data = f"// Palette Generated for {asset['path']} at {now}\n"
data += f"#include \"display/palette/palette.h\"\n\n"
data += f"#define PALETTE_{paletteIndex}_COLOR_COUNT {len(pixels)}\n\n"
data += f"#pragma pack(push, 1)\n"
data += f"static const color_t PALETTE_{paletteIndex}_COLORS[PALETTE_{paletteIndex}_COLOR_COUNT] = {{\n"
for pixel in pixels:
data += f" {{ 0x{pixel[0]:02X}, 0x{pixel[1]:02X}, 0x{pixel[2]:02X}, 0x{pixel[3]:02X} }},\n"
data += f"}};\n"
data += f"#pragma pack(pop)\n\n"
data += f"static const palette_t PALETTE_{paletteIndex} = {{\n"
data += f" .colorCount = PALETTE_{paletteIndex}_COLOR_COUNT,\n"
data += f" .colors = PALETTE_{paletteIndex}_COLORS,\n"
data += f"}};\n"
# Write Header
outputFile = os.path.join(args.headers_dir, "display", "palette", f"palette_{paletteIndex}.h")
os.makedirs(os.path.dirname(outputFile), exist_ok=True)
with open(outputFile, "w") as f:
f.write(data)
palette = {
"paletteIndex": paletteIndex,
"paletteName": fileNameWithoutPalette,
"pixels": pixels,
"headerFile": os.path.relpath(outputFile, args.headers_dir),
"asset": asset,
"files": [ ],# No zippable files.
}
palettes.append(palette)
return assetCache(asset['path'], palette)
def processPaletteList():
data = f"// Auto-generated palette list\n"
print(f"Generating palette list with {len(palettes)} palettes.")
for palette in palettes:
data += f"#include \"{palette['headerFile']}\"\n"
data += f"\n"
data += f"#define PALETTE_LIST_COUNT {len(palettes)}\n\n"
data += f"static const palette_t* PALETTE_LIST[PALETTE_LIST_COUNT] = {{\n"
for palette in palettes:
data += f" &PALETTE_{palette['paletteIndex']},\n"
data += f"}};\n"
# Write the palette list to a header file
outputFile = os.path.join(args.headers_dir, "display", "palette", "palettelist.h")
os.makedirs(os.path.dirname(outputFile), exist_ok=True)
with open(outputFile, "w") as f:
f.write(data)
-43
View File
@@ -1,43 +0,0 @@
import sys
import os
from tools.asset.args import args
from tools.asset.cache import assetCache, assetGetCache
from tools.asset.path import getAssetRelativePath
from tools.dusk.defs import fileDefs
def processScript(asset):
cache = assetGetCache(asset['path'])
if cache is not None:
return cache
# Load the lua file as a string
with open(asset['path'], 'r', encoding='utf-8') as f:
luaCode = f.read()
# TODO: I will precompile or minify the Lua code here in the future
# Replace all definitions in the code
for key, val in fileDefs.items():
luaCode = luaCode.replace(key, str(val))
# Create output Dusk Script File (DSF) data
data = ""
data += "DSF"
data += luaCode
# Write to relative output file path.
relative = getAssetRelativePath(asset['path'])
fileNameWithoutExt = os.path.splitext(os.path.basename(asset['path']))[0]
outputFileRelative = os.path.join(os.path.dirname(relative), f"{fileNameWithoutExt}.dsf")
outputFilePath = os.path.join(args.output_assets, outputFileRelative)
os.makedirs(os.path.dirname(outputFilePath), exist_ok=True)
with open(outputFilePath, "wb") as f:
f.write(data.encode('utf-8'))
outScript = {
'data': data,
'path': asset['path'],
'files': [ outputFilePath ],
'scriptPath': outputFileRelative,
}
return assetCache(asset['path'], outScript)
-178
View File
@@ -1,178 +0,0 @@
import json
import sys
import os
import datetime
from xml.etree import ElementTree
from tools.asset.process.image import processImage
from tools.asset.path import getAssetRelativePath
from tools.asset.args import args
from tools.asset.cache import assetGetCache, assetCache
tilesets = []
def loadTilesetFromTSX(asset):
# Load the TSX file
tree = ElementTree.parse(asset['path'])
root = tree.getroot()
# Expect tileheight, tilewidth, columns and tilecount attributes
if 'tilewidth' not in root.attrib or 'tileheight' not in root.attrib or 'columns' not in root.attrib or 'tilecount' not in root.attrib:
print(f"Error: TSX file {asset['path']} is missing required attributes (tilewidth, tileheight, columns, tilecount)")
sys.exit(1)
tileWidth = int(root.attrib['tilewidth'])
tileHeight = int(root.attrib['tileheight'])
columns = int(root.attrib['columns'])
tileCount = int(root.attrib['tilecount'])
rows = (tileCount + columns - 1) // columns # Calculate rows based on tileCount and columns
# Find the image element
imageElement = root.find('image')
if imageElement is None or 'source' not in imageElement.attrib:
print(f"Error: TSX file {asset['path']} is missing an image element with a source attribute")
sys.exit(1)
imagePath = imageElement.attrib['source']
# Image is relative to the TSX file
imageAssetPath = os.path.join(os.path.dirname(asset['path']), imagePath)
image = processImage({
'path': imageAssetPath,
'options': asset['options'],
})
return {
"image": image,
"tileWidth": tileWidth,
"tileHeight": tileHeight,
"columns": columns,
"rows": rows,
"originalWidth": tileWidth * columns,
"originalHeight": tileHeight * rows,
}
def loadTilesetFromArgs(asset):
# We need to determine how big each tile is. This can either be provided as
# an arg of tileWidth/tileHeight or as a count of rows/columns.
# Additionally, if the image has been factored, then the user can provide both
# tile sizes AND cols/rows to indicate the original size of the image.
image = processImage(asset)
tileWidth, tileHeight = None, None
columns, rows = None, None
originalWidth, originalHeight = image['width'], image['height']
if 'tileWidth' in asset['options'] and 'columns' in asset['options']:
tileWidth = int(asset['options']['tileWidth'])
columns = int(asset['options']['columns'])
originalWidth = tileWidth * columns
elif 'tileWidth' in asset['options']:
tileWidth = int(asset['options']['tileWidth'])
columns = image['width'] // tileWidth
elif 'columns' in asset['options']:
columns = int(asset['options']['columns'])
tileWidth = image['width'] // columns
else:
print(f"Error: Tileset {asset['path']} must specify either tileWidth or columns")
sys.exit(1)
if 'tileHeight' in asset['options'] and 'rows' in asset['options']:
tileHeight = int(asset['options']['tileHeight'])
rows = int(asset['options']['rows'])
originalHeight = tileHeight * rows
elif 'tileHeight' in asset['options']:
tileHeight = int(asset['options']['tileHeight'])
rows = image['height'] // tileHeight
elif 'rows' in asset['options']:
rows = int(asset['options']['rows'])
tileHeight = image['height'] // rows
else:
print(f"Error: Tileset {asset['path']} must specify either tileHeight or rows")
sys.exit(1)
return {
"image": image,
"tileWidth": tileWidth,
"tileHeight": tileHeight,
"columns": columns,
"rows": rows,
"originalWidth": originalWidth,
"originalHeight": originalHeight,
}
def processTileset(asset):
cache = assetGetCache(asset['path'])
if cache is not None:
return cache
print(f"Processing tileset: {asset['path']}")
tilesetData = None
if asset['path'].endswith('.tsx'):
tilesetData = loadTilesetFromTSX(asset)
else:
tilesetData = loadTilesetFromArgs(asset)
fileNameWithoutExtension = os.path.splitext(os.path.basename(asset['path']))[0]
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
tilesetName = fileNameWithoutExtension
tilesetNameUpper = tilesetName.upper()
widthScale = tilesetData['originalWidth'] / tilesetData['image']['width']
heightScale = tilesetData['originalHeight'] / tilesetData['image']['height']
# Create header
data = f"// Tileset Generated for {asset['path']} at {now}\n"
data += f"#pragma once\n"
data += f"#include \"display/tileset/tileset.h\"\n\n"
data += f"static const tileset_t TILESET_{tilesetNameUpper} = {{\n"
data += f" .name = {json.dumps(tilesetName)},\n"
data += f" .tileWidth = {tilesetData['tileWidth']},\n"
data += f" .tileHeight = {tilesetData['tileHeight']},\n"
data += f" .tileCount = {tilesetData['columns'] * tilesetData['rows']},\n"
data += f" .columns = {tilesetData['columns']},\n"
data += f" .rows = {tilesetData['rows']},\n"
data += f" .uv = {{ {widthScale / tilesetData['columns']}f, {heightScale / tilesetData['rows']}f }},\n"
data += f" .image = {json.dumps(tilesetData['image']['imagePath'])},\n"
data += f"}};\n"
# Write Header
outputFile = os.path.join(args.headers_dir, "display", "tileset", f"tileset_{tilesetName}.h")
os.makedirs(os.path.dirname(outputFile), exist_ok=True)
with open(outputFile, 'w') as f:
f.write(data)
print(f"Write header for tileset: {outputFile}")
tileset = {
"files": [],
"image": tilesetData['image'],
"headerFile": os.path.relpath(outputFile, args.headers_dir),
"tilesetName": tilesetName,
"tilesetNameUpper": tilesetNameUpper,
"tilesetIndex": len(tilesets),
"tilesetData": tilesetData,
"files": tilesetData['image']['files'],
}
tilesets.append(tileset)
return assetCache(asset['path'], tileset)
def processTilesetList():
data = f"// Tileset List Generated at {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
data += f"#pragma once\n"
for tileset in tilesets:
data += f"#include \"{tileset['headerFile']}\"\n"
data += f"\n"
data += f"#define TILESET_LIST_COUNT {len(tilesets)}\n\n"
data += f"static const tileset_t* TILESET_LIST[TILESET_LIST_COUNT] = {{\n"
for tileset in tilesets:
data += f" &TILESET_{tileset['tilesetNameUpper']},\n"
data += f"}};\n"
# Write header.
outputFile = os.path.join(args.headers_dir, "display", "tileset", f"tilesetlist.h")
os.makedirs(os.path.dirname(outputFile), exist_ok=True)
with open(outputFile, 'w') as f:
f.write(data)
-47
View File
@@ -1,47 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetpalette.h"
#include "asset/assettype.h"
#include "assert/assert.h"
errorret_t assetPaletteLoad(assetentire_t entire) {
assertNotNull(entire.data, "Data pointer cannot be NULL.");
assertNotNull(entire.output, "Output pointer cannot be NULL.");
assetpalette_t *assetData = (assetpalette_t *)entire.data;
palette_t *palette = (palette_t *)entire.output;
// Read header and version (first 4 bytes)
if(
assetData->header[0] != 'D' ||
assetData->header[1] != 'P' ||
assetData->header[2] != 'F'
) {
errorThrow("Invalid palette header");
}
// Version (can only be 1 atm)
if(assetData->version != 0x01) {
errorThrow("Unsupported palette version");
}
// Check color count.
if(
assetData->colorCount == 0 ||
assetData->colorCount > PALETTE_COLOR_COUNT_MAX
) {
errorThrow("Invalid palette color count");
}
paletteInit(
palette,
assetData->colorCount,
assetData->colors
);
errorOk();
}
-30
View File
@@ -1,30 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "display/texture/palette.h"
typedef struct assetentire_s assetentire_t;
#pragma pack(push, 1)
typedef struct {
char_t header[3];
uint8_t version;
uint8_t colorCount;
color_t colors[PALETTE_COLOR_COUNT_MAX];
} assetpalette_t;
#pragma pack(pop)
/**
* Loads a palette from the given data pointer into the output palette.
*
* @param entire Data received from the asset loader system.
* @return An error code.
*/
errorret_t assetPaletteLoad(assetentire_t entire);
-107
View File
@@ -1,107 +0,0 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "camera.h"
#include "display/display.h"
#include "assert/assert.h"
#include "display/framebuffer/framebuffer.h"
#include "display/screen/screen.h"
void cameraInit(camera_t *camera) {
cameraInitPerspective(camera);
}
void cameraInitPerspective(camera_t *camera) {
assertNotNull(camera, "Not a camera component");
camera->projType = CAMERA_PROJECTION_TYPE_PERSPECTIVE;
camera->perspective.fov = glm_rad(45.0f);
camera->nearClip = 0.1f;
camera->farClip = 10000.0f;
camera->viewType = CAMERA_VIEW_TYPE_LOOKAT;
glm_vec3_copy((vec3){ 5.0f, 5.0f, 5.0f }, camera->lookat.position);
glm_vec3_copy((vec3){ 0.0f, 1.0f, 0.0f }, camera->lookat.up);
glm_vec3_copy((vec3){ 0.0f, 0.0f, 0.0f }, camera->lookat.target);
}
void cameraInitOrthographic(camera_t *camera) {
assertNotNull(camera, "Not a camera component");
camera->projType = CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC;
camera->orthographic.left = 0.0f;
camera->orthographic.right = SCREEN.width;
camera->orthographic.top = SCREEN.height;
camera->orthographic.bottom = 0.0f;
camera->nearClip = 0.1f;
camera->farClip = 1.0f;
camera->viewType = CAMERA_VIEW_TYPE_2D;
glm_vec2_copy((vec2){ 0.0f, 0.0f }, camera->_2d.position);
camera->_2d.zoom = 1.0f;
}
void cameraGetProjectionMatrix(camera_t *camera, mat4 dest) {
assertNotNull(camera, "Not a camera component");
assertNotNull(dest, "Destination matrix must not be null");
if(
camera->projType == CAMERA_PROJECTION_TYPE_PERSPECTIVE ||
camera->projType == CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED
) {
glm_mat4_identity(dest);
glm_perspective(
camera->perspective.fov,
SCREEN.aspect,
camera->nearClip,
camera->farClip,
dest
);
if(camera->projType == CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED) {
dest[1][1] *= -1.0f;
}
} else if(camera->projType == CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC) {
glm_mat4_identity(dest);
glm_ortho(
camera->orthographic.left,
camera->orthographic.right,
camera->orthographic.top,
camera->orthographic.bottom,
camera->nearClip,
camera->farClip,
dest
);
}
}
void cameraGetViewMatrix(camera_t *camera, mat4 dest) {
assertNotNull(camera, "Not a camera component");
assertNotNull(dest, "Destination matrix must not be null");
if(camera->viewType == CAMERA_VIEW_TYPE_MATRIX) {
glm_mat4_ucopy(camera->view, dest);
} else if(camera->viewType == CAMERA_VIEW_TYPE_LOOKAT) {
glm_mat4_identity(dest);
glm_lookat(
camera->lookat.position,
camera->lookat.target,
camera->lookat.up,
dest
);
} else if(camera->viewType == CAMERA_VIEW_TYPE_2D) {
glm_mat4_identity(dest);
glm_lookat(
(vec3){ camera->_2d.position[0], camera->_2d.position[1], 0.5f },
(vec3){ camera->_2d.position[0], camera->_2d.position[1], 0.0f },
(vec3){ 0.0f, 1.0f, 0.0f },
dest
);
} else if(camera->viewType == CAMERA_VIEW_TYPE_LOOKAT_PIXEL_PERFECT) {
assertUnreachable("LOOKAT_PIXEL_PERFECT view type is not implemented yet");
}
}
-97
View File
@@ -1,97 +0,0 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "display/color.h"
#include "display/camera/cameraplatform.h"
#ifndef cameraPushMatrixPlatform
#error "cameraPushMatrixPlatform must be defined"
#endif
typedef enum {
CAMERA_VIEW_TYPE_MATRIX,
CAMERA_VIEW_TYPE_LOOKAT,
CAMERA_VIEW_TYPE_2D,
CAMERA_VIEW_TYPE_LOOKAT_PIXEL_PERFECT
} cameraviewtype_t;
typedef struct camera_s {
union {
mat4 view;
struct {
vec3 position;
vec3 target;
vec3 up;
} lookat;
struct {
vec3 offset;
vec3 target;
vec3 up;
float_t pixelsPerUnit;
} lookatPixelPerfect;
struct {
vec2 position;
float_t zoom;
} _2d;
};
union {
struct {
float_t fov;
} perspective;
struct {
float_t left;
float_t right;
float_t top;
float_t bottom;
} orthographic;
};
float_t nearClip;
float_t farClip;
cameraprojectiontype_t projType;
cameraviewtype_t viewType;
} camera_t;
/**
* Initializes a camera to default values. This calls cameraInitPerspective.
*/
void cameraInit(camera_t *camera);
/**
* Initializes a camera for perspective projection.
*/
void cameraInitPerspective(camera_t *camera);
/**
* Initializes a camera for orthographic projection.
*/
void cameraInitOrthographic(camera_t *camera);
/**
* Gets the projection matrix for a camera.
*
* @param camera Camera to get the projection matrix for
* @param dest Matrix to store the projection matrix in
*/
void cameraGetProjectionMatrix(camera_t *camera, mat4 dest);
/**
* Gets the view matrix for a camera.
*
* @param camera Camera to get the view matrix for
* @param dest Matrix to store the view matrix in
*/
void cameraGetViewMatrix(camera_t *camera, mat4 dest);
-158
View File
@@ -1,158 +0,0 @@
import json
import os
from tools.dusk.event import Event
from tools.dusk.defs import CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH, CHUNK_VERTEX_COUNT_MAX, TILE_SHAPE_NULL
from tools.dusk.tile import Tile
from tools.dusk.entity import Entity
from tools.dusk.region import Region
from tools.editor.map.vertexbuffer import VertexBuffer
from OpenGL.GL import *
class Chunk:
def __init__(self, map, x, y, z):
self.map = map
self.x = x
self.y = y
self.z = z
self.current = {}
self.original = {}
self.entities = {}
self.regions = {}
self.onChunkData = Event()
self.dirty = False
self.tiles = {}
self.vertexBuffer = VertexBuffer()
# Test Region
region = self.regions[0] = Region(self)
region.minX = 0
region.minY = 0
region.minZ = 0
region.maxX = 32
region.maxY = 32
region.maxZ = 32
region.updateVertexs()
# Gen tiles.
tileIndex = 0
for tz in range(CHUNK_DEPTH):
for ty in range(CHUNK_HEIGHT):
for tx in range(CHUNK_WIDTH):
self.tiles[tileIndex] = Tile(self, tx, ty, tz, tileIndex)
tileIndex += 1
# Update vertices
self.tileUpdateVertices()
def reload(self, newX, newY, newZ):
self.x = newX
self.y = newY
self.z = newZ
self.entities = {}
for tile in self.tiles.values():
tile.chunkReload(newX, newY, newZ)
self.load()
def tileUpdateVertices(self):
self.vertexBuffer.clear()
for tile in self.tiles.values():
tile.buffer(self.vertexBuffer)
self.vertexBuffer.buildData()
def load(self):
fname = self.getFilename()
if not fname or not os.path.exists(fname):
self.new()
return
try:
with open(fname, 'r') as f:
data = json.load(f)
if not 'shapes' in data:
data['shapes'] = []
# For each tile.
for tile in self.tiles.values():
tile.load(data)
# For each entity.
self.entities = {}
if 'entities' in data:
for id, entData in enumerate(data['entities']):
ent = Entity(self)
ent.load(entData)
self.entities[id] = ent
self.tileUpdateVertices()
self.dirty = False
self.onChunkData.invoke(self)
self.map.onEntityData.invoke()
except Exception as e:
raise RuntimeError(f"Failed to load chunk file: {e}")
def save(self):
if not self.isDirty():
return
dataOut = {
'shapes': [],
'entities': []
}
for tile in self.tiles.values():
dataOut['shapes'].append(tile.shape)
for ent in self.entities.values():
entData = {}
ent.save(entData)
dataOut['entities'].append(entData)
fname = self.getFilename()
if not fname:
raise ValueError("No filename specified for saving chunk.")
try:
with open(fname, 'w') as f:
json.dump(dataOut, f)
self.dirty = False
self.onChunkData.invoke(self)
except Exception as e:
raise RuntimeError(f"Failed to save chunk file: {e}")
def new(self):
for tile in self.tiles.values():
tile.shape = TILE_SHAPE_NULL
self.tileUpdateVertices()
self.dirty = False
self.onChunkData.invoke(self)
def isDirty(self):
return self.dirty
def getFilename(self):
if not self.map or not hasattr(self.map, 'getChunkDirectory'):
return None
dirPath = self.map.getChunkDirectory()
if dirPath is None:
return None
return f"{dirPath}/{self.x}_{self.y}_{self.z}.json"
def draw(self):
self.vertexBuffer.draw()
def addEntity(self, localX=0, localY=0, localZ=0):
ent = Entity(self, localX, localY, localZ)
self.entities[len(self.entities)] = ent
self.map.onEntityData.invoke()
self.dirty = True
return ent
def removeEntity(self, entity):
for key, val in list(self.entities.items()):
if val == entity:
del self.entities[key]
self.map.onEntityData.invoke()
self.dirty = True
return True
return False
-49
View File
@@ -1,49 +0,0 @@
from dotenv import load_dotenv, dotenv_values
import os
import sys
current_file_path = os.path.abspath(__file__)
duskDefsPath = os.path.join(os.path.dirname(current_file_path), "..", "..", "src", "duskdefs.env")
# Ensure the .env file exists
if not os.path.isfile(duskDefsPath):
print(f"Error: .env file not found at {duskDefsPath}")
sys.exit(1)
load_dotenv(dotenv_path=duskDefsPath)
defs = {key: os.getenv(key) for key in os.environ.keys()}
fileDefs = dotenv_values(dotenv_path=duskDefsPath)
# Parsed out definitions
CHUNK_WIDTH = int(defs.get('CHUNK_WIDTH'))
CHUNK_HEIGHT = int(defs.get('CHUNK_HEIGHT'))
CHUNK_DEPTH = int(defs.get('CHUNK_DEPTH'))
CHUNK_TILE_COUNT = CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_DEPTH
CHUNK_VERTEX_COUNT_MAX = int(defs.get('CHUNK_VERTEX_COUNT_MAX'))
TILE_WIDTH = float(defs.get('TILE_WIDTH'))
TILE_HEIGHT = float(defs.get('TILE_HEIGHT'))
TILE_DEPTH = float(defs.get('TILE_DEPTH'))
RPG_CAMERA_PIXELS_PER_UNIT = float(defs.get('RPG_CAMERA_PIXELS_PER_UNIT'))
RPG_CAMERA_Z_OFFSET = float(defs.get('RPG_CAMERA_Z_OFFSET'))
RPG_CAMERA_FOV = float(defs.get('RPG_CAMERA_FOV'))
MAP_WIDTH = 5
MAP_HEIGHT = 5
MAP_DEPTH = 3
MAP_CHUNK_COUNT = MAP_WIDTH * MAP_HEIGHT * MAP_DEPTH
TILE_SHAPES = {}
for key in defs.keys():
if key.startswith('TILE_SHAPE_'):
globals()[key] = int(defs.get(key))
TILE_SHAPES[key] = int(defs.get(key))
ENTITY_TYPES = {}
for key in defs.keys():
if key.startswith('ENTITY_TYPE_'):
globals()[key] = int(defs.get(key))
if key != 'ENTITY_TYPE_COUNT':
ENTITY_TYPES[key] = int(defs.get(key))
-90
View File
@@ -1,90 +0,0 @@
from tools.dusk.defs import ENTITY_TYPE_NULL, ENTITY_TYPE_NPC, CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH, TILE_WIDTH, TILE_HEIGHT, TILE_DEPTH
from tools.editor.map.vertexbuffer import VertexBuffer
class Entity:
def __init__(self, chunk, localX=0, localY=0, localZ=0):
self.type = ENTITY_TYPE_NPC
self.name = "Unititled"
self.localX = localX % CHUNK_WIDTH
self.localY = localY % CHUNK_HEIGHT
self.localZ = localZ % CHUNK_DEPTH
self.chunk = chunk
self.vertexBuffer = VertexBuffer()
pass
def load(self, obj):
self.type = obj.get('type', ENTITY_TYPE_NULL)
self.localX = obj.get('x', 0)
self.localY = obj.get('y', 0)
self.localZ = obj.get('z', 0)
self.name = obj.get('name', "Untitled")
pass
def save(self, obj):
obj['type'] = self.type
obj['name'] = self.name
obj['x'] = self.localX
obj['y'] = self.localY
obj['z'] = self.localZ
pass
def setType(self, entityType):
if self.type == entityType:
return
self.type = entityType
self.chunk.dirty = True
self.chunk.map.onEntityData.invoke()
def setName(self, name):
if self.name == name:
return
self.name = name
self.chunk.dirty = True
self.chunk.map.onEntityData.invoke()
def draw(self):
self.vertexBuffer.clear()
startX = (self.chunk.x * CHUNK_WIDTH + self.localX) * TILE_WIDTH
startY = (self.chunk.y * CHUNK_HEIGHT + self.localY) * TILE_HEIGHT
startZ = (self.chunk.z * CHUNK_DEPTH + self.localZ) * TILE_DEPTH
w = TILE_WIDTH
h = TILE_HEIGHT
d = TILE_DEPTH
# Center
startX -= w / 2
startY -= h / 2
startZ -= d / 2
# Offset upwards a little
startZ += 1
# Buffer simple quad at current position (need 6 positions)
self.vertexBuffer.vertices = [
startX, startY, startZ,
startX + w, startY, startZ,
startX + w, startY + h, startZ,
startX, startY, startZ,
startX + w, startY + h, startZ,
startX, startY + h, startZ,
]
self.vertexBuffer.colors = [
1.0, 0.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
]
self.vertexBuffer.uvs = [
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 0.0,
1.0, 1.0,
0.0, 1.0,
]
self.vertexBuffer.buildData()
self.vertexBuffer.draw()
-18
View File
@@ -1,18 +0,0 @@
class Event:
def __init__(self):
self._subscribers = []
def sub(self, callback):
"""Subscribe a callback to the event."""
if callback not in self._subscribers:
self._subscribers.append(callback)
def unsub(self, callback):
"""Unsubscribe a callback from the event."""
if callback in self._subscribers:
self._subscribers.remove(callback)
def invoke(self, *args, **kwargs):
"""Invoke all subscribers with the given arguments."""
for callback in self._subscribers:
callback(*args, **kwargs)
-259
View File
@@ -1,259 +0,0 @@
import json
import sys
from tools.dusk.event import Event
from PyQt5.QtWidgets import QFileDialog, QMessageBox
from PyQt5.QtCore import QTimer
import os
from tools.dusk.chunk import Chunk
from tools.dusk.defs import MAP_WIDTH, MAP_HEIGHT, MAP_DEPTH, CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH
import traceback
MAP_DEFAULT_PATH = os.path.join(os.path.dirname(__file__), '../../assets/map/')
EDITOR_CONFIG_PATH = os.path.join(os.path.dirname(__file__), '.editor')
class Map:
def __init__(self, parent):
self.parent = parent
self.data = {}
self.dataOriginal = {}
self.position = [None, None, None] # x, y, z
self.topLeftX = None
self.topLeftY = None
self.topLeftZ = None
self.chunks = {}
self.onMapData = Event()
self.onPositionChange = Event()
self.onEntityData = Event()
self.mapFileName = None
self.lastFile = None
self.firstLoad = True
index = 0
for x in range(MAP_WIDTH):
for y in range(MAP_HEIGHT):
for z in range(MAP_DEPTH):
self.chunks[index] = Chunk(self, x, y, z)
index += 1
# Only in editor instances:
self.moveTo(0, 0, 0)
if parent is not None:
QTimer.singleShot(16, self.loadLastFile)
def loadLastFile(self):
if not os.path.exists(EDITOR_CONFIG_PATH):
return
try:
with open(EDITOR_CONFIG_PATH, 'r') as f:
config = json.load(f)
lastFile = config.get('lastFile')
lastPosition = config.get('lastPosition')
leftPanelIndex = config.get('leftPanelIndex')
if lastFile and os.path.exists(lastFile):
self.load(lastFile)
if lastPosition and isinstance(lastPosition, list) and len(lastPosition) == 3:
self.moveTo(*lastPosition)
if leftPanelIndex is not None:
self.parent.leftPanel.tabs.setCurrentIndex(leftPanelIndex)
except Exception:
traceback.print_exc()
def updateEditorConfig(self):
if self.parent is None:
return
try:
mapFileName = self.getMapFilename()
config = {
'lastFile': mapFileName if mapFileName else "",
'lastPosition': self.position,
'leftPanelIndex': self.parent.leftPanel.tabs.currentIndex()
}
config_dir = os.path.dirname(EDITOR_CONFIG_PATH)
if not os.path.exists(config_dir):
os.makedirs(config_dir, exist_ok=True)
with open(EDITOR_CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=2)
except Exception:
traceback.print_exc()
def newFile(self):
self.data = {}
self.dataOriginal = {}
self.mapFileName = None
self.lastFile = None
for chunk in self.chunks.values():
chunk.new()
self.moveTo(0, 0, 0)
self.onMapData.invoke(self.data)
self.updateEditorConfig()
def save(self, fname=None):
if not self.getMapFilename() and fname is None:
filePath, _ = QFileDialog.getSaveFileName(None, "Save Map File", MAP_DEFAULT_PATH, "Map Files (*.json)")
if not filePath:
return
self.mapFileName = filePath
if fname:
self.mapFileName = fname
try:
with open(self.getMapFilename(), 'w') as f:
json.dump(self.data, f, indent=2)
self.dataOriginal = json.loads(json.dumps(self.data)) # Deep copy
for chunk in self.chunks.values():
chunk.save()
self.updateEditorConfig()
except Exception as e:
traceback.print_exc()
QMessageBox.critical(None, "Save Error", f"Failed to save map file:\n{e}")
def load(self, fileName):
try:
with open(fileName, 'r') as f:
self.data = json.load(f)
self.mapFileName = fileName
self.dataOriginal = json.loads(json.dumps(self.data)) # Deep copy
for chunk in self.chunks.values():
chunk.load()
self.onMapData.invoke(self.data)
self.updateEditorConfig()
except Exception as e:
traceback.print_exc()
QMessageBox.critical(None, "Load Error", f"Failed to load map file:\n{e}")
def isMapFileDirty(self):
return json.dumps(self.data, sort_keys=True) != json.dumps(self.dataOriginal, sort_keys=True)
def isDirty(self):
return self.isMapFileDirty() or self.anyChunksDirty()
def getMapFilename(self):
return self.mapFileName if self.mapFileName and os.path.exists(self.mapFileName) else None
def getMapDirectory(self):
if self.mapFileName is None:
return None
dirname = os.path.dirname(self.mapFileName)
return dirname
def getChunkDirectory(self):
dirName = self.getMapDirectory()
if dirName is None:
return None
return os.path.join(dirName, 'chunks')
def anyChunksDirty(self):
for chunk in self.chunks.values():
if chunk.isDirty():
return True
return False
def moveTo(self, x, y, z):
if self.position == [x, y, z]:
return
# We need to decide if the chunks should be unloaded here or not.
newTopLeftChunkX = x // CHUNK_WIDTH - (MAP_WIDTH // 2)
newTopLeftChunkY = y // CHUNK_HEIGHT - (MAP_HEIGHT // 2)
newTopLeftChunkZ = z // CHUNK_DEPTH - (MAP_DEPTH // 2)
if(newTopLeftChunkX != self.topLeftX or
newTopLeftChunkY != self.topLeftY or
newTopLeftChunkZ != self.topLeftZ):
chunksToUnload = []
chunksToKeep = []
for chunk in self.chunks.values():
chunkWorldX = chunk.x
chunkWorldY = chunk.y
chunkWorldZ = chunk.z
if(chunkWorldX < newTopLeftChunkX or
chunkWorldX >= newTopLeftChunkX + MAP_WIDTH or
chunkWorldY < newTopLeftChunkY or
chunkWorldY >= newTopLeftChunkY + MAP_HEIGHT or
chunkWorldZ < newTopLeftChunkZ or
chunkWorldZ >= newTopLeftChunkZ + MAP_DEPTH):
chunksToUnload.append(chunk)
else:
chunksToKeep.append(chunk)
# Unload chunks that are out of the new bounds.
for chunk in chunksToUnload:
if chunk.isDirty():
print(f"Can't move map, some chunks are dirty: ({chunk.x}, {chunk.y}, {chunk.z})")
return
# Now we can safely unload the chunks.
chunkIndex = 0
newChunks = {}
for chunk in chunksToKeep:
newChunks[chunkIndex] = chunk
chunkIndex += 1
for xPos in range(newTopLeftChunkX, newTopLeftChunkX + MAP_WIDTH):
for yPos in range(newTopLeftChunkY, newTopLeftChunkY + MAP_HEIGHT):
for zPos in range(newTopLeftChunkZ, newTopLeftChunkZ + MAP_DEPTH):
# Check if we already have this chunk.
found = False
for chunk in chunksToKeep:
if chunk.x == xPos and chunk.y == yPos and chunk.z == zPos:
found = True
break
if not found:
# Create a new chunk.
newChunk = chunksToUnload.pop()
newChunk.reload(xPos, yPos, zPos)
newChunks[chunkIndex] = newChunk
chunkIndex += 1
self.chunks = newChunks
self.topLeftX = newTopLeftChunkX
self.topLeftY = newTopLeftChunkY
self.topLeftZ = newTopLeftChunkZ
self.position = [x, y, z]
self.onPositionChange.invoke(self.position)
if not self.firstLoad:
self.updateEditorConfig()
self.firstLoad = False
def moveRelative(self, x, y, z):
self.moveTo(
self.position[0] + x,
self.position[1] + y,
self.position[2] + z
)
def draw(self):
for chunk in self.chunks.values():
chunk.draw()
for chunk in self.chunks.values():
for entity in chunk.entities.values():
entity.draw()
# Only render on Region tab
if self.parent.leftPanel.tabs.currentWidget() == self.parent.leftPanel.regionPanel:
for chunk in self.chunks.values():
for region in chunk.regions.values():
region.draw()
def getChunkAtWorldPos(self, x, y, z):
chunkX = x // CHUNK_WIDTH
chunkY = y // CHUNK_HEIGHT
chunkZ = z // CHUNK_DEPTH
for chunk in self.chunks.values():
if chunk.x == chunkX and chunk.y == chunkY and chunk.z == chunkZ:
return chunk
return None
def getTileAtWorldPos(self, x, y, z):
chunk = self.getChunkAtWorldPos(x, y, z)
if not chunk:
print("No chunk found at position:", (x, y, z))
return None
tileX = x % CHUNK_WIDTH
tileY = y % CHUNK_HEIGHT
tileZ = z % CHUNK_DEPTH
tileIndex = tileX + tileY * CHUNK_WIDTH + tileZ * CHUNK_WIDTH * CHUNK_HEIGHT
return chunk.tiles.get(tileIndex)
-141
View File
@@ -1,141 +0,0 @@
from tools.dusk.defs import CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH, TILE_WIDTH, TILE_HEIGHT, TILE_DEPTH
from tools.editor.map.vertexbuffer import VertexBuffer
from OpenGL.GL import *
from OpenGL.GLU import *
class Region:
def __init__(self, chunk):
self.minX = 0
self.minY = 0
self.minZ = 0
self.maxX = 0
self.maxY = 0
self.maxZ = 0
self.chunk = chunk
self.vertexBuffer = VertexBuffer()
self.color = (1.0, 0.0, 0.0)
self.updateVertexs()
pass
def updateVertexs(self):
# Draw a quad, semi transparent with solid outlines
vminX = (self.minX * CHUNK_WIDTH) * TILE_WIDTH
vminY = (self.minY * CHUNK_HEIGHT) * TILE_HEIGHT
vminZ = (self.minZ * CHUNK_DEPTH) * TILE_DEPTH
vmaxX = (self.maxX * CHUNK_WIDTH) * TILE_WIDTH
vmaxY = (self.maxY * CHUNK_HEIGHT) * TILE_HEIGHT
vmaxZ = (self.maxZ * CHUNK_DEPTH) * TILE_DEPTH
alpha = 0.25
# Move back half a tile width
vminX -= TILE_WIDTH / 2
vmaxX -= TILE_WIDTH / 2
vminY -= TILE_HEIGHT / 2
vmaxY -= TILE_HEIGHT / 2
vminZ -= TILE_DEPTH / 2
vmaxZ -= TILE_DEPTH / 2
# Cube (6 verts per face)
self.vertexBuffer.vertices = [
# Front face
vminX, vminY, vmaxZ,
vmaxX, vminY, vmaxZ,
vmaxX, vmaxY, vmaxZ,
vminX, vminY, vmaxZ,
vmaxX, vmaxY, vmaxZ,
vminX, vmaxY, vmaxZ,
# Back face
vmaxX, vminY, vminZ,
vminX, vminY, vminZ,
vminX, vmaxY, vminZ,
vmaxX, vminY, vminZ,
vminX, vmaxY, vminZ,
vmaxX, vmaxY, vminZ,
# Left face
vminX, vminY, vminZ,
vminX, vminY, vmaxZ,
vminX, vmaxY, vmaxZ,
vminX, vminY, vminZ,
vminX, vmaxY, vmaxZ,
vminX, vmaxY, vminZ,
# Right face
vmaxX, vminY, vmaxZ,
vmaxX, vminY, vminZ,
vmaxX, vmaxY, vminZ,
vmaxX, vminY, vmaxZ,
vmaxX, vmaxY, vminZ,
vmaxX, vmaxY, vmaxZ,
# Top face
vminX, vmaxY, vmaxZ,
vmaxX, vmaxY, vmaxZ,
vmaxX, vmaxY, vminZ,
vminX, vmaxY, vmaxZ,
vmaxX, vmaxY, vminZ,
vminX, vmaxY, vminZ,
# Bottom face
vminX, vminY, vminZ,
vmaxX, vminY, vminZ,
vmaxX, vminY, vmaxZ,
vminX, vminY, vminZ,
vmaxX, vminY, vmaxZ,
vminX, vminY, vmaxZ,
]
self.vertexBuffer.colors = [
# Front face
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
# Back face
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
# Left face
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
# Right face
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
# Top face
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
# Bottom face
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
self.color[0], self.color[1], self.color[2], alpha,
]
self.vertexBuffer.buildData()
def draw(self):
self.vertexBuffer.draw()
-206
View File
@@ -1,206 +0,0 @@
from OpenGL.GL import *
from tools.dusk.defs import (
TILE_WIDTH, TILE_HEIGHT, TILE_DEPTH,
CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH,
TILE_SHAPE_NULL, TILE_SHAPE_FLOOR,
TILE_SHAPE_RAMP_NORTH, TILE_SHAPE_RAMP_SOUTH,
TILE_SHAPE_RAMP_EAST, TILE_SHAPE_RAMP_WEST,
TILE_SHAPE_RAMP_SOUTHWEST, TILE_SHAPE_RAMP_SOUTHEAST,
TILE_SHAPE_RAMP_NORTHWEST, TILE_SHAPE_RAMP_NORTHEAST
)
def getItem(arr, index, default):
if index < len(arr):
return arr[index]
return default
class Tile:
def __init__(self, chunk, x, y, z, tileIndex):
self.shape = TILE_SHAPE_NULL
self.chunk = chunk
self.x = x
self.y = y
self.z = z
self.index = tileIndex
self.posX = x * TILE_WIDTH + chunk.x * CHUNK_WIDTH * TILE_WIDTH
self.posY = y * TILE_HEIGHT + chunk.y * CHUNK_HEIGHT * TILE_HEIGHT
self.posZ = z * TILE_DEPTH + chunk.z * CHUNK_DEPTH * TILE_DEPTH
def chunkReload(self, newX, newY, newZ):
self.posX = self.x * TILE_WIDTH + newX * CHUNK_WIDTH * TILE_WIDTH
self.posY = self.y * TILE_HEIGHT + newY * CHUNK_HEIGHT * TILE_HEIGHT
self.posZ = self.z * TILE_DEPTH + newZ * CHUNK_DEPTH * TILE_DEPTH
def load(self, chunkData):
self.shape = getItem(chunkData['shapes'], self.index, TILE_SHAPE_NULL)
def setShape(self, shape):
if shape == self.shape:
return
self.shape = shape
self.chunk.dirty = True
self.chunk.tileUpdateVertices()
self.chunk.onChunkData.invoke(self.chunk)
def getBaseTileModel(self):
vertices = []
indices = []
uvs = []
colors = []
if self.shape == TILE_SHAPE_NULL:
pass
elif self.shape == TILE_SHAPE_FLOOR:
vertices = [
(self.posX, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ),
(self.posX, self.posY + TILE_HEIGHT, self.posZ)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (255, 255, 255, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_NORTH:
vertices = [
(self.posX, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ),
(self.posX, self.posY + TILE_HEIGHT, self.posZ)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (255, 0, 0, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_SOUTH:
vertices = [
(self.posX, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH),
(self.posX, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (0, 255, 0, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_EAST:
vertices = [
(self.posX, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH),
(self.posX, self.posY + TILE_HEIGHT, self.posZ)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (0, 0, 255, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_WEST:
vertices = [
(self.posX, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ),
(self.posX, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (255, 255, 0, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_SOUTHWEST:
vertices = [
(self.posX, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH),
(self.posX, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (255, 128, 0, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_NORTHWEST:
vertices = [
(self.posX, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ),
(self.posX, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (128, 255, 0, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_NORTHEAST:
vertices = [
(self.posX, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH),
(self.posX, self.posY + TILE_HEIGHT, self.posZ)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (0, 255, 128, 255) ] * 4
elif self.shape == TILE_SHAPE_RAMP_SOUTHEAST:
vertices = [
(self.posX, self.posY, self.posZ),
(self.posX + TILE_WIDTH, self.posY, self.posZ + TILE_DEPTH),
(self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH),
(self.posX, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH)
]
indices = [0, 1, 2, 0, 2, 3]
uvs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
colors = [ (255, 128, 255, 255) ] * 4
else:
# Solid black cube for unknown shape
x0, y0, z0 = self.posX, self.posY, self.posZ
x1, y1, z1 = self.posX + TILE_WIDTH, self.posY + TILE_HEIGHT, self.posZ + TILE_DEPTH
vertices = [
(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), # bottom
(x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1) # top
]
indices = [
0,1,2, 0,2,3, # bottom
4,5,6, 4,6,7, # top
0,1,5, 0,5,4, # front
2,3,7, 2,7,6, # back
1,2,6, 1,6,5, # right
3,0,4, 3,4,7 # left
]
uvs = [ (0,0) ] * 8
colors = [ (0,0,0,255) ] * 8
return {
'vertices': vertices,
'indices': indices,
'uvs': uvs,
'colors': colors
}
def buffer(self, vertexBuffer):
if self.shape == TILE_SHAPE_NULL:
return
# New code:
baseData = self.getBaseTileModel()
# Base data is indiced but we need to buffer unindiced data
for index in baseData['indices']:
verts = baseData['vertices'][index]
uv = baseData['uvs'][index]
color = baseData['colors'][index]
vertexBuffer.vertices.extend([
verts[0] - (TILE_WIDTH / 2.0),
verts[1] - (TILE_HEIGHT / 2.0),
verts[2] - (TILE_DEPTH / 2.0)
])
vertexBuffer.colors.extend([
color[0] / 255.0,
color[1] / 255.0,
color[2] / 255.0,
color[3] / 255.0
])
+18
View File
@@ -0,0 +1,18 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
add_subdirectory(debug)
add_subdirectory(frame)
add_subdirectory(focus)
add_subdirectory(overlay)
add_subdirectory(transition)
add_subdirectory(widget)
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
ui.c
uielement.c
)
+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
uiconsole.c
uifps.c
)
+138
View File
@@ -0,0 +1,138 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiconsole.h"
#include "assert/assert.h"
#include "console/console.h"
#include "display/screen/screen.h"
#include "display/text/text.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "display/mesh/mesh.h"
#include "util/memory.h"
typedef struct {
mesh_t mesh;
bool_t built;
meshvertex_t vertices[UI_CONSOLE_CACHE_VERTEX_MAX];
int32_t vertexCount;
int32_t cachedScanX;
int32_t cachedScanY;
} uiconsolecache_t;
uiconsolecache_t UI_CONSOLE_CACHE;
errorret_t uiConsoleDraw(void) {
if(!CONSOLE.visible) errorOk();
if(
CONSOLE.dirty ||
UI_CONSOLE_CACHE.cachedScanX != SCREEN.scanX ||
UI_CONSOLE_CACHE.cachedScanY != SCREEN.scanY
) {
errorChain(uiConsoleRebuild());
}
if(UI_CONSOLE_CACHE.vertexCount == 0) errorOk();
shadermaterial_t material = {
.unlit = {
.color = COLOR_RED,
.texture = FONT_DEFAULT.texture
}
};
errorChain(shaderBind(&SHADER_UNLIT));
errorChain(shaderSetMaterial(&SHADER_UNLIT, &material));
return meshDraw(&UI_CONSOLE_CACHE.mesh, 0, UI_CONSOLE_CACHE.vertexCount);
}
errorret_t uiConsoleRebuild(void) {
int32_t spriteCount = 0;
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
char_t c;
int32_t j = 0;
while((c = CONSOLE.line[i][j++]) != '\0') {
if(c != ' ' && c != '\n') spriteCount++;
}
}
assertTrue(
spriteCount <= UI_CONSOLE_CACHE_GLYPH_MAX,
"Console history exceeds fixed cache capacity"
);
const int32_t vertexCount = spriteCount * QUAD_VERTEX_COUNT;
UI_CONSOLE_CACHE.vertexCount = vertexCount;
if(vertexCount > 0) {
const float_t lineH = (float_t)FONT_DEFAULT.tileset->tileHeight;
const float_t charW = (float_t)FONT_DEFAULT.tileset->tileWidth;
int32_t index = 0;
int32_t row = 0;
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
float_t posX = (float_t)SCREEN.scanX;
float_t posY = (float_t)SCREEN.scanY + lineH * (float_t)row;
char_t c;
int32_t j = 0;
while((c = CONSOLE.line[i][j++]) != '\0') {
if(c == '\n') {
posX = (float_t)SCREEN.scanX;
posY += lineH;
row++;
continue;
}
if(c == ' ') {
posX += charW;
continue;
}
const spritebatchsprite_t sprite = textGetSprite(
(vec2){ posX, posY }, c, &FONT_DEFAULT
);
spriteBatchBufferToMesh(
&sprite, 1,
&UI_CONSOLE_CACHE.vertices[index], QUAD_VERTEX_COUNT
);
index += QUAD_VERTEX_COUNT;
posX += charW;
}
row++;
}
if(!UI_CONSOLE_CACHE.built) {
errorChain(meshInit(
&UI_CONSOLE_CACHE.mesh,
QUAD_PRIMITIVE_TYPE,
UI_CONSOLE_CACHE_VERTEX_MAX,
UI_CONSOLE_CACHE.vertices
));
UI_CONSOLE_CACHE.built = true;
} else {
errorChain(meshFlush(&UI_CONSOLE_CACHE.mesh, 0, vertexCount));
}
}
UI_CONSOLE_CACHE.cachedScanX = SCREEN.scanX;
UI_CONSOLE_CACHE.cachedScanY = SCREEN.scanY;
CONSOLE.dirty = false;
errorOk();
}
errorret_t uiConsoleDispose(void) {
if(UI_CONSOLE_CACHE.built) {
errorChain(meshDispose(&UI_CONSOLE_CACHE.mesh));
}
memoryZero(&UI_CONSOLE_CACHE, sizeof(uiconsolecache_t));
errorOk();
}
+48
View File
@@ -0,0 +1,48 @@
/**
* 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/mesh/quad.h"
// Fixed capacity for the console's cached glyph mesh, in glyphs -- the
// mesh/vertex buffer is sized to this once and never grown/shrunk, so
// history producing more non-space characters than this asserts (see
// uiConsoleRebuild) instead of reallocating.
#define UI_CONSOLE_CACHE_GLYPH_MAX 512
#define UI_CONSOLE_CACHE_VERTEX_MAX (\
UI_CONSOLE_CACHE_GLYPH_MAX * QUAD_VERTEX_COUNT \
)
/**
* Renders the console history into the scan-safe area, drawing a mesh
* that is only rebuilt when the history changes or the scan-safe origin
* moves, rather than rebuffering vertices every frame. No-ops when the
* console is not visible.
*
* @return Any error that occurs.
*/
errorret_t uiConsoleDraw(void);
/**
* Rebuilds the cached mesh for the console's current history and
* scan-safe origin. Called automatically by uiConsoleDraw() whenever
* needed; only needs calling directly to force an immediate rebuild.
* The underlying vertex buffer is a fixed-size array (see
* UI_CONSOLE_CACHE_VERTEX_MAX) -- asserts if the history produces more
* glyphs than that capacity, rather than growing it.
*
* @return Any error that occurs.
*/
errorret_t uiConsoleRebuild(void);
/**
* Frees the mesh and vertex buffer built up by uiConsoleDraw().
*
* @return Any error that occurs.
*/
errorret_t uiConsoleDispose(void);
@@ -7,13 +7,21 @@
#include "uifps.h"
#include "time/time.h"
#include "display/spritebatch/spritebatch.h"
#include "util/string.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "engine/engine.h"
uifps_t UIFPS;
errorret_t uiFPSInit() {
uiLabelInit(&UIFPS.fpsLabel, &FONT_DEFAULT);
uiLabelInit(&UIFPS.versionLabel, &FONT_DEFAULT);
uiLabelSetText(&UIFPS.versionLabel, ENGINE.version);
uiLabelSetColor(&UIFPS.versionLabel, color(255, 255, 255, 128));
errorOk();
}
errorret_t uiFPSDraw() {
char_t fpsText[32];
@@ -50,22 +58,21 @@ errorret_t uiFPSDraw() {
textColor = COLOR_RED;
}
errorChain(textDraw(
0, 0,
fpsText, textColor,
&FONT_DEFAULT
uiLabelSetColor(&UIFPS.fpsLabel, textColor);
if(stringCompare(fpsText, UIFPS.fpsLabel.text) != 0) {
uiLabelSetText(&UIFPS.fpsLabel, fpsText);
}
errorChain(uiLabelDraw(
&UIFPS.fpsLabel, (float_t)SCREEN.scanX, (float_t)SCREEN.scanY
));
errorChain(spriteBatchFlush());
int32_t versionWidth, versionHeight;
textMeasure(ENGINE.version, &FONT_DEFAULT, &versionWidth, &versionHeight);
errorChain(textDraw(
(float_t)(SCREEN.width - versionWidth),
(float_t)(SCREEN.height - versionHeight),
ENGINE.version,
color(255, 255, 255, 128),
&FONT_DEFAULT
uiLabelGetSize(&UIFPS.versionLabel, &versionWidth, &versionHeight);
errorChain(uiLabelDraw(
&UIFPS.versionLabel,
(float_t)(SCREEN.scanX + SCREEN.scanWidth - versionWidth),
(float_t)(SCREEN.scanY + SCREEN.scanHeight - versionHeight)
));
return spriteBatchFlush();
errorOk();
}
@@ -8,14 +8,24 @@
#pragma once
#include "error/error.h"
#include "time/timeepoch.h"
#include "ui/widget/uilabel.h"
typedef struct {
dusktimeepoch_t lastTick;
float_t fpsAverage;
uilabel_t fpsLabel;
uilabel_t versionLabel;
} uifps_t;
extern uifps_t UIFPS;
/**
* Initializes the FPS counter, caching the (static) version label.
*
* @return Any error that occurs.
*/
errorret_t uiFPSInit();
/**
* Draws the FPS counter on the screen, and also does the update (for now).
*
@@ -5,5 +5,5 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
cutscene.c
uifocus.c
)
+190
View File
@@ -0,0 +1,190 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uifocus.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "input/input.h"
#include "time/time.h"
const uifocusdirmap_t UI_FOCUS_DIR_MAP[] = {
{ INPUT_BIND_UP, UI_FOCUS_DIRECTION_UP, 0, -1 },
{ INPUT_BIND_DOWN, UI_FOCUS_DIRECTION_DOWN, 0, 1 },
{ INPUT_BIND_LEFT, UI_FOCUS_DIRECTION_LEFT, -1, 0 },
{ INPUT_BIND_RIGHT, UI_FOCUS_DIRECTION_RIGHT, 1, 0 },
{ INPUT_BIND_NULL, UI_FOCUS_DIRECTION_NONE, 0, 0 },
};
uifocus_t UI_FOCUS;
void uiFocusInit(void) {
memoryZero(&UI_FOCUS, sizeof(uifocus_t));
}
uifocusitem_t * uiFocusPush(
const uint8_t cols,
const uint8_t rows,
uifocusitemcallback_t selected,
uifocusitemcallback_t changed,
uifocusitemcallback_t closed,
uifocusitemdirectioncallback_t direction,
void *user
) {
assertTrue(
UI_FOCUS.count < UI_FOCUS_STACK_MAX,
"UI focus stack overflow"
);
assertTrue(cols > 0, "Focus item cols must be > 0");
assertTrue(rows > 0, "Focus item rows must be > 0");
uifocusitem_t *item = &UI_FOCUS.items[UI_FOCUS.count];
memoryZero(item, sizeof(uifocusitem_t));
item->cols = cols;
item->rows = rows;
item->selected = selected;
item->changed = changed;
item->closed = closed;
item->direction = direction;
item->user = user;
UI_FOCUS.count++;
UI_FOCUS.pushedThisTick = true;
if(item->changed != NULL) item->changed(item);
return item;
}
void uiFocusPop(void) {
assertTrue(UI_FOCUS.count > 0, "UI focus stack underflow");
uifocusitem_t *item = &UI_FOCUS.items[UI_FOCUS.count - 1];
if(item->closed != NULL) item->closed(item);
UI_FOCUS.count--;
}
void uiFocusPopItem(uifocusitem_t *item) {
assertTrue(UI_FOCUS.count > 0, "UI focus stack underflow");
assertTrue(item >= UI_FOCUS.items, "Item is not on the focus stack");
assertTrue(
item < UI_FOCUS.items + UI_FOCUS.count,
"Item is not on the focus stack"
);
while(&UI_FOCUS.items[UI_FOCUS.count - 1] != item) {
uiFocusPop();
}
uiFocusPop();
}
void uiFocusSetPosition(uifocusitem_t *item, const uint8_t x, const uint8_t y) {
assertTrue(UI_FOCUS.count > 0, "No active focus item");
assertTrue(item->cols > 0, "Focus item cols must be > 0");
assertTrue(item->rows > 0, "Focus item rows must be > 0");
uint8_t newX = x % item->cols;
uint8_t newY = y % item->rows;
if(item->changed != NULL) {
uint8_t oldX = item->x;
uint8_t oldY = item->y;
item->x = newX;
item->y = newY;
if(!item->changed(item)) {
item->x = oldX;
item->y = oldY;
}
return;
}
item->x = newX;
item->y = newY;
}
void uiFocusMoveDirection(
uifocusitem_t *item,
const uifocusdirection_t dir
) {
for(
const uifocusdirmap_t *m = UI_FOCUS_DIR_MAP;
m->action != INPUT_BIND_NULL;
m++
) {
if(m->direction != dir) continue;
uint8_t x = (uint8_t)(item->x + m->dx);
uint8_t y = (uint8_t)(item->y + m->dy);
uiFocusSetPosition(item, x, y);
break;
}
}
void uiFocusHandleDirection(
uifocusitem_t *item,
const uifocusdirection_t dir
) {
if(item->direction != NULL && item->direction(item, dir)) return;
uiFocusMoveDirection(item, dir);
}
void uiFocusUpdate(void) {
if(UI_FOCUS.count == 0) return;
#ifdef DUSK_TIME_DYNAMIC
if(TIME.dynamicUpdate) return;
#endif
if(UI_FOCUS.pushedThisTick) {
UI_FOCUS.pushedThisTick = false;
return;
}
uifocusitem_t *item = &UI_FOCUS.items[UI_FOCUS.count - 1];
if(inputPressed(INPUT_BIND_ACCEPT)) {
if(item->selected != NULL) item->selected(item);
return;
}
if(inputPressed(INPUT_BIND_CANCEL)) {
uiFocusPop();
return;
}
for(
const uifocusdirmap_t *m = UI_FOCUS_DIR_MAP;
m->action != INPUT_BIND_NULL;
m++
) {
if(!inputPressed(m->action)) continue;
UI_FOCUS.direction = m->direction;
UI_FOCUS.timeHeld = 0.0f;
uiFocusHandleDirection(item, m->direction);
return;
}
bool_t held = false;
for(
const uifocusdirmap_t *m = UI_FOCUS_DIR_MAP;
m->action != INPUT_BIND_NULL;
m++
) {
if(m->direction != UI_FOCUS.direction) continue;
held = inputIsDown(m->action);
break;
}
if(!held) {
UI_FOCUS.direction = UI_FOCUS_DIRECTION_NONE;
UI_FOCUS.timeHeld = 0.0f;
return;
}
UI_FOCUS.timeHeld += TIME.delta;
if(UI_FOCUS.timeHeld < UI_FOCUS_HOLD_DELAY) return;
if(UI_FOCUS.timeHeld < UI_FOCUS_HOLD_DELAY + UI_FOCUS_HOLD_REPEAT) return;
UI_FOCUS.timeHeld = UI_FOCUS_HOLD_DELAY;
uiFocusHandleDirection(item, UI_FOCUS.direction);
}
+133
View File
@@ -0,0 +1,133 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "uifocusitem.h"
#include "input/inputaction.h"
/** Maximum depth of the focus stack. */
#define UI_FOCUS_STACK_MAX 8
/**
* How long a direction must be held before repeating begins, in seconds.
*/
#define UI_FOCUS_HOLD_DELAY 0.5f
/**
* Interval between repeated moves while a direction is held, in seconds.
*/
#define UI_FOCUS_HOLD_REPEAT 0.1f
typedef struct {
inputbind_t action;
uifocusdirection_t direction;
int8_t dx;
int8_t dy;
} uifocusdirmap_t;
/**
* Mapping of input actions to focus directions, terminated by an
* entry with action == INPUT_BIND_NULL.
*/
extern const uifocusdirmap_t UI_FOCUS_DIR_MAP[];
/**
* A stack of focused UI items. Push an item when a widget captures
* focus; pop it when focus is released. The topmost item is always
* the active focus context.
*/
typedef struct {
uifocusitem_t items[UI_FOCUS_STACK_MAX];
uint8_t count;
uifocusdirection_t direction;
float_t timeHeld;
bool_t pushedThisTick;
} uifocus_t;
extern uifocus_t UI_FOCUS;
/**
* Initializes the focus system, zeroing all state.
*/
void uiFocusInit(void);
/**
* Pushes a new focus item onto the stack with the given grid dimensions
* and callbacks. x and y are initialized to 0.
*
* @param cols Number of columns in the focus grid.
* @param rows Number of rows in the focus grid.
* @param selected Called when the user selects the focused cell.
* @param changed Called when the focused cell position changes.
* @param closed Called when this focus item is popped.
* @param direction Called on a direction press/hold before the default
* cell-to-cell movement is applied; may be NULL.
* @param user Arbitrary pointer stored on the item before changed fires.
* @returns Pointer to the newly pushed focus item.
*/
uifocusitem_t * uiFocusPush(
const uint8_t cols,
const uint8_t rows,
uifocusitemcallback_t selected,
uifocusitemcallback_t changed,
uifocusitemcallback_t closed,
uifocusitemdirectioncallback_t direction,
void *user
);
/**
* Pops the topmost focus item from the stack, invoking its closed
* callback if one is set.
*/
void uiFocusPop(void);
/**
* Pops an item and anything that was pushed after it from the focus stack.
*
* @param item The focus item to pop to. Must be on the stack.
*/
void uiFocusPopItem(uifocusitem_t *item);
/**
* Manually sets the cursor position of the topmost focus item and
* fires its changed callback.
*
* @param x Column to move to.
* @param y Row to move to.
*/
void uiFocusSetPosition(uifocusitem_t *item, const uint8_t x, const uint8_t y);
/**
* Moves the topmost focus item one step in the given direction,
* wrapping at the grid edges, and fires its changed callback.
*
* @param item The focus item to move.
* @param dir Direction to move.
*/
void uiFocusMoveDirection(
uifocusitem_t *item,
const uifocusdirection_t dir
);
/**
* Handles a direction press/hold for the given item: gives the item's
* direction callback (if any) first refusal, falling back to the
* default cell-to-cell movement if it's unset or returns false.
*
* @param item The focus item to move.
* @param dir Direction that was pressed or held.
*/
void uiFocusHandleDirection(
uifocusitem_t *item,
const uifocusdirection_t dir
);
/**
* Updates the focus system. Handles first-press movement and
* held-direction repeating. Called once per game tick.
*/
void uiFocusUpdate(void);
+57
View File
@@ -0,0 +1,57 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct uifocusitem_s uifocusitem_t;
typedef enum {
UI_FOCUS_DIRECTION_NONE,
UI_FOCUS_DIRECTION_UP,
UI_FOCUS_DIRECTION_DOWN,
UI_FOCUS_DIRECTION_LEFT,
UI_FOCUS_DIRECTION_RIGHT
} uifocusdirection_t;
/**
* Callback invoked when a focus item's selected cell changes.
*
* @param item The focus item that changed.
*/
typedef bool_t (*uifocusitemcallback_t)(const uifocusitem_t *item);
/**
* Callback invoked when a direction is pressed or held-repeated while
* this item is focused, before the default cell-to-cell movement is
* applied.
*
* @param item The focus item that is currently focused.
* @param direction The direction that was pressed.
* @returns True if the direction was fully handled and the default
* grid movement should be skipped; false to fall through to it.
*/
typedef bool_t (*uifocusitemdirectioncallback_t)(
const uifocusitem_t *item,
const uifocusdirection_t direction
);
/**
* A single entry on the UI focus stack. Tracks the focused cell
* within a grid of cols x rows, and the current x/y position.
*/
struct uifocusitem_s {
uint8_t cols;
uint8_t rows;
uint8_t x;
uint8_t y;
uifocusitemcallback_t selected;
uifocusitemcallback_t changed;
uifocusitemcallback_t closed;
uifocusitemdirectioncallback_t direction;
void *user;
};
+12
View File
@@ -0,0 +1,12 @@
# 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
uiframe.c
uiconfirm.c
)
add_subdirectory(settings)
@@ -0,0 +1,13 @@
# 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
uisettings.c
uisettingsgeneral.c
uisettingsinput.c
uisettingsdisplay.c
uisettingsaudio.c
)
+248
View File
@@ -0,0 +1,248 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettings.h"
#include "uisettingsgeneral.h"
#include "uisettingsinput.h"
#include "uisettingsdisplay.h"
#include "uisettingsaudio.h"
#include "ui/frame/uiframe.h"
#include "ui/frame/uiconfirm.h"
#include "util/memory.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "assert/assert.h"
#include "locale/localemanager.h"
#include "asset/loader/locale/assetlocaleloader.h"
uisettings_t UI_SETTINGS;
uisettingstabdef_t UI_SETTINGS_TAB_DEFS[UI_SETTINGS_TAB_COUNT] = {
{
.localeId = "ui.settings.tabs.general",
.init = uiSettingsGeneralInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsGeneralLoad,
.apply = uiSettingsGeneralApply,
.hasChanges = uiSettingsGeneralHasChanges
},
{
.localeId = "ui.settings.tabs.input",
.init = uiSettingsInputInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsInputLoad,
.apply = uiSettingsInputApply,
.hasChanges = uiSettingsInputHasChanges
},
{
.localeId = "ui.settings.tabs.display",
.init = uiSettingsDisplayInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsDisplayLoad,
.apply = uiSettingsDisplayApply,
.hasChanges = uiSettingsDisplayHasChanges
},
{
.localeId = "ui.settings.tabs.audio",
.init = uiSettingsAudioInit,
.menu = (uimenu_t *)&UI_SETTINGS.data,
.load = uiSettingsAudioLoad,
.apply = uiSettingsAudioApply,
.hasChanges = uiSettingsAudioHasChanges
}
};
static uisettingstabdef_t UI_SETTINGS_TOP_DEF = {
.menu = &UI_SETTINGS.tabsMenu,
.load = uiSettingsLoad,
.hasChanges = uiSettingsHasChanges
};
static uisettingstabdef_t *UI_SETTINGS_PENDING_DISCARD = NULL;
static uisettingstabdef_t *UI_SETTINGS_ACTIVE_TAB = NULL;
errorret_t uiSettingsActivateTab(uisettingstabdef_t *def) {
if(def == UI_SETTINGS_ACTIVE_TAB) errorOk();
errorChain(def->init(&UI_SETTINGS.data));
def->menu->user = def;
def->load();
UI_SETTINGS_ACTIVE_TAB = def;
errorOk();
}
void uiSettingsTabChanged(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index >= UI_SETTINGS_TAB_COUNT) return;
errorCatch(uiSettingsActivateTab(&UI_SETTINGS_TAB_DEFS[index]));
}
void uiSettingsTabSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index >= UI_SETTINGS_TAB_COUNT) return;
uisettingstabdef_t *def = &UI_SETTINGS_TAB_DEFS[index];
errorCatch(uiSettingsActivateTab(def));
uiMenuOpen(def->menu);
}
errorret_t uiSettingsInit(void) {
memoryZero(&UI_SETTINGS, sizeof(uisettings_t));
UI_SETTINGS_ACTIVE_TAB = NULL;
for(uint8_t i = 0; i < UI_SETTINGS_TAB_COUNT; i++) {
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
UI_SETTINGS_TAB_DEFS[i].localeId,
0,
UI_SETTINGS.tabLabels[i],
UI_SETTINGS_TAB_LABEL_MAX
));
}
MENU_BEGIN(
&UI_SETTINGS.tabsMenu, UI_SETTINGS.tabs, uiSettingsTabSelected,
uiSettingsDiscardMenuClosed, uiSettingsTabChanged
);
for(uint8_t i = 0; i < UI_SETTINGS_TAB_COUNT; i++) {
MENU_TAB(UI_SETTINGS.tabLabels[i]);
}
MENU_END(UI_SETTINGS.tabs, menuIndex);
UI_SETTINGS.tabsMenu.user = &UI_SETTINGS_TOP_DEF;
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.apply",
0,
UI_SETTINGS.applyLabel,
UI_SETTINGS_APPLY_LABEL_MAX
));
errorChain(uiSettingsActivateTab(&UI_SETTINGS_TAB_DEFS[0]));
errorOk();
}
errorret_t uiSettingsDraw(void) {
if(!uiMenuIsActive(&UI_SETTINGS.tabsMenu)) errorOk();
const float_t width = SCREEN.width;
const float_t height = SCREEN.height;
const float_t x = (float_t)SCREEN.scanX +
((float_t)SCREEN.scanWidth - width) * 0.5f;
const float_t y = (float_t)SCREEN.scanY +
((float_t)SCREEN.scanHeight - height) * 0.5f;
errorChain(uiFrameDrawCached(&UI_SETTINGS.frameCache, x, y, width, height));
const float_t contentX = x + UI_FRAME_START_X;
const float_t contentY = y + UI_FRAME_START_Y;
const float_t contentWidth = width - (UI_FRAME_START_X * 2);
const float_t contentHeight = height - (UI_FRAME_START_Y * 2);
errorChain(uiMenuDraw(
&UI_SETTINGS.tabsMenu,
contentX,
contentY,
contentWidth,
contentHeight
));
const float_t tabsRowHeight = (float_t)FONT_DEFAULT.tileset->tileHeight;
const float_t pageY = contentY + tabsRowHeight + UI_FRAME_PADDING_Y;
const float_t pageHeight = contentHeight - tabsRowHeight - UI_FRAME_PADDING_Y;
if(UI_SETTINGS_ACTIVE_TAB != NULL) {
errorChain(uiMenuDraw(
UI_SETTINGS_ACTIVE_TAB->menu, contentX, pageY, contentWidth, pageHeight
));
}
errorOk();
}
errorret_t uiSettingsUpdate(void) {
if(!UI_SETTINGS_PENDING_DISCARD) errorOk();
uisettingstabdef_t *def = UI_SETTINGS_PENDING_DISCARD;
UI_SETTINGS_PENDING_DISCARD = NULL;
return uiSettingsDiscardUpdate(def);
}
bool_t uiSettingsIsOpen(void) {
return uiMenuIsActive(&UI_SETTINGS.tabsMenu);
}
void uiSettingsOpen() {
uiSettingsLoad();
uiMenuOpen(&UI_SETTINGS.tabsMenu);
}
void uiSettingsClose() {
uiMenuClose(&UI_SETTINGS.tabsMenu);
}
errorret_t uiSettingsDispose(void) {
errorOk();
}
void uiSettingsLoad(void) {
if(UI_SETTINGS_ACTIVE_TAB != NULL) UI_SETTINGS_ACTIVE_TAB->load();
}
void uiSettingsApply(void) {
if(UI_SETTINGS_ACTIVE_TAB != NULL) UI_SETTINGS_ACTIVE_TAB->apply();
}
bool_t uiSettingsHasChanges(void) {
return UI_SETTINGS_ACTIVE_TAB != NULL && UI_SETTINGS_ACTIVE_TAB->hasChanges();
}
void uiSettingsDiscardMenuClosed(const uimenu_t *menu) {
uisettingstabdef_t *def = (uisettingstabdef_t *)menu->user;
if(def->hasChanges()) UI_SETTINGS_PENDING_DISCARD = def;
}
errorret_t uiSettingsDiscardUpdate(uisettingstabdef_t *def) {
#define UI_SETTINGS_DISCARD_TEXT_MAX 128
char_t text[UI_SETTINGS_DISCARD_TEXT_MAX];
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.confirm.discard_changes",
0,
text,
UI_SETTINGS_DISCARD_TEXT_MAX
));
#undef UI_SETTINGS_DISCARD_TEXT_MAX
uiConfirmOpen(text, uiSettingsDiscardConfirmResult, def);
errorOk();
}
void uiSettingsDiscardConfirmResult(const bool_t result, void *user) {
uisettingstabdef_t *def = (uisettingstabdef_t *)user;
if(!result) {
uiMenuOpen(def->menu);
return;
}
def->load();
}
+135
View File
@@ -0,0 +1,135 @@
/**
* 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 "ui/widget/uimenu.h"
#include "ui/frame/uiframe.h"
#include "uisettingsdata.h"
#define UI_SETTINGS_TAB_COUNT 4
#define UI_SETTINGS_TAB_LABEL_MAX 32
#define UI_SETTINGS_APPLY_LABEL_MAX 32
typedef struct {
const char_t *localeId;
errorret_t (*init)(uisettingsdata_t *data);
uimenu_t *menu;
void (*load)(void);
void (*apply)(void);
bool_t (*hasChanges)(void);
} uisettingstabdef_t;
typedef struct {
uimenu_t tabsMenu;
uimenuitem_t tabs[UI_SETTINGS_TAB_COUNT];
char_t tabLabels[UI_SETTINGS_TAB_COUNT][UI_SETTINGS_TAB_LABEL_MAX];
char_t applyLabel[UI_SETTINGS_APPLY_LABEL_MAX];
uisettingsdata_t data;
uiframecache_t frameCache;
} uisettings_t;
extern uisettings_t UI_SETTINGS;
extern uisettingstabdef_t UI_SETTINGS_TAB_DEFS[UI_SETTINGS_TAB_COUNT];
/**
* Menu closed callback that flags a pending discard-changes
* confirmation if the menu's settings page/panel reports unsaved
* changes. Pass this directly as a settings page menu's closed
* callback. The pending def is picked up by uiSettingsUpdate on the
* next tick.
*
* @param menu The menu that was just closed.
*/
void uiSettingsDiscardMenuClosed(const uimenu_t *menu);
/**
* Shows the discard-changes confirmation dialog for def. Called once
* by uiSettingsUpdate when uiSettingsDiscardMenuClosed has flagged a
* pending def.
*
* @param def The tab/panel def to show the confirmation for.
* @return Any error that occurs.
*/
errorret_t uiSettingsDiscardUpdate(uisettingstabdef_t *def);
/**
* Callback passed to uiConfirmOpen by uiSettingsDiscardUpdate. Reopens
* the menu if the user chose to keep editing, otherwise reloads the
* widgets back to the actual engine values.
*
* @param result True if the user confirmed discarding changes, false
* to keep editing.
* @param user The uisettingstabdef_t* this confirmation belongs to.
*/
void uiSettingsDiscardConfirmResult(const bool_t result, void *user);
/**
* Initializes the settings panel and all of its category pages.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsInit(void);
/**
* Draws the settings panel. No-op when not visible.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsDraw(void);
/**
* Updates the settings panel. Shows a discard-changes confirmation if
* the panel was just closed with unsaved changes.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsUpdate(void);
/**
* Returns true when the settings panel is currently open.
*
* @returns True if open.
*/
bool_t uiSettingsIsOpen(void);
/**
* Opens the settings panel. No-op when already open.
*/
void uiSettingsOpen();
/**
* Closes the settings panel. No-op when already closed.
*/
void uiSettingsClose();
/**
* Disposes of the settings panel.
*
* @return Any error that occurs.
*/
errorret_t uiSettingsDispose(void);
/**
* Loads every category page's widgets from the current engine settings.
* Called automatically by uiSettingsOpen.
*/
void uiSettingsLoad(void);
/**
* Applies every category page's widget values to the engine settings.
* Called automatically when a page's own Apply button is pressed.
*/
void uiSettingsApply(void);
/**
* Returns whether any category page has a widget value that differs
* from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsHasChanges(void);
@@ -0,0 +1,47 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsaudio.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
void uiSettingsAudioSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index != UI_SETTINGS_AUDIO_INDEX_APPLY) return;
uiSettingsAudioApply();
}
errorret_t uiSettingsAudioInit(uisettingsdata_t *data) {
uisettingsaudio_t *audio = &data->audio;
memoryZero(audio, sizeof(uisettingsaudio_t));
MENU_BEGIN(
&audio->menu, audio->items,
uiSettingsAudioSelected, uiSettingsDiscardMenuClosed, NULL
);
MENU_LABEL("No audio settings yet");
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(audio->items, 1);
errorOk();
}
void uiSettingsAudioLoad(void) {
}
void uiSettingsAudioApply(void) {
uiMenuClose(&UI_SETTINGS.data.audio.menu);
}
bool_t uiSettingsAudioHasChanges(void) {
return false;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the audio settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsAudioInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine audio settings.
*/
void uiSettingsAudioLoad(void);
/**
* Applies the page's widget values to the engine audio settings.
*/
void uiSettingsAudioApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsAudioHasChanges(void);
@@ -0,0 +1,67 @@
/**
* 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 "ui/widget/uimenu.h"
#define UI_SETTINGS_GENERAL_ITEM_COUNT 3
#define UI_SETTINGS_GENERAL_INDEX_LANGUAGE 0
#define UI_SETTINGS_GENERAL_INDEX_LANGUAGE_DETAIL 1
#define UI_SETTINGS_GENERAL_INDEX_APPLY 2
#define UI_SETTINGS_GENERAL_LOCALE_COUNT 3
#define UI_SETTINGS_GENERAL_LABEL_MAX 32
#define UI_SETTINGS_GENERAL_INFO_MAX 64
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_GENERAL_ITEM_COUNT];
const char_t *localeNames[UI_SETTINGS_GENERAL_LOCALE_COUNT];
char_t languageLabel[UI_SETTINGS_GENERAL_LABEL_MAX];
char_t labelInfo[UI_SETTINGS_GENERAL_INFO_MAX];
} uisettingsgeneral_t;
#define UI_SETTINGS_INPUT_ITEM_COUNT 2
#define UI_SETTINGS_INPUT_LABEL_MAX 32
#define UI_SETTINGS_INPUT_INDEX_DEADZONE 0
#define UI_SETTINGS_INPUT_INDEX_APPLY 1
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_INPUT_ITEM_COUNT];
char_t deadzoneLabel[UI_SETTINGS_INPUT_LABEL_MAX];
} uisettingsinput_t;
#define UI_SETTINGS_DISPLAY_ITEM_COUNT 2
#define UI_SETTINGS_DISPLAY_INDEX_APPLY 1
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_DISPLAY_ITEM_COUNT];
} uisettingsdisplay_t;
#define UI_SETTINGS_AUDIO_ITEM_COUNT 2
#define UI_SETTINGS_AUDIO_INDEX_APPLY 1
typedef struct {
uimenu_t menu;
uimenuitem_t items[UI_SETTINGS_AUDIO_ITEM_COUNT];
} uisettingsaudio_t;
/**
* Shared, overlapping storage for every settings tab's page data. Only
* one member is ever live at a time -- the active tab's Init writes
* into it, overwriting whatever the previously active tab left there.
* This trades simultaneous access to every tab for a memory footprint
* of only the single largest page.
*/
typedef union {
uisettingsgeneral_t general;
uisettingsinput_t input;
uisettingsdisplay_t display;
uisettingsaudio_t audio;
} uisettingsdata_t;
@@ -0,0 +1,47 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsdisplay.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
void uiSettingsDisplaySelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index != UI_SETTINGS_DISPLAY_INDEX_APPLY) return;
uiSettingsDisplayApply();
}
errorret_t uiSettingsDisplayInit(uisettingsdata_t *data) {
uisettingsdisplay_t *display = &data->display;
memoryZero(display, sizeof(uisettingsdisplay_t));
MENU_BEGIN(
&display->menu, display->items,
uiSettingsDisplaySelected, uiSettingsDiscardMenuClosed, NULL
);
MENU_LABEL("No display settings yet");
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(display->items, 1);
errorOk();
}
void uiSettingsDisplayLoad(void) {
}
void uiSettingsDisplayApply(void) {
uiMenuClose(&UI_SETTINGS.data.display.menu);
}
bool_t uiSettingsDisplayHasChanges(void) {
return false;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the display settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsDisplayInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine display settings.
*/
void uiSettingsDisplayLoad(void);
/**
* Applies the page's widget values to the engine display settings.
*/
void uiSettingsDisplayApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsDisplayHasChanges(void);
@@ -0,0 +1,117 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsgeneral.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "locale/localemanager.h"
#include "locale/localeinfo.h"
#include "asset/loader/locale/assetlocaleloader.h"
static const localeinfo_t *const UI_SETTINGS_GENERAL_LOCALES[
UI_SETTINGS_GENERAL_LOCALE_COUNT
] = {
&LOCALE_EN_US,
&LOCALE_JP_JP,
&LOCALE_ES_MX
};
void uiSettingsGeneralSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
switch(index) {
case UI_SETTINGS_GENERAL_INDEX_APPLY:
uiSettingsGeneralApply();
break;
default:
break;
}
}
errorret_t uiSettingsGeneralInit(uisettingsdata_t *data) {
uisettingsgeneral_t *general = &data->general;
memoryZero(general, sizeof(uisettingsgeneral_t));
for(uint8_t i = 0; i < UI_SETTINGS_GENERAL_LOCALE_COUNT; i++) {
general->localeNames[i] = UI_SETTINGS_GENERAL_LOCALES[i]->name;
}
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.general.language",
0,
general->languageLabel,
UI_SETTINGS_GENERAL_LABEL_MAX
));
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.general.language_detail",
0,
general->labelInfo,
UI_SETTINGS_GENERAL_INFO_MAX
));
MENU_BEGIN(
&general->menu, general->items,
uiSettingsGeneralSelected, uiSettingsDiscardMenuClosed, NULL
);
MENU_DROPDOWN(
general->languageLabel, general->localeNames,
UI_SETTINGS_GENERAL_LOCALE_COUNT, 0
);
MENU_LABEL(general->labelInfo);
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(general->items, 1);
errorOk();
}
void uiSettingsGeneralLoad(void) {
uisettingsgeneral_t *general = &UI_SETTINGS.data.general;
uint8_t index = 0;
for(uint8_t i = 0; i < UI_SETTINGS_GENERAL_LOCALE_COUNT; i++) {
if(stringCompare(LOCALE.locale->file, UI_SETTINGS_GENERAL_LOCALES[i]->file) != 0) {
continue;
}
index = i;
break;
}
uiDropdownSetSelectedIndex(
&general->items[UI_SETTINGS_GENERAL_INDEX_LANGUAGE].dropdown, index
);
}
void uiSettingsGeneralApply(void) {
uisettingsgeneral_t *general = &UI_SETTINGS.data.general;
uint8_t index = uiDropdownGetSelectedIndex(
&general->items[UI_SETTINGS_GENERAL_INDEX_LANGUAGE].dropdown
);
errorCatch(localeManagerSetLocale(UI_SETTINGS_GENERAL_LOCALES[index]));
uiMenuClose(&general->menu);
}
bool_t uiSettingsGeneralHasChanges(void) {
uisettingsgeneral_t *general = &UI_SETTINGS.data.general;
uint8_t index = uiDropdownGetSelectedIndex(
&general->items[UI_SETTINGS_GENERAL_INDEX_LANGUAGE].dropdown
);
return stringCompare(
LOCALE.locale->file, UI_SETTINGS_GENERAL_LOCALES[index]->file
) != 0;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the general settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsGeneralInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine general settings.
*/
void uiSettingsGeneralLoad(void);
/**
* Applies the page's widget values to the engine general settings.
*/
void uiSettingsGeneralApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsGeneralHasChanges(void);
@@ -0,0 +1,82 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uisettingsinput.h"
#include "uisettings.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "locale/localemanager.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "input/input.h"
#include "save/savesettings.h"
void uiSettingsInputSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
if(index != UI_SETTINGS_INPUT_INDEX_APPLY) return;
uiSettingsInputApply();
}
errorret_t uiSettingsInputInit(uisettingsdata_t *data) {
uisettingsinput_t *input = &data->input;
memoryZero(input, sizeof(uisettingsinput_t));
MENU_BEGIN(
&input->menu, input->items,
uiSettingsInputSelected, uiSettingsDiscardMenuClosed, NULL
);
#ifdef DUSK_INPUT_GAMEPAD
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.settings.input.deadzone",
0,
input->deadzoneLabel,
UI_SETTINGS_INPUT_LABEL_MAX
));
MENU_SLIDER_FLOAT(
input->deadzoneLabel, INPUT_DEADZONE_DEFAULT, 0.0f, 1.0f, 0.05f
);
#else
MENU_LABEL("No input settings yet");
#endif
MENU_BUTTON(UI_SETTINGS.applyLabel);
MENU_END(input->items, 1);
errorOk();
}
void uiSettingsInputLoad(void) {
#ifdef DUSK_INPUT_GAMEPAD
uiSliderSetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider,
INPUT.deadzone
);
#endif
}
void uiSettingsInputApply(void) {
#ifdef DUSK_INPUT_GAMEPAD
INPUT.deadzone = uiSliderGetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider
);
#endif
errorCatch(errorPrint(saveSettingsWrite()));
uiMenuClose(&UI_SETTINGS.data.input.menu);
}
bool_t uiSettingsInputHasChanges(void) {
#ifdef DUSK_INPUT_GAMEPAD
if(uiSliderGetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider
) != INPUT.deadzone) return true;
#endif
return false;
}
@@ -0,0 +1,36 @@
/**
* 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 "uisettingsdata.h"
/**
* Initializes the input settings page into the shared settings data
* union.
*
* @param data The shared settings data union to initialize into.
* @return Any error that occurs.
*/
errorret_t uiSettingsInputInit(uisettingsdata_t *data);
/**
* Loads the page's widgets from the current engine input settings.
*/
void uiSettingsInputLoad(void);
/**
* Applies the page's widget values to the engine input settings.
*/
void uiSettingsInputApply(void);
/**
* Returns whether any widget's value differs from what was loaded.
*
* @returns True if there are unsaved changes.
*/
bool_t uiSettingsInputHasChanges(void);
+126
View File
@@ -0,0 +1,126 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiconfirm.h"
#include "uiframe.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/math.h"
#include "display/screen/screen.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/texture/texture.h"
#include "display/shader/shaderunlit.h"
#define UI_CONFIRM_BACKDROP_COLOR color4b(0, 0, 0, 160)
uiconfirm_t UI_CONFIRM;
void uiConfirmSelected(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
) {
UI_CONFIRM.result = index == UI_CONFIRM_INDEX_CONFIRM;
uiConfirmClose();
}
void uiConfirmClosed(const uimenu_t *menu) {
if(UI_CONFIRM.callback != NULL) {
UI_CONFIRM.callback(UI_CONFIRM.result, UI_CONFIRM.user);
}
}
errorret_t uiConfirmInit(void) {
memoryZero(&UI_CONFIRM, sizeof(uiconfirm_t));
uiLabelInit(&UI_CONFIRM.textLabel, &FONT_DEFAULT);
MENU_BEGIN(
&UI_CONFIRM.menu, UI_CONFIRM.items, uiConfirmSelected, uiConfirmClosed, NULL
);
MENU_BUTTON("Confirm");
MENU_BUTTON("Cancel");
MENU_END(UI_CONFIRM.items, menuIndex);
errorOk();
}
errorret_t uiConfirmDraw(void) {
if(!uiMenuIsActive(&UI_CONFIRM.menu)) errorOk();
spritebatchsprite_t backdropSprite = {
.min = { 0.0f, 0.0f, 0.0f },
.max = { (float_t)SCREEN.width, (float_t)SCREEN.height, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t backdropMaterial = {
.unlit = {
.color = UI_CONFIRM_BACKDROP_COLOR,
.texture = &TEXTURE_WHITE
}
};
errorChain(
spriteBatchBuffer(&backdropSprite, 1, &SHADER_UNLIT, backdropMaterial)
);
int32_t textW, textH;
uiLabelGetSize(&UI_CONFIRM.textLabel, &textW, &textH);
float_t rowHeight = (float_t)FONT_DEFAULT.tileset->tileHeight;
float_t width = mathMax(
(float_t)textW + (UI_FRAME_START_X * 2), UI_CONFIRM_MIN_WIDTH
);
float_t height = (UI_FRAME_START_Y * 2) + rowHeight + UI_FRAME_PADDING_Y +
rowHeight;
float_t x = (float_t)SCREEN.scanX + ((float_t)SCREEN.scanWidth - width) * 0.5f;
float_t y = (float_t)SCREEN.scanY + ((float_t)SCREEN.scanHeight - height) * 0.5f;
errorChain(uiFrameDrawCached(&UI_CONFIRM.frameCache, x, y, width, height));
float_t contentX = x + UI_FRAME_START_X;
float_t contentY = y + UI_FRAME_START_Y;
float_t contentWidth = width - (UI_FRAME_START_X * 2);
errorChain(uiLabelDraw(&UI_CONFIRM.textLabel, contentX, contentY));
float_t buttonsY = contentY + rowHeight + UI_FRAME_PADDING_Y;
errorChain(uiMenuDraw(&UI_CONFIRM.menu, contentX, buttonsY, contentWidth, rowHeight));
errorOk();
}
bool_t uiConfirmIsOpen(void) {
return uiMenuIsActive(&UI_CONFIRM.menu);
}
bool_t uiConfirmGetResult(void) {
return UI_CONFIRM.result;
}
void uiConfirmOpen(
const char_t *question,
uiconfirmcallback_t callback,
void *user
) {
assertNotNull(question, "Question cannot be NULL");
uiLabelSetText(&UI_CONFIRM.textLabel, question);
UI_CONFIRM.callback = callback;
UI_CONFIRM.user = user;
UI_CONFIRM.result = false;
uiMenuOpen(&UI_CONFIRM.menu);
}
void uiConfirmClose(void) {
uiMenuClose(&UI_CONFIRM.menu);
}
errorret_t uiConfirmDispose(void) {
errorOk();
}
+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
*/
#pragma once
#include "error/error.h"
#include "ui/widget/uimenu.h"
#include "ui/widget/uilabel.h"
#include "ui/frame/uiframe.h"
#define UI_CONFIRM_MIN_WIDTH 160.0f
#define UI_CONFIRM_INDEX_CONFIRM 0
#define UI_CONFIRM_INDEX_CANCEL 1
#define UI_CONFIRM_ITEM_COUNT 2
/**
* Callback invoked once a confirm dialog is dismissed.
*
* @param result True if Confirm was selected, false if Cancel was
* selected or the dialog was backed out of.
* @param user Arbitrary pointer passed to uiConfirmOpen.
*/
typedef void (*uiconfirmcallback_t)(const bool_t result, void *user);
typedef struct {
uilabel_t textLabel;
uimenu_t menu;
uimenuitem_t items[UI_CONFIRM_ITEM_COUNT];
uiconfirmcallback_t callback;
void *user;
bool_t result;
uiframecache_t frameCache;
} uiconfirm_t;
extern uiconfirm_t UI_CONFIRM;
/**
* Initializes the confirm dialog.
*
* @return Any error that occurs.
*/
errorret_t uiConfirmInit(void);
/**
* Draws the confirm dialog: a semi-transparent black backdrop covering
* the whole screen, then its own centered frame with the question text
* and Confirm/Cancel buttons. No-op when not open.
*
* @return Any error that occurs.
*/
errorret_t uiConfirmDraw(void);
/**
* Returns true when the confirm dialog is currently open.
*
* @returns True if open.
*/
bool_t uiConfirmIsOpen(void);
/**
* Returns the result of the most recently dismissed confirm dialog.
*
* @returns True if Confirm was selected, false otherwise.
*/
bool_t uiConfirmGetResult(void);
/**
* Opens the confirm dialog with the given question text. callback is
* invoked exactly once with the result, whether the dialog was
* dismissed by selecting a button or by pressing cancel/back.
*
* @param question Display text; copied internally, safe to be transient.
* @param callback Called with the result once the dialog closes. May be
* NULL.
* @param user Arbitrary pointer passed through to callback.
*/
void uiConfirmOpen(
const char_t *question,
uiconfirmcallback_t callback,
void *user
);
/**
* Closes the confirm dialog. No-op when already closed.
*/
void uiConfirmClose(void);
/**
* Disposes of the confirm dialog.
*
* @return Any error that occurs.
*/
errorret_t uiConfirmDispose(void);
+161
View File
@@ -0,0 +1,161 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiframe.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "display/texture/texture.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "display/color.h"
uiframe_t UI_FRAME;
errorret_t uiFrameInit(void) {
memoryZero(&UI_FRAME, sizeof(uiframe_t));
// Init texture.
color_t border = color4b(0, 50, 255, 255);
color_t center = color4b(0, 100, 220, 240);
for(uint8_t y = 0; y < UI_FRAME_TEXTURE_HEIGHT_POW2; y++) {
for(uint8_t x = 0; x < UI_FRAME_TEXTURE_WIDTH_POW2; x++) {
color_t c;
if(x >= UI_FRAME_TEXTURE_WIDTH || y >= UI_FRAME_TEXTURE_HEIGHT) {
c = COLOR_TRANSPARENT;
} else if(
y < UI_FRAME_TILE_HEIGHT || y >= UI_FRAME_TILE_HEIGHT * 2 ||
x < UI_FRAME_TILE_WIDTH || x >= UI_FRAME_TILE_WIDTH * 2
) {
c = border;
} else {
c = center;
}
UI_FRAME.pixels[y * UI_FRAME_TEXTURE_WIDTH_POW2 + x] = c;
}
}
errorChain(textureInit(
&UI_FRAME.texture,
UI_FRAME_TEXTURE_WIDTH_POW2, UI_FRAME_TEXTURE_HEIGHT_POW2,
TEXTURE_FORMAT_RGBA,
(texturedata_t){ .rgbaColors = UI_FRAME.pixels }
));
UI_FRAME.tileset.tileWidth = UI_FRAME_TILE_WIDTH;
UI_FRAME.tileset.tileHeight = UI_FRAME_TILE_HEIGHT;
UI_FRAME.tileset.columns = 3;
UI_FRAME.tileset.rows = 3;
UI_FRAME.tileset.tileCount = 9;
UI_FRAME.tileset.uv[0] =
(float_t)UI_FRAME_TILE_WIDTH / UI_FRAME_TEXTURE_WIDTH_POW2;
UI_FRAME.tileset.uv[1] =
(float_t)UI_FRAME_TILE_HEIGHT / UI_FRAME_TEXTURE_HEIGHT_POW2;
errorOk();
}
errorret_t uiFrameDraw(
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = &UI_FRAME.texture
}
};
spritebatchsprite_t sprites[9];
uiFrameBuildSprites(sprites, x, y, width, height);
return spriteBatchBuffer(sprites, 9, &SHADER_UNLIT, material);
}
void uiFrameBuildSprites(
spritebatchsprite_t sprites[9],
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
float_t tileW = (float_t)UI_FRAME_BORDER_WIDTH;
float_t tileH = (float_t)UI_FRAME_BORDER_HEIGHT;
sprites[0] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 0, 0,
x, y, tileW, tileH
);
sprites[1] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 1, 0,
x + tileW, y, width - (tileW * 2.0f), tileH
);
sprites[2] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 2, 0,
x + width - tileW, y, tileW, tileH
);
sprites[3] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 0, 1,
x, y + tileH, tileW, height - (tileH * 2.0f)
);
sprites[4] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 1, 1,
x + tileW, y + tileH,
width - (tileW * 2.0f), height - (tileH * 2.0f)
);
sprites[5] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 2, 1,
x + width - tileW, y + tileH, tileW, height - (tileH * 2.0f)
);
sprites[6] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 0, 2,
x, y + height - tileH, tileW, tileH
);
sprites[7] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 1, 2,
x + tileW, y + height - tileH, width - (tileW * 2.0f), tileH
);
sprites[8] = spriteBatchSpriteTilesetPosition(
&UI_FRAME.tileset, 2, 2,
x + width - tileW, y + height - tileH, tileW, tileH
);
}
errorret_t uiFrameDrawCached(
uiframecache_t *cache,
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
assertNotNull(cache, "Frame cache cannot be NULL");
if(
!cache->built ||
cache->lastX != x || cache->lastY != y ||
cache->lastWidth != width || cache->lastHeight != height
) {
uiFrameBuildSprites(cache->sprites, x, y, width, height);
cache->lastX = x;
cache->lastY = y;
cache->lastWidth = width;
cache->lastHeight = height;
cache->built = true;
}
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = &UI_FRAME.texture
}
};
return spriteBatchBuffer(cache->sprites, 9, &SHADER_UNLIT, material);
}
errorret_t uiFrameDispose(void) {
return textureDispose(&UI_FRAME.texture);
}
+122
View File
@@ -0,0 +1,122 @@
/**
* 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/texture/texture.h"
#include "display/texture/tileset.h"
#include "display/spritebatch/spritebatchsprite.h"
#define UI_FRAME_BORDER_WIDTH 6
#define UI_FRAME_BORDER_HEIGHT 6
#define UI_FRAME_PADDING_X 2
#define UI_FRAME_PADDING_Y 2
#define UI_FRAME_START_X (UI_FRAME_BORDER_WIDTH + UI_FRAME_PADDING_X)
#define UI_FRAME_START_Y (UI_FRAME_BORDER_HEIGHT + UI_FRAME_PADDING_Y)
#define UI_FRAME_TILE_WIDTH 1
#define UI_FRAME_TILE_HEIGHT 1
#define UI_FRAME_TEXTURE_WIDTH (UI_FRAME_TILE_WIDTH * 3)
#define UI_FRAME_TEXTURE_HEIGHT (UI_FRAME_TILE_HEIGHT * 3)
#define UI_FRAME_TEXTURE_WIDTH_POW2 4
#define UI_FRAME_TEXTURE_HEIGHT_POW2 4
typedef struct {
tileset_t tileset;
texture_t texture;
color_t pixels[UI_FRAME_BORDER_WIDTH * UI_FRAME_BORDER_HEIGHT];
} uiframe_t;
extern uiframe_t UI_FRAME;
/**
* Initializes the global UI_FRAME: builds the dummy texture and
* configures the tileset. Call once after displayInit().
*
* @return Any error that occurs.
*/
errorret_t uiFrameInit(void);
/**
* Draws UI_FRAME using 9-slice rendering from its 3x3 tileset.
* Pushes quads to the sprite batch without flushing.
*
* @param x Screen x position.
* @param y Screen y position.
* @param width Total width of the frame.
* @param height Total height of the frame.
* @return Any error that occurs.
*/
errorret_t uiFrameDraw(
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* Builds the 9 sprites for a 9-slice frame at the given rect. Used
* internally by uiFrameDraw and uiFrameDrawCached -- call directly only
* if you need the raw sprites instead of buffering them.
*
* @param sprites Destination array of exactly 9 sprites.
* @param x Screen x position.
* @param y Screen y position.
* @param width Total width of the frame.
* @param height Total height of the frame.
*/
void uiFrameBuildSprites(
spritebatchsprite_t sprites[9],
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* A frame's cached 9-slice sprites, plus the rect they were built for.
* Owned by whichever widget/screen draws a frame repeatedly (dialogs,
* textboxes, settings panels) so uiFrameDrawCached can skip rebuilding
* the sprites when the rect hasn't moved since the last draw.
*/
typedef struct {
spritebatchsprite_t sprites[9];
bool_t built;
float_t lastX;
float_t lastY;
float_t lastWidth;
float_t lastHeight;
} uiframecache_t;
/**
* Draws a 9-slice frame using a caller-owned cache, only rebuilding the
* sprites (via uiFrameBuildSprites) when x/y/width/height differ from
* the last call -- unlike uiFrameDraw, which rebuilds unconditionally
* every time. Prefer this for frames redrawn every frame at a fixed or
* rarely-changing rect (dialogs, panels); use plain uiFrameDraw for
* genuinely one-off or per-frame-varying rects.
*
* @param cache Caller-owned cache, zero-initialized before first use.
* @param x Screen x position.
* @param y Screen y position.
* @param width Total width of the frame.
* @param height Total height of the frame.
* @return Any error that occurs.
*/
errorret_t uiFrameDrawCached(
uiframecache_t *cache,
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* Disposes of the global UI_FRAME, releasing its GPU texture.
*
* @return Any error that occurs.
*/
errorret_t uiFrameDispose(void);
+11
View File
@@ -0,0 +1,11 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
uicrop.c
uifullbox.c
uiloading.c
)
+89
View File
@@ -0,0 +1,89 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uicrop.h"
#include "display/screen/screen.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "display/texture/texture.h"
uicrop_t UI_CROP;
errorret_t uiCropInit(void) {
UI_CROP.color = COLOR_BLACK;
errorOk();
}
errorret_t uiCropDraw(void) {
#ifndef DUSK_DISPLAY_SIZE_DYNAMIC
errorOk();
#endif
if(
SCREEN.scanX == 0 &&
SCREEN.scanY == 0 &&
SCREEN.scanWidth == SCREEN.width &&
SCREEN.scanHeight == SCREEN.height
) errorOk();
float_t x0 = (float_t)SCREEN.scanX;
float_t y0 = (float_t)SCREEN.scanY;
float_t x1 = (float_t)(SCREEN.scanX + SCREEN.scanWidth);
float_t y1 = (float_t)(SCREEN.scanY + SCREEN.scanHeight);
float_t w = (float_t)SCREEN.width;
float_t h = (float_t)SCREEN.height;
spritebatchsprite_t sprites[4];
int32_t count = 0;
if(SCREEN.scanX > 0) {
sprites[count++] = (spritebatchsprite_t){
.min = { 0.0f, 0.0f, 0.0f },
.max = { x0, h, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
if(SCREEN.scanX + SCREEN.scanWidth < SCREEN.width) {
sprites[count++] = (spritebatchsprite_t){
.min = { x1, 0.0f, 0.0f },
.max = { w, h, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
if(SCREEN.scanY > 0) {
sprites[count++] = (spritebatchsprite_t){
.min = { x0, 0.0f, 0.0f },
.max = { x1, y0, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
if(SCREEN.scanY + SCREEN.scanHeight < SCREEN.height) {
sprites[count++] = (spritebatchsprite_t){
.min = { x0, y1, 0.0f },
.max = { x1, h, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
if(count == 0) errorOk();
shadermaterial_t material = {
.unlit = {
.color = UI_CROP.color,
.texture = &TEXTURE_WHITE
}
};
errorChain(spriteBatchBuffer(sprites, count, &SHADER_UNLIT, material));
errorOk();
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "display/color.h"
typedef struct {
color_t color;
} uicrop_t;
extern uicrop_t UI_CROP;
/**
* Initializes the crop bars to opaque black.
*
* @return Any error that occurs.
*/
errorret_t uiCropInit(void);
/**
* Renders solid-color bars covering every area outside the
* current scan-safe region. No-ops when the scan area equals
* the full viewport.
*
* @return Any error that occurs.
*/
errorret_t uiCropDraw(void);
@@ -8,6 +8,7 @@
#include "uifullbox.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "time/time.h"
#include "display/screen/screen.h"
#include "display/texture/texture.h"
#include "display/spritebatch/spritebatch.h"
@@ -74,7 +75,7 @@ errorret_t uiFullboxDraw(uifullbox_t *fullbox) {
}
};
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
return spriteBatchFlush();
errorOk();
}
void uiFullboxTransition(
@@ -92,10 +93,30 @@ void uiFullboxTransition(
fullbox->easing = easing;
}
errorret_t uiFullboxUnderInit(void) {
uiFullboxInit(&UI_FULLBOX_UNDER);
errorOk();
}
errorret_t uiFullboxUnderUpdate(void) {
uiFullboxUpdate(&UI_FULLBOX_UNDER, TIME.delta);
errorOk();
}
errorret_t uiFullboxUnderDraw(void) {
return uiFullboxDraw(&UI_FULLBOX_UNDER);
}
errorret_t uiFullboxOverInit(void) {
uiFullboxInit(&UI_FULLBOX_OVER);
errorOk();
}
errorret_t uiFullboxOverUpdate(void) {
uiFullboxUpdate(&UI_FULLBOX_OVER, TIME.delta);
errorOk();
}
errorret_t uiFullboxOverDraw(void) {
return uiFullboxDraw(&UI_FULLBOX_OVER);
}
@@ -66,12 +66,44 @@ void uiFullboxTransition(
easingtype_t easing
);
/**
* Init function for UI_FULLBOX_UNDER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxUnderInit(void);
/**
* Update function for UI_FULLBOX_UNDER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxUnderUpdate(void);
/**
* Draw function for UI_FULLBOX_UNDER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxUnderDraw(void);
/**
* Init function for UI_FULLBOX_OVER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxOverInit(void);
/**
* Update function for UI_FULLBOX_OVER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxOverUpdate(void);
/**
* Draw function for UI_FULLBOX_OVER (registered in UI_ELEMENTS).
*
* @return Any error that occurs.
*/
errorret_t uiFullboxOverDraw(void);
@@ -8,33 +8,37 @@
#include "uiloading.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "time/time.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "display/spritebatch/spritebatch.h"
#include "ui/uifullbox.h"
#include "uifullbox.h"
#define UI_LOADING_TEXT "loading"
uiloading_t UI_LOADING;
void uiLoadingInit(void) {
errorret_t uiLoadingInit(void) {
memoryZero(&UI_LOADING, sizeof(uiloading_t));
uiLabelInit(&UI_LOADING.textLabel, &FONT_DEFAULT);
uiLabelSetText(&UI_LOADING.textLabel, UI_LOADING_TEXT);
eventInit(
&UI_LOADING.onTransitionEnd,
UI_LOADING.onTransitionEndCallbacks,
UI_LOADING.onTransitionEndUsers,
4
);
errorOk();
}
void uiLoadingUpdate(float_t delta) {
if(UI_LOADING.duration <= 0.0f || UI_LOADING.time >= UI_LOADING.duration)
return;
UI_LOADING.time += delta;
errorret_t uiLoadingUpdate(void) {
if(UI_LOADING.duration > 0.0f && UI_LOADING.time < UI_LOADING.duration) {
UI_LOADING.time += TIME.delta;
if(UI_LOADING.time >= UI_LOADING.duration) {
UI_LOADING.time = UI_LOADING.duration;
eventInvoke(&UI_LOADING.onTransitionEnd, &UI_LOADING);
}
}
errorOk();
}
errorret_t uiLoadingDraw(void) {
@@ -50,16 +54,19 @@ errorret_t uiLoadingDraw(void) {
if(alpha <= 0.0f) errorOk();
int32_t textW, textH;
textMeasure(UI_LOADING_TEXT, &FONT_DEFAULT, &textW, &textH);
uiLabelGetSize(&UI_LOADING.textLabel, &textW, &textH);
float_t x = (float_t)SCREEN.width - (float_t)textW - UI_LOADING_MARGIN;
float_t y = (float_t)SCREEN.height - (float_t)textH - UI_LOADING_MARGIN;
float_t x = (float_t)(SCREEN.scanX + SCREEN.scanWidth) -
(float_t)textW - UI_LOADING_MARGIN;
float_t y = (float_t)(SCREEN.scanY + SCREEN.scanHeight) -
(float_t)textH - UI_LOADING_MARGIN;
color_t color = COLOR_WHITE;
color.a = (uint8_t)(alpha * 255.0f);
uiLabelSetColor(&UI_LOADING.textLabel, color);
errorChain(textDraw(x, y, UI_LOADING_TEXT, color, &FONT_DEFAULT));
return spriteBatchFlush();
errorChain(uiLabelDraw(&UI_LOADING.textLabel, x, y));
errorOk();
}
static void uiLoadingTransition(
@@ -8,6 +8,7 @@
#pragma once
#include "error/error.h"
#include "event/event.h"
#include "ui/widget/uilabel.h"
#define UI_LOADING_FADE_DURATION 0.5f
#define UI_LOADING_MARGIN 8.0f
@@ -20,22 +21,25 @@ typedef struct {
eventcallback_t onTransitionEndCallbacks[4];
void *onTransitionEndUsers[4];
event_t onTransitionEnd;
uilabel_t textLabel;
} uiloading_t;
extern uiloading_t UI_LOADING;
/**
* Initializes the loading indicator.
*
* @return Any error that occurs.
*/
void uiLoadingInit(void);
errorret_t uiLoadingInit(void);
/**
* Advances the loading indicator fade transition. Fires onTransitionEnd once
* when the transition completes.
*
* @param delta Seconds elapsed since last update.
* @return Any error that occurs.
*/
void uiLoadingUpdate(float_t delta);
errorret_t uiLoadingUpdate(void);
/**
* Draws the loading indicator. No-op when fully transparent.
+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
uitransition.c
uitransitionfade.c
)
+81
View File
@@ -0,0 +1,81 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitransition.h"
#include "uitransitionfade.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "time/time.h"
#include "util/math.h"
uitransition_t UI_TRANSITION;
uitransitiondrawfunc_t UI_TRANSITION_TYPE_DRAW[UI_TRANSITION_TYPE_COUNT] = {
[UI_TRANSITION_TYPE_FADE] = uiTransitionFadeDraw
};
errorret_t uiTransitionInit(void) {
memoryZero(&UI_TRANSITION, sizeof(uitransition_t));
// uiTransitionStart((uitransitionstartparams_t){
// .duration = 5.0f,
// .type = UI_TRANSITION_TYPE_FADE,
// .params = {
// .fade = {
// .easing = EASING_OUT_QUART,
// .fromColor = COLOR_TRANSPARENT_BLACK,
// .toColor = COLOR_BLACK
// }
// },
// .finished = NULL,
// .user = NULL
// });
errorOk();
}
errorret_t uiTransitionUpdate(void) {
// Update time.
float_t newTime = UI_TRANSITION.data.time + TIME.delta;
UI_TRANSITION.data.time = mathClamp(
newTime,
0.0f,
UI_TRANSITION.data.duration
);
UI_TRANSITION.data.t = (
(UI_TRANSITION.data.duration <= 0.0f) ?
1.0f :
(UI_TRANSITION.data.time / UI_TRANSITION.data.duration)
);
if(UI_TRANSITION.data.t >= 1.0f && UI_TRANSITION.finished) {
UI_TRANSITION.finished(UI_TRANSITION.user);
}
errorOk();
}
errorret_t uiTransitionDraw(void) {
uitransitiondrawfunc_t draw = UI_TRANSITION_TYPE_DRAW[UI_TRANSITION.type];
if(!draw) errorOk();
return draw(&UI_TRANSITION.data);
}
void uiTransitionStart(const uitransitionstartparams_t info) {
assertTrue(info.type > UI_TRANSITION_TYPE_NULL, "Invalid type");
assertTrue(info.type < UI_TRANSITION_TYPE_COUNT, "Invalid type");
assertTrue(info.duration >= 0.0f, "Duration must be non-negative");
memoryZero(&UI_TRANSITION, sizeof(uitransition_t));
UI_TRANSITION.data.duration = info.duration;
UI_TRANSITION.type = info.type;
UI_TRANSITION.data.params = info.params;
UI_TRANSITION.finished = info.finished;
UI_TRANSITION.user = info.user;
}
+74
View File
@@ -0,0 +1,74 @@
/**
* 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"
#include "animation/easing.h"
#include "uitransitiondata.h"
typedef void (*uitransitioncallback_t)(void *user);
typedef enum {
UI_TRANSITION_TYPE_NULL,
UI_TRANSITION_TYPE_FADE,
UI_TRANSITION_TYPE_COUNT
} uitransitiontype_t;
extern uitransitiondrawfunc_t UI_TRANSITION_TYPE_DRAW[UI_TRANSITION_TYPE_COUNT];
typedef struct {
uitransitiondata_t data;
uitransitiontype_t type;
uitransitioncallback_t finished;
void *user;
} uitransition_t;
extern uitransition_t UI_TRANSITION;
/**
* Initializes the transition overlay, zeroing all fields and wiring the
* onTransitionEnd event.
*
* @return Any error that occurs.
*/
errorret_t uiTransitionInit(void);
/**
* Advances the transition. Fires onTransitionEnd once when it completes.
* Safe to call when no transition is running.
*
* @return Any error that occurs.
*/
errorret_t uiTransitionUpdate(void);
/**
* Renders the transition overlay. Skipped entirely when the current alpha
* is zero.
*
* @return Any error that occurs.
*/
errorret_t uiTransitionDraw(void);
typedef struct {
float_t duration;
uitransitiontype_t type;
uitransitionparams_t params;
uitransitioncallback_t finished;
void *user;
} uitransitionstartparams_t;
/**
* Starts a transition described by an info struct.
*
* @param info Transition parameters.
*/
void uiTransitionStart(const uitransitionstartparams_t info);
@@ -0,0 +1,23 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "uitransitionfade.h"
typedef union uitransitionparams_u {
uitransitionfade_t fade;
} uitransitionparams_t;
typedef struct uitransitiondata_s {
float_t time;
float_t duration;
float_t t;
uitransitionparams_t params;
} uitransitiondata_t;
typedef errorret_t (*uitransitiondrawfunc_t)(const uitransitiondata_t *data);
@@ -0,0 +1,56 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitransition.h"
#include "assert/assert.h"
#include "display/screen/screen.h"
#include "display/texture/texture.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
errorret_t uiTransitionFadeDraw(const uitransitiondata_t *data) {
assertNotNull(data, "data must not be NULL");
float_t e = easingApply(data->params.fade.easing, data->t);
float_t r = (float_t)(
data->params.fade.toColor.r - data->params.fade.fromColor.r
) * e;
float_t g = (float_t)(
data->params.fade.toColor.g - data->params.fade.fromColor.g
) * e;
float_t b = (float_t)(
data->params.fade.toColor.b - data->params.fade.fromColor.b
) * e;
float_t a = (float_t)(
data->params.fade.toColor.a - data->params.fade.fromColor.a
) * e;
color_t color = color4b(
data->params.fade.fromColor.r + (uint8_t)r,
data->params.fade.fromColor.g + (uint8_t)g,
data->params.fade.fromColor.b + (uint8_t)b,
data->params.fade.fromColor.a + (uint8_t)a
);
if(color.a == 0) errorOk();
spritebatchsprite_t sprite = {
.min = { 0.0f, 0.0f, 0.0f },
.max = { (float_t)SCREEN.width, (float_t)SCREEN.height, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
shadermaterial_t material = {
.unlit = {
.color = color,
.texture = NULL
}
};
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
errorOk();
}
@@ -0,0 +1,29 @@
/**
* 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"
#include "animation/easing.h"
typedef struct uitransitiondata_s uitransitiondata_t;
typedef struct {
color_t fromColor;
color_t toColor;
easingtype_t easing;
} uitransitionfade_t;
/**
* Renders a full-screen color overlay interpolated between fade->fromColor
* and fade->toColor using fade->easing. t is the raw normalized progress
* in [0, 1] before easing is applied. No-op when the resulting alpha is zero.
*
* @param fade The fade parameters.
* @return Any error that occurs.
*/
errorret_t uiTransitionFadeDraw(const uitransitiondata_t *fade);
+62
View File
@@ -0,0 +1,62 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "ui.h"
#include "util/memory.h"
#include "assert/assert.h"
#include "display/spritebatch/spritebatch.h"
#include "display/screen/screen.h"
#include "ui/uielement.h"
#include "ui/focus/uifocus.h"
ui_t UI;
errorret_t uiInit(void) {
memoryZero(&UI, sizeof(ui_t));
uiFocusInit();
uiElementsSort();
uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementInit(element));
element++;
}
errorOk();
}
errorret_t uiUpdate(void) {
uiFocusUpdate();
uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementUpdate(element));
element++;
}
errorOk();
}
errorret_t uiRender(void) {
const uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementDraw(element));
element++;
}
errorChain(spriteBatchFlush());
errorOk();
}
errorret_t uiDispose(void) {
uielement_t *element = &UI_ELEMENTS[0];
while(!uiElementIsNull(element)) {
errorChain(uiElementDispose(element));
element++;
}
errorOk();
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
typedef struct {
void *nothing;
} ui_t;
extern ui_t UI;
/**
* Initializes the UI system.
*/
errorret_t uiInit(void);
/**
* Updates the UI system.
*
* @return Any error that occurs.
*/
errorret_t uiUpdate(void);
/**
* Renders the UI system.
*
* @return Any error that occurs.
*/
errorret_t uiRender(void);
/**
* Disposes of the UI system.
*
* @return Any error that occurs.
*/
errorret_t uiDispose(void);
+86
View File
@@ -0,0 +1,86 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uielement.h"
#include "assert/assert.h"
#include "util/sort.h"
#include "ui/frame/uiframe.h"
#include "ui/debug/uifps.h"
#include "engine/engine.h"
#include "ui/overlay/uifullbox.h"
#include "ui/overlay/uiloading.h"
#include "ui/overlay/uicrop.h"
#include "ui/transition/uitransition.h"
#include "ui/debug/uiconsole.h"
#include "ui/frame/uiconfirm.h"
// Priming pass: X does nothing here, so this only exists to process any
// #include directives nested in uielementlist.h/ui/uielementgame.h at
// file scope (each such header's own #pragma once makes it a no-op on
// the real pass below, which happens inside UI_ELEMENTS[]'s braces,
// where a raw #include of a declaration would be invalid).
#define X(initFn, updateFn, drawFn, disposeFn, order) // do nothing
#include "uielementlist.h"
#undef X
uielement_t UI_ELEMENTS[] = {
#define X(initFn, updateFn, drawFn, disposeFn, elementOrder) \
{ \
.init = initFn, .update = updateFn, .draw = drawFn, \
.dispose = disposeFn, .order = elementOrder \
},
#include "uielementlist.h"
#undef X
{ 0 } // Null terminator
};
bool_t uiElementIsNull(const uielement_t *element) {
return element->init == NULL &&
element->update == NULL &&
element->draw == NULL &&
element->dispose == NULL;
}
int_t uiElementCompareOrder(const void *a, const void *b) {
const uielement_t *elementA = (const uielement_t *)a;
const uielement_t *elementB = (const uielement_t *)b;
if(elementA->order < elementB->order) return -1;
if(elementA->order > elementB->order) return 1;
return 0;
}
void uiElementsSort(void) {
// The trailing null terminator is always the last static entry -- sort
// everything before it, and leave it in place.
const size_t count = (sizeof(UI_ELEMENTS) / sizeof(UI_ELEMENTS[0])) - 1;
sortBubble(UI_ELEMENTS, count, sizeof(uielement_t), uiElementCompareOrder);
}
errorret_t uiElementInit(uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->init != NULL) errorChain(element->init());
errorOk();
}
errorret_t uiElementUpdate(uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->update != NULL) errorChain(element->update());
errorOk();
}
errorret_t uiElementDraw(const uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->draw != NULL) errorChain(element->draw());
errorOk();
}
errorret_t uiElementDispose(uielement_t *element) {
assertNotNull(element, "element must not be NULL");
if(element->dispose != NULL) errorChain(element->dispose());
errorOk();
}
+84
View File
@@ -0,0 +1,84 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
// Built-in order tiers. Lower values update/render first; ties preserve
// their relative UI_ELEMENTS declaration order (uiElementsSort uses a
// stable sort). Game-specific elements can use any int32_t value -- these
// are just the ones the engine itself relies on.
#define UI_ELEMENT_ORDER_DEFAULT 0
#define UI_ELEMENT_ORDER_DEBUG 1000
typedef struct {
errorret_t (*init)();
errorret_t (*update)();
errorret_t (*draw)();
errorret_t (*dispose)();
int32_t order;
} uielement_t;
extern uielement_t UI_ELEMENTS[];
/**
* Returns true when all four callbacks on the element are NULL,
* which marks the end of the UI_ELEMENTS array.
*
* @param element The element to test.
* @returns True if the element is the null terminator.
*/
bool_t uiElementIsNull(const uielement_t *element);
/**
* Compares two elements by their .order field, ascending. Matches
* sortcompare_t, for use with the project's sort utilities.
*
* @param a First uielement_t to compare.
* @param b Second uielement_t to compare.
* @return Negative if a < b, zero if a == b, positive if a > b.
*/
int_t uiElementCompareOrder(const void *a, const void *b);
/**
* Stably sorts UI_ELEMENTS in place by .order, ascending. The trailing
* null terminator is never moved. Called once by uiInit -- element order
* is static after that, so there's no need to re-sort every frame.
*/
void uiElementsSort(void);
/**
* Initializes a UI element, invoking its init callback if set.
*
* @param element The element to initialize.
* @return Any error that occurs.
*/
errorret_t uiElementInit(uielement_t *element);
/**
* Updates a UI element, calling its update callback if set.
*
* @param element The element to update.
* @return Any error that occurs.
*/
errorret_t uiElementUpdate(uielement_t *element);
/**
* Draws a UI element, calling its draw callback if set.
*
* @param element The element to render.
* @return Any error that occurs.
*/
errorret_t uiElementDraw(const uielement_t *element);
/**
* Disposes of a UI element, invoking its dispose callback if set.
*
* @param element The element to dispose.
* @return Any error that occurs.
*/
errorret_t uiElementDispose(uielement_t *element);
+47
View File
@@ -0,0 +1,47 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
// X(init, update, draw, dispose, order) -- pass NULL for any callback the
// element doesn't need. order controls update/draw sequence (lower first,
// see UI_ELEMENT_ORDER_* in uielement.h); ties preserve declaration order.
// See uielement.c for how this expands.
X(uiFrameInit, NULL, NULL, uiFrameDispose, UI_ELEMENT_ORDER_DEFAULT)
// Fullbox under: above scene, below system UI.
X(
uiFullboxUnderInit, uiFullboxUnderUpdate, uiFullboxUnderDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
// Text stuffs
X(uiConfirmInit, NULL, uiConfirmDraw, uiConfirmDispose, UI_ELEMENT_ORDER_DEFAULT)
X(
uiTransitionInit, uiTransitionUpdate, uiTransitionDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
// Fullbox over: above absolutely everything (except debug).
X(
uiFullboxOverInit, uiFullboxOverUpdate, uiFullboxOverDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
X(
uiLoadingInit, uiLoadingUpdate, uiLoadingDraw, NULL,
UI_ELEMENT_ORDER_DEFAULT
)
X(uiCropInit, NULL, uiCropDraw, NULL, UI_ELEMENT_ORDER_DEFAULT)
// Debug items -- always last.
X(NULL, NULL, uiConsoleDraw, uiConsoleDispose, UI_ELEMENT_ORDER_DEBUG)
X(uiFPSInit, NULL, uiFPSDraw, NULL, UI_ELEMENT_ORDER_DEBUG)
// Game-specific UI elements (duskrpg)
#include "ui/uielementgame.h"
+17
View File
@@ -0,0 +1,17 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
uibutton.c
uicheckbox.c
uitab.c
uislider.c
uidropdown.c
uiscrolling.c
uimenu.c
uilabel.c
uiwidgetlabel.c
)
+42
View File
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uibutton.h"
#include "assert/assert.h"
#include "display/text/text.h"
#include "display/color.h"
void uiButtonInit(uibutton_t *button, const char_t *label) {
assertNotNull(button, "Button cannot be NULL");
assertNotNull(label, "Label cannot be NULL");
uiWidgetLabelInit(&button->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&button->label, label);
button->highlighted = false;
}
bool_t uiButtonIsHighlighted(const uibutton_t *button) {
assertNotNull(button, "Button cannot be NULL");
return button->highlighted;
}
void uiButtonSetHighlighted(uibutton_t *button, const bool_t highlighted) {
assertNotNull(button, "Button cannot be NULL");
button->highlighted = highlighted;
uiWidgetLabelSetColor(
&button->label, highlighted ? COLOR_RED : COLOR_WHITE
);
}
errorret_t uiButtonDraw(
const uibutton_t *button,
const float_t x,
const float_t y
) {
assertNotNull(button, "Button cannot be NULL");
errorChain(uiWidgetLabelDraw(&button->label, x, y));
errorOk();
}
+53
View File
@@ -0,0 +1,53 @@
/**
* 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 "ui/widget/uiwidgetlabel.h"
typedef struct {
uiwidgetlabel_t label;
bool_t highlighted;
} uibutton_t;
/**
* Initializes a button.
*
* @param button The button to initialize.
* @param label Display label.
*/
void uiButtonInit(uibutton_t *button, const char_t *label);
/**
* Returns whether the button is highlighted.
*
* @param button The button to query.
* @returns True if highlighted.
*/
bool_t uiButtonIsHighlighted(const uibutton_t *button);
/**
* Sets the highlighted state of the button.
*
* @param button The button to update.
* @param highlighted The new highlighted state.
*/
void uiButtonSetHighlighted(uibutton_t *button, const bool_t highlighted);
/**
* Draws the button at the given screen position.
*
* @param button The button to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiButtonDraw(
const uibutton_t *button,
const float_t x,
const float_t y
);
+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
*/
#include "uicheckbox.h"
#include "util/memory.h"
#include "util/string.h"
#include "display/text/text.h"
#include "display/color.h"
void uiCheckboxInit(
uicheckbox_t *checkbox,
const char_t *label
) {
memoryZero(checkbox, sizeof(uicheckbox_t));
checkbox->rawLabel = label;
uiWidgetLabelInit(&checkbox->label, &FONT_DEFAULT);
uiCheckboxRebuildLabel(checkbox);
}
bool_t uiCheckboxIsChecked(const uicheckbox_t *checkbox) {
return checkbox->checked;
}
void uiCheckboxSetChecked(uicheckbox_t *checkbox, const bool_t checked) {
checkbox->checked = checked;
uiCheckboxRebuildLabel(checkbox);
}
void uiCheckboxToggle(uicheckbox_t *checkbox) {
uiCheckboxSetChecked(checkbox, !uiCheckboxIsChecked(checkbox));
}
bool_t uiCheckboxIsHighlighted(const uicheckbox_t *checkbox) {
return checkbox->highlighted;
}
void uiCheckboxSetHighlighted(uicheckbox_t *checkbox, const bool_t highlighted) {
checkbox->highlighted = highlighted;
uiWidgetLabelSetColor(
&checkbox->label, highlighted ? COLOR_RED : COLOR_WHITE
);
}
errorret_t uiCheckboxDraw(
const uicheckbox_t *checkbox,
const float_t x,
const float_t y
) {
errorChain(uiWidgetLabelDraw(&checkbox->label, x, y));
errorOk();
}
void uiCheckboxRebuildLabel(uicheckbox_t *checkbox) {
char_t combined[UI_WIDGET_LABEL_TEXT_MAX];
stringFormat(
combined, UI_WIDGET_LABEL_TEXT_MAX - 1, "%s %s",
checkbox->checked ? "Y" : "N", checkbox->rawLabel
);
uiWidgetLabelSetText(&checkbox->label, combined);
}
+90
View File
@@ -0,0 +1,90 @@
/**
* 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 "ui/widget/uiwidgetlabel.h"
typedef struct uicheckbox_s {
const char_t *rawLabel;
uiwidgetlabel_t label;
bool_t checked;
bool_t highlighted;
} uicheckbox_t;
/**
* Initializes a checkbox.
*
* @param checkbox The checkbox to initialize.
* @param label Display label.
*/
void uiCheckboxInit(
uicheckbox_t *checkbox,
const char_t *label
);
/**
* Returns whether the checkbox is checked.
*
* @param checkbox The checkbox to query.
* @returns True if checked.
*/
bool_t uiCheckboxIsChecked(const uicheckbox_t *checkbox);
/**
* Sets the checked state of the checkbox.
*
* @param checkbox The checkbox to update.
* @param checked The new checked state.
*/
void uiCheckboxSetChecked(uicheckbox_t *checkbox, const bool_t checked);
/**
* Toggles the checked state of the checkbox.
*
* @param checkbox The checkbox to toggle.
*/
void uiCheckboxToggle(uicheckbox_t *checkbox);
/**
* Returns whether the checkbox is highlighted.
*
* @param checkbox The checkbox to query.
* @returns True if highlighted.
*/
bool_t uiCheckboxIsHighlighted(const uicheckbox_t *checkbox);
/**
* Sets the highlighted state of the checkbox.
*
* @param checkbox The checkbox to update.
* @param highlighted The new highlighted state.
*/
void uiCheckboxSetHighlighted(uicheckbox_t *checkbox, const bool_t highlighted);
/**
* Draws the checkbox at the given screen position.
*
* @param checkbox The checkbox to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiCheckboxDraw(
const uicheckbox_t *checkbox,
const float_t x,
const float_t y
);
/**
* Rebuilds the checkbox's cached label ("Y "/"N " mark plus rawLabel)
* from its current checked state. Called internally whenever checked
* changes.
*
* @param checkbox The checkbox to update.
*/
void uiCheckboxRebuildLabel(uicheckbox_t *checkbox);
+110
View File
@@ -0,0 +1,110 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uidropdown.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "display/text/text.h"
#include "display/color.h"
void uiDropdownInit(
uidropdown_t *dropdown,
const char_t *label,
const char_t *const *options,
const uint8_t optionCount,
const uint8_t selectedIndex
) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
assertNotNull(label, "Label cannot be NULL");
assertNotNull(options, "Options cannot be NULL");
assertTrue(optionCount > 0, "Dropdown must have at least one option");
memoryZero(dropdown, sizeof(uidropdown_t));
uiWidgetLabelInit(&dropdown->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&dropdown->label, label);
uiWidgetLabelInit(&dropdown->value, &FONT_DEFAULT);
dropdown->options = options;
dropdown->optionCount = optionCount;
dropdown->selectedIndex = selectedIndex < optionCount ? selectedIndex : 0;
uiDropdownRebuildValue(dropdown);
}
uint8_t uiDropdownGetSelectedIndex(const uidropdown_t *dropdown) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
return dropdown->selectedIndex;
}
const char_t *uiDropdownGetSelectedOption(const uidropdown_t *dropdown) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
return dropdown->options[dropdown->selectedIndex];
}
void uiDropdownSetSelectedIndex(uidropdown_t *dropdown, const uint8_t index) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
assertTrue(index < dropdown->optionCount, "Dropdown index out of range");
dropdown->selectedIndex = index;
uiDropdownRebuildValue(dropdown);
}
void uiDropdownStepNext(uidropdown_t *dropdown) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
dropdown->selectedIndex =
(dropdown->selectedIndex + 1) % dropdown->optionCount;
uiDropdownRebuildValue(dropdown);
}
void uiDropdownStepPrev(uidropdown_t *dropdown) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
dropdown->selectedIndex = dropdown->selectedIndex == 0 ?
dropdown->optionCount - 1 : dropdown->selectedIndex - 1;
uiDropdownRebuildValue(dropdown);
}
bool_t uiDropdownIsHighlighted(const uidropdown_t *dropdown) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
return dropdown->highlighted;
}
void uiDropdownSetHighlighted(
uidropdown_t *dropdown,
const bool_t highlighted
) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
dropdown->highlighted = highlighted;
color_t color = highlighted ? COLOR_RED : COLOR_WHITE;
uiWidgetLabelSetColor(&dropdown->label, color);
uiWidgetLabelSetColor(&dropdown->value, color);
}
errorret_t uiDropdownDraw(
const uidropdown_t *dropdown,
const float_t x,
const float_t y
) {
assertNotNull(dropdown, "Dropdown cannot be NULL");
errorChain(uiWidgetLabelDraw(&dropdown->label, x, y));
int32_t labelW, labelH;
uiWidgetLabelGetSize(&dropdown->label, &labelW, &labelH);
errorChain(uiWidgetLabelDraw(
&dropdown->value, x + (float_t)labelW + UI_DROPDOWN_GAP, y
));
errorOk();
}
void uiDropdownRebuildValue(uidropdown_t *dropdown) {
char_t valueText[UI_WIDGET_LABEL_TEXT_MAX];
stringFormat(
valueText, UI_WIDGET_LABEL_TEXT_MAX - 1, "< %s >",
uiDropdownGetSelectedOption(dropdown)
);
uiWidgetLabelSetText(&dropdown->value, valueText);
}
+123
View File
@@ -0,0 +1,123 @@
/**
* 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 "ui/widget/uiwidgetlabel.h"
#define UI_DROPDOWN_GAP 4.0f
typedef struct {
uiwidgetlabel_t label;
uiwidgetlabel_t value;
const char_t *const *options;
uint8_t optionCount;
uint8_t selectedIndex;
bool_t highlighted;
} uidropdown_t;
/**
* Initializes a dropdown.
*
* @param dropdown The dropdown to initialize.
* @param label Display label.
* @param options Array of option display strings; caller-owned, must
* outlive the dropdown.
* @param optionCount Number of entries in options. Must be > 0.
* @param selectedIndex Initial selected option index, clamped to
* [0, optionCount - 1].
*/
void uiDropdownInit(
uidropdown_t *dropdown,
const char_t *label,
const char_t *const *options,
const uint8_t optionCount,
const uint8_t selectedIndex
);
/**
* Returns the index of the currently selected option.
*
* @param dropdown The dropdown to query.
* @returns The selected option index.
*/
uint8_t uiDropdownGetSelectedIndex(const uidropdown_t *dropdown);
/**
* Returns the currently selected option's display string.
*
* @param dropdown The dropdown to query.
* @returns The selected option string.
*/
const char_t *uiDropdownGetSelectedOption(const uidropdown_t *dropdown);
/**
* Sets the selected option by index.
*
* @param dropdown The dropdown to update.
* @param index The new selected option index. Must be < optionCount.
*/
void uiDropdownSetSelectedIndex(uidropdown_t *dropdown, const uint8_t index);
/**
* Selects the next option, wrapping around to the first option past
* the last.
*
* @param dropdown The dropdown to update.
*/
void uiDropdownStepNext(uidropdown_t *dropdown);
/**
* Selects the previous option, wrapping around to the last option
* before the first.
*
* @param dropdown The dropdown to update.
*/
void uiDropdownStepPrev(uidropdown_t *dropdown);
/**
* Returns whether the dropdown is highlighted.
*
* @param dropdown The dropdown to query.
* @returns True if highlighted.
*/
bool_t uiDropdownIsHighlighted(const uidropdown_t *dropdown);
/**
* Sets the highlighted state of the dropdown.
*
* @param dropdown The dropdown to update.
* @param highlighted The new highlighted state.
*/
void uiDropdownSetHighlighted(
uidropdown_t *dropdown,
const bool_t highlighted
);
/**
* Draws the dropdown at the given screen position: label, then the
* currently selected option surrounded by cycle arrows.
*
* @param dropdown The dropdown to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiDropdownDraw(
const uidropdown_t *dropdown,
const float_t x,
const float_t y
);
/**
* Rebuilds the dropdown's cached value label ("< option >") from its
* current selectedIndex. Called internally whenever selectedIndex
* changes.
*
* @param dropdown The dropdown to update.
*/
void uiDropdownRebuildValue(uidropdown_t *dropdown);
+70
View File
@@ -0,0 +1,70 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uilabel.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "display/text/text.h"
void uiLabelInit(uilabel_t *label, font_t *font) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(font, "Font cannot be NULL");
memoryZero(label, sizeof(uilabel_t));
label->font = font;
label->color = COLOR_WHITE;
}
void uiLabelSetText(uilabel_t *label, const char_t *text) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
assertStrLenMax(text, UI_LABEL_TEXT_MAX, "Label text too long");
stringCopy(label->text, text, UI_LABEL_TEXT_MAX);
label->spriteCount = textBuildSpriteCache(
label->text, label->font, label->sprites, UI_LABEL_SPRITE_COUNT_MAX,
&label->width, &label->height
);
}
void uiLabelSetColor(uilabel_t *label, const color_t color) {
assertNotNull(label, "Label cannot be NULL");
label->color = color;
}
void uiLabelGetSize(
const uilabel_t *label,
int32_t *outWidth,
int32_t *outHeight
) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(outWidth, "Output width cannot be NULL");
assertNotNull(outHeight, "Output height cannot be NULL");
*outWidth = label->width;
*outHeight = label->height;
}
errorret_t uiLabelDraw(
const uilabel_t *label,
const float_t x,
const float_t y
) {
assertNotNull(label, "Label cannot be NULL");
if(label->spriteCount == 0) errorOk();
// Cached sprites are relative to (0,0); textDrawSpriteCache translates
// into the requested screen position here instead of in
// uiLabelSetText, so a label can be repositioned every frame without
// rebuilding the (much more expensive) glyph/UV cache.
spritebatchsprite_t scratch[UI_LABEL_SPRITE_COUNT_MAX];
errorChain(textDrawSpriteCache(
label->sprites, label->spriteCount, scratch, x, y, label->color,
label->font->texture
));
errorOk();
}
+85
View File
@@ -0,0 +1,85 @@
/**
* 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/text/font.h"
#include "display/spritebatch/spritebatchsprite.h"
#include "display/color.h"
#define UI_LABEL_TEXT_MAX 256
#define UI_LABEL_SPRITE_COUNT_MAX UI_LABEL_TEXT_MAX
typedef struct {
char_t text[UI_LABEL_TEXT_MAX];
color_t color;
font_t *font;
spritebatchsprite_t sprites[UI_LABEL_SPRITE_COUNT_MAX];
uint32_t spriteCount;
int32_t width;
int32_t height;
} uilabel_t;
/**
* Initializes a label, defaulting to white text and no text set.
*
* @param label The label to initialize.
* @param font Font to use for rendering. Must outlive the label.
*/
void uiLabelInit(uilabel_t *label, font_t *font);
/**
* Sets the label's text, rebuilding its cached sprites (glyph lookup, UV,
* and layout) immediately. This is the only way the sprite cache gets
* rebuilt -- uiLabelDraw never recomputes it, so call this whenever the
* text changes rather than once up front and expecting it to stay in sync.
*
* @param label The label to update.
* @param text Null-terminated string to display. Must be shorter than
* UI_LABEL_TEXT_MAX.
*/
void uiLabelSetText(uilabel_t *label, const char_t *text);
/**
* Sets the label's tint color. Cheap -- doesn't touch the sprite cache,
* since color is applied via the draw material, not baked into sprites.
*
* @param label The label to update.
* @param color The new tint color.
*/
void uiLabelSetColor(uilabel_t *label, const color_t color);
/**
* Gets the measured size (in pixels) of the label's current text, cached
* from the last uiLabelSetText call.
*
* @param label The label to query.
* @param outWidth Pointer to store the width.
* @param outHeight Pointer to store the height.
*/
void uiLabelGetSize(
const uilabel_t *label,
int32_t *outWidth,
int32_t *outHeight
);
/**
* Draws the label's cached sprites at the given screen position in a
* single batched buffer call. Does not recompute glyph layout -- call
* uiLabelSetText first whenever the text changes.
*
* @param label The label to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiLabelDraw(
const uilabel_t *label,
const float_t x,
const float_t y
);
+293
View File
@@ -0,0 +1,293 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uimenu.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "display/text/text.h"
#include "display/color.h"
#include "ui/widget/uiwidgetlabel.h"
#include "ui/widget/uibutton.h"
#include "ui/widget/uitab.h"
#include "ui/widget/uislider.h"
#include "ui/widget/uidropdown.h"
void uiMenuInit(
uimenu_t *menu,
uimenuselectedcallback_t selected,
uimenuclosedcallback_t closed,
uimenuchangedcallback_t changed
) {
assertNotNull(menu, "Menu cannot be NULL");
memoryZero(menu, sizeof(uimenu_t));
menu->selected = selected;
menu->closed = closed;
menu->changed = changed;
}
void uiMenuSetItems(
uimenu_t *menu,
const uimenuitem_t *items,
const uint8_t itemCount,
const uint8_t columns
) {
assertNotNull(menu, "Menu cannot be NULL");
assertNotNull(items, "Items cannot be NULL");
assertTrue(itemCount > 0, "Item count must be > 0");
assertTrue(columns > 0, "Columns must be > 0");
menu->items = (uimenuitem_t *)items;
menu->itemCount = itemCount;
menu->columns = columns;
}
void uiMenuSetPosition(uimenu_t *menu, const uint8_t x, const uint8_t y) {
assertNotNull(menu, "Menu cannot be NULL");
if(menu->focusItem == NULL) return;
uiFocusSetPosition(menu->focusItem, x, y);
}
void uiMenuOpen(uimenu_t *menu) {
assertNotNull(menu, "Menu cannot be NULL");
assertNotNull(menu->items, "Menu items cannot be NULL");
assertTrue(menu->itemCount > 0, "Menu item count must be > 0");
assertTrue(menu->columns > 0, "Menu columns must be > 0");
if(menu->focusItem != NULL) return;
uint8_t focusable = uiMenuFocusableCount(menu);
uint8_t rows = focusable > 0 ?
(focusable + menu->columns - 1) / menu->columns : 1;
menu->focusItem = uiFocusPush(
menu->columns, rows,
uiMenuFocusSelected,
uiMenuFocusChanged,
uiMenuFocusClosed,
uiMenuFocusDirection,
menu
);
}
void uiMenuClose(uimenu_t *menu) {
assertNotNull(menu, "Menu cannot be NULL");
if(menu->focusItem == NULL) return;
uiFocusPopItem(menu->focusItem);
menu->focusItem = NULL;
}
bool_t uiMenuIsActive(const uimenu_t *menu) {
assertNotNull(menu, "Menu cannot be NULL");
return menu->focusItem != NULL;
}
errorret_t uiMenuDraw(
const uimenu_t *menu,
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
assertNotNull(menu, "Menu cannot be NULL");
if(menu->itemCount == 0) errorOk();
float_t colStep = width / (float_t)menu->columns;
float_t rowHeight = (float_t)FONT_DEFAULT.tileset->tileHeight;
uint8_t col = 0;
uint8_t row = 0;
for(uint8_t i = 0; i < menu->itemCount; i++) {
const uimenuitem_t *item = &menu->items[i];
if(item->type == UI_MENU_WIDGET_TYPE_LABEL) {
if(col > 0) { row++; col = 0; }
errorChain(uiWidgetLabelDraw(
&item->label, x, y + (float_t)row * rowHeight
));
row++;
continue;
}
if(item->type == UI_MENU_WIDGET_TYPE_SPACER) {
if(col > 0) { row++; col = 0; }
row++;
continue;
}
float_t ix = x + (float_t)col * colStep;
float_t iy = y + (float_t)row * rowHeight;
switch(item->type) {
case UI_MENU_WIDGET_TYPE_CHECKBOX:
errorChain(uiCheckboxDraw(&item->checkbox, ix, iy));
break;
case UI_MENU_WIDGET_TYPE_BUTTON:
errorChain(uiButtonDraw(&item->button, ix, iy));
break;
case UI_MENU_WIDGET_TYPE_TAB:
errorChain(uiTabDraw(&item->tab, ix, iy));
break;
case UI_MENU_WIDGET_TYPE_SLIDER:
errorChain(uiSliderDraw(&item->slider, ix, iy));
break;
case UI_MENU_WIDGET_TYPE_DROPDOWN:
errorChain(uiDropdownDraw(&item->dropdown, ix, iy));
break;
default:
break;
}
col++;
if(col >= menu->columns) { col = 0; row++; }
}
errorOk();
}
bool_t uiMenuFocusSelected(const uifocusitem_t *focusItem) {
assertNotNull(focusItem, "Focus item cannot be NULL");
assertNotNull(focusItem->user, "Focus item user cannot be NULL");
uimenu_t *menu = (uimenu_t *)focusItem->user;
if(menu->selected == NULL) return true;
uint8_t slot = focusItem->y * menu->columns + focusItem->x;
uint8_t index = uiMenuFocusSlotToIndex(menu, slot);
if(index == 0xFF) return true;
menu->selected(menu, index, &menu->items[index]);
return true;
}
bool_t uiMenuFocusChanged(const uifocusitem_t *focusItem) {
assertNotNull(focusItem, "Focus item cannot be NULL");
assertNotNull(focusItem->user, "Focus item user cannot be NULL");
uimenu_t *menu = (uimenu_t *)focusItem->user;
uint8_t focusSlot = focusItem->y * menu->columns + focusItem->x;
uint8_t slot = 0;
for(uint8_t i = 0; i < menu->itemCount; i++) {
uimenuitem_t *item = &menu->items[i];
if(
item->type == UI_MENU_WIDGET_TYPE_LABEL ||
item->type == UI_MENU_WIDGET_TYPE_SPACER
) continue;
uiMenuItemSetHighlighted(item, slot == focusSlot);
slot++;
}
if(menu->changed == NULL) return true;
uint8_t index = uiMenuFocusSlotToIndex(menu, focusSlot);
if(index == 0xFF) return true;
menu->changed(menu, index, &menu->items[index]);
return true;
}
bool_t uiMenuFocusClosed(const uifocusitem_t *focusItem) {
assertNotNull(focusItem, "Focus item cannot be NULL");
assertNotNull(focusItem->user, "Focus item user cannot be NULL");
uimenu_t *menu = (uimenu_t *)focusItem->user;
menu->focusItem = NULL;
for(uint8_t i = 0; i < menu->itemCount; i++) {
uiMenuItemSetHighlighted(&menu->items[i], false);
}
if(menu->closed != NULL) menu->closed(menu);
return true;
}
bool_t uiMenuFocusDirection(
const uifocusitem_t *focusItem,
const uifocusdirection_t direction
) {
assertNotNull(focusItem, "Focus item cannot be NULL");
assertNotNull(focusItem->user, "Focus item user cannot be NULL");
if(direction != UI_FOCUS_DIRECTION_LEFT && direction != UI_FOCUS_DIRECTION_RIGHT) {
return false;
}
uimenu_t *menu = (uimenu_t *)focusItem->user;
uint8_t slot = focusItem->y * menu->columns + focusItem->x;
uint8_t index = uiMenuFocusSlotToIndex(menu, slot);
if(index == 0xFF) return false;
uimenuitem_t *item = &menu->items[index];
bool_t right = direction == UI_FOCUS_DIRECTION_RIGHT;
if(item->type == UI_MENU_WIDGET_TYPE_SLIDER) {
if(right) {
uiSliderStepUp(&item->slider);
} else {
uiSliderStepDown(&item->slider);
}
return true;
}
if(item->type == UI_MENU_WIDGET_TYPE_CHECKBOX) {
uiCheckboxToggle(&item->checkbox);
return true;
}
if(item->type == UI_MENU_WIDGET_TYPE_DROPDOWN) {
if(right) {
uiDropdownStepNext(&item->dropdown);
} else {
uiDropdownStepPrev(&item->dropdown);
}
return true;
}
return false;
}
uint8_t uiMenuFocusableCount(const uimenu_t *menu) {
assertNotNull(menu, "Menu cannot be NULL");
uint8_t count = 0;
for(uint8_t i = 0; i < menu->itemCount; i++) {
uimenuwidgettype_t t = menu->items[i].type;
if(t != UI_MENU_WIDGET_TYPE_LABEL && t != UI_MENU_WIDGET_TYPE_SPACER) count++;
}
return count;
}
uint8_t uiMenuFocusSlotToIndex(const uimenu_t *menu, const uint8_t slot) {
assertNotNull(menu, "Menu cannot be NULL");
uint8_t focusable = 0;
for(uint8_t i = 0; i < menu->itemCount; i++) {
uimenuwidgettype_t t = menu->items[i].type;
if(t == UI_MENU_WIDGET_TYPE_LABEL || t == UI_MENU_WIDGET_TYPE_SPACER) continue;
if(focusable == slot) return i;
focusable++;
}
return 0xFF;
}
void uiMenuLabelInit(uimenuitem_t *item, const char_t *text) {
assertNotNull(item, "Item cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
uiWidgetLabelInit(&item->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&item->label, text);
}
void uiMenuItemSetHighlighted(uimenuitem_t *item, const bool_t highlighted) {
if(item->type == UI_MENU_WIDGET_TYPE_CHECKBOX) {
uiCheckboxSetHighlighted(&item->checkbox, highlighted);
} else if(item->type == UI_MENU_WIDGET_TYPE_BUTTON) {
uiButtonSetHighlighted(&item->button, highlighted);
} else if(item->type == UI_MENU_WIDGET_TYPE_TAB) {
uiTabSetActive(&item->tab, highlighted);
} else if(item->type == UI_MENU_WIDGET_TYPE_SLIDER) {
uiSliderSetHighlighted(&item->slider, highlighted);
} else if(item->type == UI_MENU_WIDGET_TYPE_DROPDOWN) {
uiDropdownSetHighlighted(&item->dropdown, highlighted);
}
}
+292
View File
@@ -0,0 +1,292 @@
/**
* 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 "ui/focus/uifocus.h"
#include "ui/widget/uiwidgetlabel.h"
#include "ui/widget/uibutton.h"
#include "ui/widget/uicheckbox.h"
#include "ui/widget/uitab.h"
#include "ui/widget/uislider.h"
#include "ui/widget/uidropdown.h"
typedef struct uimenu_s uimenu_t;
typedef enum {
UI_MENU_WIDGET_TYPE_NONE,
UI_MENU_WIDGET_TYPE_LABEL,
UI_MENU_WIDGET_TYPE_SPACER,
UI_MENU_WIDGET_TYPE_CHECKBOX,
UI_MENU_WIDGET_TYPE_BUTTON,
UI_MENU_WIDGET_TYPE_TAB,
UI_MENU_WIDGET_TYPE_SLIDER,
UI_MENU_WIDGET_TYPE_DROPDOWN,
} uimenuwidgettype_t;
typedef struct {
uimenuwidgettype_t type;
union {
uiwidgetlabel_t label;
uicheckbox_t checkbox;
uibutton_t button;
uitab_t tab;
uislider_t slider;
uidropdown_t dropdown;
};
} uimenuitem_t;
typedef void (*uimenuselectedcallback_t)(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
);
typedef void (*uimenuchangedcallback_t)(
const uimenu_t *menu,
const uint8_t index,
const uimenuitem_t *item
);
typedef void (*uimenuclosedcallback_t)(const uimenu_t *menu);
typedef struct uimenu_s {
uimenuitem_t *items;
uint8_t itemCount;
uint8_t columns;
uifocusitem_t *focusItem;
uimenuselectedcallback_t selected;
uimenuclosedcallback_t closed;
uimenuchangedcallback_t changed;
void *user;
} uimenu_t;
/**
* Initializes a menu, clearing all items and focus state.
*
* @param menu The menu to initialize.
* @param items The list of items to display in the menu.
* @param itemCount The number of items in the list.
* @param columns The number of columns to display the items in.
* @param selected The callback to invoke when an item is selected.
* @param closed The callback to invoke when the menu is closed.
* @param changed The callback to invoke when the menu changes.
*/
void uiMenuInit(
uimenu_t *menu,
uimenuselectedcallback_t selected,
uimenuclosedcallback_t closed,
uimenuchangedcallback_t changed
);
/**
* Sets the items to display in the menu.
*
* @param menu The menu to update.
* @param items The list of items to display in the menu.
* @param itemCount The number of items in the list.
* @param columns The number of columns to display the items in.
*/
void uiMenuSetItems(
uimenu_t *menu,
const uimenuitem_t *items,
const uint8_t itemCount,
const uint8_t columns
);
/**
* Sets the position of the menu on the screen.
*
* @param menu The menu to position.
* @param x The x-coordinate to position the menu at.
* @param y The y-coordinate to position the menu at.
*/
void uiMenuSetPosition(uimenu_t *menu, const uint8_t x, const uint8_t y);
/**
* Pushes a menu onto the UI focus stack, making it the active menu.
*
* @param menu The menu to push.
*/
void uiMenuOpen(uimenu_t *menu);
/**
* Pops a menu from the UI focus stack, removing it from the active menu.
*
* @param menu The menu to pop.
*/
void uiMenuClose(uimenu_t *menu);
/**
* Returns whether the menu is currently active (on the UI focus stack).
*
* @param menu The menu to query.
* @returns True if the menu is active.
*/
bool_t uiMenuIsActive(const uimenu_t *menu);
/**
* Draws the menu at the specified position and size.
*
* @param menu The menu to draw.
* @param x The x-coordinate to draw the menu at.
* @param y The y-coordinate to draw the menu at.
* @param width The width of the menu.
* @param height The height of the menu.
* @returns An error code indicating success or failure.
*/
errorret_t uiMenuDraw(
const uimenu_t *menu,
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* Returns the number of focusable (non-label) items in the menu.
*
* @param menu The menu to query.
* @returns Count of non-label items.
*/
uint8_t uiMenuFocusableCount(const uimenu_t *menu);
/**
* Maps a flat focus slot index to the corresponding item array index,
* skipping over label items which are not focusable.
*
* @param menu The menu to query.
* @param slot The focus slot index (y * columns + x).
* @returns The item array index, or 0xFF if out of range.
*/
uint8_t uiMenuFocusSlotToIndex(const uimenu_t *menu, const uint8_t slot);
/**
* Sets the highlighted/active state on a menu item, dispatching to the
* matching widget's setter based on its type. No-op for label/spacer
* items and any other type with no highlight concept.
*
* @param item The item to update.
* @param highlighted The new highlighted/active state.
*/
void uiMenuItemSetHighlighted(uimenuitem_t *item, const bool_t highlighted);
/**
* Initializes a menu item as a standalone label, caching its text.
* Used internally by the MENU_LABEL helper macro.
*
* @param item The item to initialize.
* @param text Display text.
*/
void uiMenuLabelInit(uimenuitem_t *item, const char_t *text);
/**
* Internal focus callback - forwards selection to the menu's selected handler.
*
* @param focusItem The active focus item; user field must point to uimenu_t.
* @returns True.
*/
bool_t uiMenuFocusSelected(const uifocusitem_t *focusItem);
/**
* Internal focus callback - updates widget highlights and fires changed.
*
* @param focusItem The active focus item; user field must point to uimenu_t.
* @returns True.
*/
bool_t uiMenuFocusChanged(const uifocusitem_t *focusItem);
/**
* Internal focus callback - clears focusItem and fires the closed handler.
*
* @param focusItem The active focus item; user field must point to uimenu_t.
* @returns True.
*/
bool_t uiMenuFocusClosed(const uifocusitem_t *focusItem);
/**
* Internal focus callback - gives the focused item's widget a chance to
* handle LEFT/RIGHT itself (e.g. a slider adjusting its value) before
* falling back to the default cell-to-cell movement.
*
* @param focusItem The active focus item; user field must point to uimenu_t.
* @param direction The direction that was pressed or held.
* @returns True if the focused widget handled the direction.
*/
bool_t uiMenuFocusDirection(
const uifocusitem_t *focusItem,
const uifocusdirection_t direction
);
// Helper macros
#define MENU_BEGIN(menuPtr, itemsArray, selected, closed, changed) \
uimenu_t *menu = (menuPtr); \
uiMenuInit(menu, selected, closed, changed); \
menu->items = (itemsArray); \
uint8_t menuIndex = 0; \
uint8_t menuCapacity = sizeof(itemsArray) / sizeof((itemsArray)[0])
#define MENU_LABEL(text) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_LABEL; \
uiMenuLabelInit(&menu->items[menuIndex], text); \
++menuIndex
#define MENU_SPACER() \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_SPACER; \
++menuIndex
#define MENU_CHECKBOX(label) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_CHECKBOX; \
uiCheckboxInit(&menu->items[menuIndex].checkbox, label); \
++menuIndex
#define MENU_BUTTON(label) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_BUTTON; \
uiButtonInit(&menu->items[menuIndex].button, label); \
++menuIndex
#define MENU_TAB(label) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_TAB; \
uiTabInit(&menu->items[menuIndex].tab, label); \
++menuIndex
#define MENU_SLIDER_FLOAT(label, value, min, max, step) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_SLIDER; \
uiSliderInitFloat( \
&menu->items[menuIndex].slider, label, value, min, max, step \
); \
++menuIndex
#define MENU_SLIDER_INT(label, value, min, max, step) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_SLIDER; \
uiSliderInitInt( \
&menu->items[menuIndex].slider, label, value, min, max, step \
); \
++menuIndex
#define MENU_DROPDOWN(label, options, optionCount, selectedIndex) \
assertTrue(menuIndex < menuCapacity, "Menu item count exceeds capacity"); \
menu->items[menuIndex].type = UI_MENU_WIDGET_TYPE_DROPDOWN; \
uiDropdownInit( \
&menu->items[menuIndex].dropdown, label, options, optionCount, \
selectedIndex \
); \
++menuIndex
#define MENU_END(itemsArray, columns) \
uiMenuSetItems(menu, (itemsArray), menuIndex, (columns))
//EOF
+15
View File
@@ -0,0 +1,15 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiscrolling.h"
#include "assert/assert.h"
void uiScrollingInit(uiscrolling_t *scrolling) {
assertNotNull(scrolling, "Scrolling container cannot be NULL");
// Nothing to initialize yet -- uiscrolling_t is currently a
// placeholder with no fields.
}
+21
View File
@@ -0,0 +1,21 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
typedef struct {
} uiscrolling_t;
/**
* Initializes a scrolling container. Currently a placeholder -- no
* scrolling behavior is implemented yet.
*
* @param scrolling The scrolling container to initialize.
*/
void uiScrollingInit(uiscrolling_t *scrolling);
+282
View File
@@ -0,0 +1,282 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uislider.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/math.h"
#include "util/string.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/texture/texture.h"
#include "display/shader/shaderunlit.h"
void uiSliderInitFloat(
uislider_t *slider,
const char_t *label,
const float_t value,
const float_t min,
const float_t max,
const float_t step
) {
assertNotNull(slider, "Slider cannot be NULL");
assertNotNull(label, "Label cannot be NULL");
assertTrue(max > min, "Slider max must be greater than min");
assertTrue(step > 0.0f, "Slider step must be greater than zero");
memoryZero(slider, sizeof(uislider_t));
uiWidgetLabelInit(&slider->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&slider->label, label);
uiWidgetLabelInit(&slider->valueLabel, &FONT_DEFAULT);
slider->type = UI_SLIDER_TYPE_FLOAT;
slider->min.f = min;
slider->max.f = max;
slider->step.f = step;
slider->value.f = mathClamp(value, min, max);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
void uiSliderInitInt(
uislider_t *slider,
const char_t *label,
const int32_t value,
const int32_t min,
const int32_t max,
const int32_t step
) {
assertNotNull(slider, "Slider cannot be NULL");
assertNotNull(label, "Label cannot be NULL");
assertTrue(max > min, "Slider max must be greater than min");
assertTrue(step > 0, "Slider step must be greater than zero");
memoryZero(slider, sizeof(uislider_t));
uiWidgetLabelInit(&slider->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&slider->label, label);
uiWidgetLabelInit(&slider->valueLabel, &FONT_DEFAULT);
slider->type = UI_SLIDER_TYPE_INT;
slider->min.i = min;
slider->max.i = max;
slider->step.i = step;
slider->value.i = mathClamp(value, min, max);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
float_t uiSliderGetFloat(const uislider_t *slider) {
assertNotNull(slider, "Slider cannot be NULL");
return slider->type == UI_SLIDER_TYPE_INT ?
(float_t)slider->value.i : slider->value.f;
}
int32_t uiSliderGetInt(const uislider_t *slider) {
assertNotNull(slider, "Slider cannot be NULL");
assertTrue(
slider->type == UI_SLIDER_TYPE_INT, "Slider is not an int slider"
);
return slider->value.i;
}
void uiSliderSetFloat(uislider_t *slider, const float_t value) {
assertNotNull(slider, "Slider cannot be NULL");
assertTrue(
slider->type == UI_SLIDER_TYPE_FLOAT, "Slider is not a float slider"
);
slider->value.f = mathClamp(value, slider->min.f, slider->max.f);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
void uiSliderSetInt(uislider_t *slider, const int32_t value) {
assertNotNull(slider, "Slider cannot be NULL");
assertTrue(
slider->type == UI_SLIDER_TYPE_INT, "Slider is not an int slider"
);
slider->value.i = mathClamp(value, slider->min.i, slider->max.i);
uiSliderRebuildValueLabel(slider);
uiSliderRebuildGeometry(slider);
}
void uiSliderStepUp(uislider_t *slider) {
assertNotNull(slider, "Slider cannot be NULL");
if(slider->type == UI_SLIDER_TYPE_INT) {
int32_t next = slider->value.i + slider->step.i;
uiSliderSetInt(slider, next > slider->max.i ? slider->min.i : next);
} else {
float_t next = slider->value.f + slider->step.f;
uiSliderSetFloat(slider, next > slider->max.f ? slider->min.f : next);
}
}
void uiSliderStepDown(uislider_t *slider) {
assertNotNull(slider, "Slider cannot be NULL");
if(slider->type == UI_SLIDER_TYPE_INT) {
int32_t next = slider->value.i - slider->step.i;
uiSliderSetInt(slider, next < slider->min.i ? slider->max.i : next);
} else {
float_t next = slider->value.f - slider->step.f;
uiSliderSetFloat(slider, next < slider->min.f ? slider->max.f : next);
}
}
float_t uiSliderGetRatio(const uislider_t *slider) {
assertNotNull(slider, "Slider cannot be NULL");
if(slider->type == UI_SLIDER_TYPE_INT) {
if(slider->max.i == slider->min.i) return 0.0f;
return (float_t)(slider->value.i - slider->min.i) /
(float_t)(slider->max.i - slider->min.i);
}
if(slider->max.f == slider->min.f) return 0.0f;
return (slider->value.f - slider->min.f) / (slider->max.f - slider->min.f);
}
int32_t uiSliderGetStepCount(const uislider_t *slider) {
assertNotNull(slider, "Slider cannot be NULL");
if(slider->type != UI_SLIDER_TYPE_INT || slider->step.i <= 0) return 0;
return (slider->max.i - slider->min.i) / slider->step.i;
}
bool_t uiSliderIsHighlighted(const uislider_t *slider) {
assertNotNull(slider, "Slider cannot be NULL");
return slider->highlighted;
}
void uiSliderSetHighlighted(uislider_t *slider, const bool_t highlighted) {
assertNotNull(slider, "Slider cannot be NULL");
slider->highlighted = highlighted;
color_t color = highlighted ? COLOR_RED : COLOR_WHITE;
uiWidgetLabelSetColor(&slider->label, color);
uiWidgetLabelSetColor(&slider->valueLabel, color);
}
errorret_t uiSliderDraw(
const uislider_t *slider,
const float_t x,
const float_t y
) {
assertNotNull(slider, "Slider cannot be NULL");
errorChain(uiWidgetLabelDraw(&slider->label, x, y));
shadermaterial_t trackMaterial = {
.unlit = {
.color = COLOR_DARK_GRAY,
.texture = &TEXTURE_WHITE
}
};
spritebatchsprite_t track = spriteBatchSpriteTranslate(
&slider->cachedTrack, x, y
);
errorChain(spriteBatchBuffer(&track, 1, &SHADER_UNLIT, trackMaterial));
if(slider->cachedFillVisible) {
shadermaterial_t fillMaterial = {
.unlit = {
.color = slider->highlighted ? COLOR_RED : COLOR_WHITE,
.texture = &TEXTURE_WHITE
}
};
spritebatchsprite_t fill = spriteBatchSpriteTranslate(
&slider->cachedFill, x, y
);
errorChain(spriteBatchBuffer(&fill, 1, &SHADER_UNLIT, fillMaterial));
}
if(slider->cachedMarkerCount > 0) {
spritebatchsprite_t markers[UI_SLIDER_STEP_MARKERS_MAX];
for(int32_t i = 0; i < slider->cachedMarkerCount; i++) {
markers[i] = spriteBatchSpriteTranslate(&slider->cachedMarkers[i], x, y);
}
shadermaterial_t markerMaterial = {
.unlit = {
.color = COLOR_WHITE,
.texture = &TEXTURE_WHITE
}
};
errorChain(spriteBatchBuffer(
markers, slider->cachedMarkerCount, &SHADER_UNLIT, markerMaterial
));
}
errorChain(uiWidgetLabelDraw(
&slider->valueLabel,
x + slider->cachedTrack.max[0] + UI_SLIDER_GAP,
y
));
errorOk();
}
void uiSliderRebuildValueLabel(uislider_t *slider) {
char_t valueText[UI_WIDGET_LABEL_TEXT_MAX];
if(slider->type == UI_SLIDER_TYPE_INT) {
stringFormat(
valueText, UI_WIDGET_LABEL_TEXT_MAX - 1, "%d", slider->value.i
);
} else {
stringFormat(
valueText, UI_WIDGET_LABEL_TEXT_MAX - 1, "%.2f", slider->value.f
);
}
uiWidgetLabelSetText(&slider->valueLabel, valueText);
}
void uiSliderRebuildGeometry(uislider_t *slider) {
int32_t labelW, labelH;
uiWidgetLabelGetSize(&slider->label, &labelW, &labelH);
float_t trackX = (float_t)labelW + UI_SLIDER_GAP;
float_t trackY = ((float_t)labelH - UI_SLIDER_TRACK_HEIGHT) * 0.5f;
slider->cachedTrack = (spritebatchsprite_t){
.min = { trackX, trackY, 0.0f },
.max = {
trackX + UI_SLIDER_TRACK_WIDTH, trackY + UI_SLIDER_TRACK_HEIGHT, 0.0f
},
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
float_t fillWidth = UI_SLIDER_TRACK_WIDTH * uiSliderGetRatio(slider);
slider->cachedFillVisible = fillWidth > 0.0f;
if(slider->cachedFillVisible) {
slider->cachedFill = (spritebatchsprite_t){
.min = { trackX, trackY, 0.0f },
.max = { trackX + fillWidth, trackY + UI_SLIDER_TRACK_HEIGHT, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
int32_t stepCount = uiSliderGetStepCount(slider);
if(stepCount > 0 && stepCount < UI_SLIDER_STEP_MARKERS_MAX) {
for(int32_t i = 0; i <= stepCount; i++) {
float_t markerX = trackX +
UI_SLIDER_TRACK_WIDTH * (float_t)i / (float_t)stepCount;
slider->cachedMarkers[i] = (spritebatchsprite_t){
.min = {
markerX - UI_SLIDER_STEP_MARKER_WIDTH * 0.5f,
trackY - UI_SLIDER_STEP_MARKER_OVERHANG,
0.0f
},
.max = {
markerX + UI_SLIDER_STEP_MARKER_WIDTH * 0.5f,
trackY + UI_SLIDER_TRACK_HEIGHT + UI_SLIDER_STEP_MARKER_OVERHANG,
0.0f
},
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
slider->cachedMarkerCount = stepCount + 1;
} else {
slider->cachedMarkerCount = 0;
}
}
+215
View File
@@ -0,0 +1,215 @@
/**
* 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 "ui/widget/uiwidgetlabel.h"
#include "display/spritebatch/spritebatchsprite.h"
#define UI_SLIDER_TRACK_WIDTH 80.0f
#define UI_SLIDER_TRACK_HEIGHT 4.0f
#define UI_SLIDER_STEP_MARKER_WIDTH 2.0f
#define UI_SLIDER_STEP_MARKER_OVERHANG 1.0f
#define UI_SLIDER_GAP 4.0f
/**
* Number of discrete steps below which an int slider renders individual
* step markers on its track instead of a smooth fill.
*/
#define UI_SLIDER_STEP_MARKERS_MAX 10
typedef enum {
UI_SLIDER_TYPE_FLOAT,
UI_SLIDER_TYPE_INT,
UI_SLIDER_TYPE_COUNT
} uislidertype_t;
typedef union {
float_t f;
int32_t i;
} uislidervalue_t;
typedef struct {
uiwidgetlabel_t label;
uiwidgetlabel_t valueLabel;
uislidertype_t type;
uislidervalue_t value;
uislidervalue_t min;
uislidervalue_t max;
uislidervalue_t step;
bool_t highlighted;
// Track/fill/marker geometry, cached relative to origin (0,0) and only
// rebuilt when the value or step configuration changes (see
// uiSliderRebuildGeometry) -- uiSliderDraw just translates these into
// position instead of re-deriving them every frame.
spritebatchsprite_t cachedTrack;
spritebatchsprite_t cachedFill;
bool_t cachedFillVisible;
spritebatchsprite_t cachedMarkers[UI_SLIDER_STEP_MARKERS_MAX];
int32_t cachedMarkerCount;
} uislider_t;
/**
* Initializes a floating point slider.
*
* @param slider The slider to initialize.
* @param label Display label.
* @param value Initial value, clamped to [min, max].
* @param min Minimum value.
* @param max Maximum value.
* @param step The amount a single step moves the value by.
*/
void uiSliderInitFloat(
uislider_t *slider,
const char_t *label,
const float_t value,
const float_t min,
const float_t max,
const float_t step
);
/**
* Initializes an integer slider.
*
* @param slider The slider to initialize.
* @param label Display label.
* @param value Initial value, clamped to [min, max].
* @param min Minimum value.
* @param max Maximum value.
* @param step The amount a single step moves the value by.
*/
void uiSliderInitInt(
uislider_t *slider,
const char_t *label,
const int32_t value,
const int32_t min,
const int32_t max,
const int32_t step
);
/**
* Returns the slider's current value as a float. Works for both slider
* types; int values are widened to float.
*
* @param slider The slider to query.
* @returns The current value.
*/
float_t uiSliderGetFloat(const uislider_t *slider);
/**
* Returns the slider's current value as an int. Only valid for
* UI_SLIDER_TYPE_INT sliders.
*
* @param slider The slider to query.
* @returns The current value.
*/
int32_t uiSliderGetInt(const uislider_t *slider);
/**
* Sets the slider's value, clamped to [min, max]. Only valid for
* UI_SLIDER_TYPE_FLOAT sliders.
*
* @param slider The slider to update.
* @param value The new value.
*/
void uiSliderSetFloat(uislider_t *slider, const float_t value);
/**
* Sets the slider's value, clamped to [min, max]. Only valid for
* UI_SLIDER_TYPE_INT sliders.
*
* @param slider The slider to update.
* @param value The new value.
*/
void uiSliderSetInt(uislider_t *slider, const int32_t value);
/**
* Moves the slider's value up by one step, wrapping around to its min
* if the step would exceed its max.
*
* @param slider The slider to update.
*/
void uiSliderStepUp(uislider_t *slider);
/**
* Moves the slider's value down by one step, wrapping around to its
* max if the step would go below its min.
*
* @param slider The slider to update.
*/
void uiSliderStepDown(uislider_t *slider);
/**
* Returns the slider's current value normalized to a 0..1 range based
* on its min/max.
*
* @param slider The slider to query.
* @returns The normalized value.
*/
float_t uiSliderGetRatio(const uislider_t *slider);
/**
* Returns the number of discrete steps between min and max. Always 0
* for float sliders.
*
* @param slider The slider to query.
* @returns The step count.
*/
int32_t uiSliderGetStepCount(const uislider_t *slider);
/**
* Returns whether the slider is highlighted.
*
* @param slider The slider to query.
* @returns True if highlighted.
*/
bool_t uiSliderIsHighlighted(const uislider_t *slider);
/**
* Sets the highlighted state of the slider.
*
* @param slider The slider to update.
* @param highlighted The new highlighted state.
*/
void uiSliderSetHighlighted(uislider_t *slider, const bool_t highlighted);
/**
* Draws the slider at the given screen position: label, then track,
* then the current value as text. Int sliders with fewer than
* UI_SLIDER_STEP_MARKERS_MAX discrete steps render a marker per step
* instead of a plain track.
*
* @param slider The slider to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiSliderDraw(
const uislider_t *slider,
const float_t x,
const float_t y
);
/**
* Rebuilds the slider's cached value label from its current value.
* Called internally whenever value changes.
*
* @param slider The slider to update.
*/
void uiSliderRebuildValueLabel(uislider_t *slider);
/**
* Rebuilds the slider's cached track/fill/marker geometry (relative to
* origin (0,0)) from its current label size, value, and step
* configuration. Called internally on init and whenever the value
* changes -- uiSliderDraw never recomputes this itself.
*
* @param slider The slider to update.
*/
void uiSliderRebuildGeometry(uislider_t *slider);
+69
View File
@@ -0,0 +1,69 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitab.h"
#include "assert/assert.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/texture/texture.h"
#include "display/shader/shaderunlit.h"
void uiTabInit(uitab_t *tab, const char_t *label) {
assertNotNull(tab, "Tab cannot be NULL");
assertNotNull(label, "Label cannot be NULL");
uiWidgetLabelInit(&tab->label, &FONT_DEFAULT);
uiWidgetLabelSetText(&tab->label, label);
tab->active = false;
uiTabRebuildBackground(tab);
}
bool_t uiTabIsActive(const uitab_t *tab) {
assertNotNull(tab, "Tab cannot be NULL");
return tab->active;
}
void uiTabSetActive(uitab_t *tab, const bool_t active) {
assertNotNull(tab, "Tab cannot be NULL");
tab->active = active;
}
errorret_t uiTabDraw(
const uitab_t *tab,
const float_t x,
const float_t y
) {
assertNotNull(tab, "Tab cannot be NULL");
spritebatchsprite_t sprite = spriteBatchSpriteTranslate(
&tab->cachedBackground, x, y
);
shadermaterial_t material = {
.unlit = {
.color = tab->active ? COLOR_GREEN : COLOR_RED,
.texture = &TEXTURE_WHITE
}
};
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
errorChain(uiWidgetLabelDraw(&tab->label, x, y));
errorOk();
}
void uiTabRebuildBackground(uitab_t *tab) {
assertNotNull(tab, "Tab cannot be NULL");
int32_t labelW, labelH;
uiWidgetLabelGetSize(&tab->label, &labelW, &labelH);
tab->cachedBackground = (spritebatchsprite_t){
.min = { 0.0f, 0.0f, 0.0f },
.max = { (float_t)labelW, (float_t)labelH, 0.0f },
.uvMin = { 0.0f, 0.0f },
.uvMax = { 1.0f, 1.0f }
};
}
+70
View File
@@ -0,0 +1,70 @@
/**
* 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 "ui/widget/uiwidgetlabel.h"
#include "display/spritebatch/spritebatchsprite.h"
typedef struct {
uiwidgetlabel_t label;
bool_t active;
// Background quad, cached relative to origin (0,0) from the label's
// size at init -- uiTabDraw only translates this into position, since
// active/inactive only changes the material color, not the geometry.
spritebatchsprite_t cachedBackground;
} uitab_t;
/**
* Initializes a tab.
*
* @param tab The tab to initialize.
* @param label Display label.
*/
void uiTabInit(uitab_t *tab, const char_t *label);
/**
* Returns whether the tab is active.
*
* @param tab The tab to query.
* @returns True if active.
*/
bool_t uiTabIsActive(const uitab_t *tab);
/**
* Sets the active state of the tab.
*
* @param tab The tab to update.
* @param active The new active state.
*/
void uiTabSetActive(uitab_t *tab, const bool_t active);
/**
* Draws the tab at the given screen position. Active tabs draw with a
* green background; inactive tabs draw with a red background.
*
* @param tab The tab to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiTabDraw(
const uitab_t *tab,
const float_t x,
const float_t y
);
/**
* Rebuilds the tab's cached background quad (relative to origin (0,0))
* from its current label size. Called internally by uiTabInit -- the
* background's geometry never changes afterwards, since the tab has no
* API to change its label text.
*
* @param tab The tab to update.
*/
void uiTabRebuildBackground(uitab_t *tab);
+66
View File
@@ -0,0 +1,66 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uiwidgetlabel.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "display/text/text.h"
void uiWidgetLabelInit(uiwidgetlabel_t *label, font_t *font) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(font, "Font cannot be NULL");
memoryZero(label, sizeof(uiwidgetlabel_t));
label->font = font;
label->color = COLOR_WHITE;
}
void uiWidgetLabelSetText(uiwidgetlabel_t *label, const char_t *text) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
assertStrLenMax(text, UI_WIDGET_LABEL_TEXT_MAX, "Label text too long");
stringCopy(label->text, text, UI_WIDGET_LABEL_TEXT_MAX);
label->spriteCount = textBuildSpriteCache(
label->text, label->font, label->sprites,
UI_WIDGET_LABEL_SPRITE_COUNT_MAX, &label->width, &label->height
);
}
void uiWidgetLabelSetColor(uiwidgetlabel_t *label, const color_t color) {
assertNotNull(label, "Label cannot be NULL");
label->color = color;
}
void uiWidgetLabelGetSize(
const uiwidgetlabel_t *label,
int32_t *outWidth,
int32_t *outHeight
) {
assertNotNull(label, "Label cannot be NULL");
assertNotNull(outWidth, "Output width cannot be NULL");
assertNotNull(outHeight, "Output height cannot be NULL");
*outWidth = label->width;
*outHeight = label->height;
}
errorret_t uiWidgetLabelDraw(
const uiwidgetlabel_t *label,
const float_t x,
const float_t y
) {
assertNotNull(label, "Label cannot be NULL");
if(label->spriteCount == 0) errorOk();
spritebatchsprite_t scratch[UI_WIDGET_LABEL_SPRITE_COUNT_MAX];
errorChain(textDrawSpriteCache(
label->sprites, label->spriteCount, scratch, x, y, label->color,
label->font->texture
));
errorOk();
}
+90
View File
@@ -0,0 +1,90 @@
/**
* 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/text/font.h"
#include "display/spritebatch/spritebatchsprite.h"
#include "display/color.h"
// A cached, cheap-to-redraw label sized for embedding directly inside
// small widgets (buttons, checkboxes, sliders, ...) rather than
// referencing text by pointer and re-deriving glyph geometry every
// frame. Capacity is intentionally much smaller than uilabel_t's -- it
// gets embedded by value in every widget instance (and inside
// uimenuitem_t's union, which is often arrayed), so keeping it small
// matters on memory-constrained targets. See uilabel_t for the
// general-purpose, larger-capacity equivalent.
#define UI_WIDGET_LABEL_TEXT_MAX 64
#define UI_WIDGET_LABEL_SPRITE_COUNT_MAX UI_WIDGET_LABEL_TEXT_MAX
typedef struct {
char_t text[UI_WIDGET_LABEL_TEXT_MAX];
color_t color;
font_t *font;
spritebatchsprite_t sprites[UI_WIDGET_LABEL_SPRITE_COUNT_MAX];
uint32_t spriteCount;
int32_t width;
int32_t height;
} uiwidgetlabel_t;
/**
* Initializes a widget label, defaulting to white text and no text set.
*
* @param label The label to initialize.
* @param font Font to use for rendering. Must outlive the label.
*/
void uiWidgetLabelInit(uiwidgetlabel_t *label, font_t *font);
/**
* Sets the label's text, rebuilding its cached sprites immediately.
* Call this whenever the displayed text changes -- uiWidgetLabelDraw
* never recomputes it.
*
* @param label The label to update.
* @param text Null-terminated string to display. Must be shorter than
* UI_WIDGET_LABEL_TEXT_MAX.
*/
void uiWidgetLabelSetText(uiwidgetlabel_t *label, const char_t *text);
/**
* Sets the label's tint color. Cheap -- doesn't touch the sprite cache.
*
* @param label The label to update.
* @param color The new tint color.
*/
void uiWidgetLabelSetColor(uiwidgetlabel_t *label, const color_t color);
/**
* Gets the measured size (in pixels) of the label's current text, cached
* from the last uiWidgetLabelSetText call.
*
* @param label The label to query.
* @param outWidth Pointer to store the width.
* @param outHeight Pointer to store the height.
*/
void uiWidgetLabelGetSize(
const uiwidgetlabel_t *label,
int32_t *outWidth,
int32_t *outHeight
);
/**
* Draws the label's cached sprites at the given screen position in a
* single batched buffer call. Does not recompute glyph layout.
*
* @param label The label to draw.
* @param x Screen x position.
* @param y Screen y position.
* @return Any error that occurs.
*/
errorret_t uiWidgetLabelDraw(
const uiwidgetlabel_t *label,
const float_t x,
const float_t y
);
+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
uitextbox.c
uitextboxmain.c
)
+276
View File
@@ -0,0 +1,276 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitextbox.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "time/time.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "ui/frame/uiframe.h"
void uiTextboxInit(
uitextbox_t *box,
char_t *text,
const uint32_t maxLength,
uitextboxline_t *lines,
const uint32_t linesMax
) {
assertNotNull(box, "Textbox cannot be NULL");
assertNotNull(text, "Text buffer cannot be NULL");
assertTrue(maxLength >= 1, "maxLength must be at least 1");
assertNotNull(lines, "Lines buffer cannot be NULL");
assertTrue(linesMax >= 1, "linesMax must be at least 1");
memoryZero(box, sizeof(uitextbox_t));
box->text = text;
box->maxLength = maxLength;
box->lines = lines;
box->linesMax = linesMax;
box->glyphsBuiltForPage = -1;
}
void uiTextboxSetText(uitextbox_t *box, const char_t *text) {
assertNotNull(box, "Textbox cannot be NULL");
assertNotNull(text, "Text cannot be NULL");
stringCopy(box->text, text, box->maxLength);
box->currentPage = 0;
box->scroll = 0;
box->layoutWidth = 0.0f;
box->layoutHeight = 0.0f;
box->glyphsBuiltForPage = -1;
}
void uiTextboxBuildLayout(
uitextbox_t *box,
const float_t width,
const float_t height
) {
assertNotNull(box, "Textbox cannot be NULL");
box->glyphsBuiltForPage = -1;
box->layoutWidth = width;
box->layoutHeight = height;
box->lineCount = 0;
box->pageCount = 1;
float_t fontW = (float_t)FONT_DEFAULT.tileset->tileWidth;
float_t fontH = (float_t)FONT_DEFAULT.tileset->tileHeight;
if(fontW <= 0.0f || fontH <= 0.0f) return;
box->charsPerLine = (int32_t)(width / fontW);
box->linesPerPage = (int32_t)(height / (fontH + UI_TEXTBOX_LINE_SPACING));
if(box->linesPerPage > UI_TEXTBOX_LINES_PER_PAGE_MAX) {
box->linesPerPage = UI_TEXTBOX_LINES_PER_PAGE_MAX;
}
if(box->charsPerLine <= 0 || box->linesPerPage <= 0) return;
if(box->text[0] == '\0') return;
char_t *src = box->text;
int32_t i = 0;
while(src[i] != '\0' && box->lineCount < (int32_t)box->linesMax) {
if(src[i] == '\t') {
i++;
int32_t rem = box->lineCount % box->linesPerPage;
int32_t pad = rem > 0 ? box->linesPerPage - rem : 0;
while(pad > 0 && box->lineCount < (int32_t)box->linesMax) {
box->lines[box->lineCount].start = i;
box->lines[box->lineCount].count = 0;
box->lineCount++;
pad--;
}
continue;
}
int32_t lineStart = i;
int32_t lineWidth = 0;
while(src[i] != '\0') {
char_t c = src[i];
if(c == '\n') { i++; break; }
if(c == '\t') break;
if(c == ' ') {
int32_t wordLen = 0;
int32_t j = i + 1;
while(
src[j] != ' ' && src[j] != '\n' &&
src[j] != '\t' && src[j] != '\0'
) {
wordLen++;
j++;
}
if(lineWidth > 0 && lineWidth + 1 + wordLen > box->charsPerLine) {
i++;
break;
}
lineWidth++;
i++;
} else {
if(lineWidth >= box->charsPerLine) break;
lineWidth++;
i++;
}
}
box->lines[box->lineCount].start = lineStart;
box->lines[box->lineCount].count = lineWidth;
box->lineCount++;
}
if(box->lineCount == 0) {
box->pageCount = 1;
} else {
box->pageCount =
(box->lineCount + box->linesPerPage - 1) / box->linesPerPage;
}
}
errorret_t uiTextboxUpdate(uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
#ifdef DUSK_TIME_DYNAMIC
if(TIME.dynamicUpdate) errorOk();
#endif
if(!uiTextboxPageIsComplete(box)) {
box->scroll += UI_TEXTBOX_SCROLL_CHARS_PER_TICK;
}
errorOk();
}
errorret_t uiTextboxDraw(
uitextbox_t *box,
const float_t x,
const float_t y,
const float_t width,
const float_t height
) {
assertNotNull(box, "Textbox cannot be NULL");
float_t startX = (float_t)UI_FRAME_START_X;
float_t startY = (float_t)UI_FRAME_START_Y;
float_t contentX = x + startX;
float_t contentY = y + startY;
float_t contentW = width - 2.0f * startX;
float_t contentH = height - 2.0f * startY;
if(contentW != box->layoutWidth || contentH != box->layoutHeight) {
uiTextboxBuildLayout(box, contentW, contentH);
}
errorChain(uiFrameDrawCached(&box->frameCache, x, y, width, height));
if(box->lineCount == 0 || box->text[0] == '\0') errorOk();
if(box->glyphsBuiltForPage != box->currentPage) {
uiTextboxBuildPageGlyphs(box);
}
if(box->glyphCount == 0) errorOk();
int32_t visibleCount = 0;
while(
visibleCount < box->glyphCount &&
box->glyphs[visibleCount].revealAt <= box->scroll
) visibleCount++;
if(visibleCount == 0) errorOk();
spritebatchsprite_t scratch[UI_TEXTBOX_PAGE_GLYPHS_MAX];
for(int32_t i = 0; i < visibleCount; i++) {
scratch[i] = spriteBatchSpriteTranslate(
&box->glyphs[i].sprite, contentX, contentY
);
}
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = FONT_DEFAULT.texture
}
};
errorChain(spriteBatchBuffer(scratch, visibleCount, &SHADER_UNLIT, material));
errorOk();
}
void uiTextboxBuildPageGlyphs(uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
box->glyphCount = 0;
int32_t pageFirst = box->currentPage * box->linesPerPage;
int32_t pageLast = pageFirst + box->linesPerPage;
if(pageLast > box->lineCount) pageLast = box->lineCount;
float_t fontW = (float_t)FONT_DEFAULT.tileset->tileWidth;
float_t fontH = (float_t)FONT_DEFAULT.tileset->tileHeight;
int32_t consumed = 0;
for(int32_t li = pageFirst; li < pageLast; li++) {
uitextboxline_t *line = &box->lines[li];
float_t lineY =
(float_t)(li - pageFirst) * (fontH + UI_TEXTBOX_LINE_SPACING);
for(int32_t ci = 0; ci < line->count; ci++) {
consumed++;
char_t c = box->text[line->start + ci];
if(c == ' ') continue;
assertTrue(
box->glyphCount < UI_TEXTBOX_PAGE_GLYPHS_MAX,
"Textbox page produces too many glyphs"
);
uitextboxglyph_t *glyph = &box->glyphs[box->glyphCount++];
glyph->sprite = textGetSprite(
(vec2){ (float_t)ci * fontW, lineY }, c, &FONT_DEFAULT
);
glyph->revealAt = consumed;
}
}
box->glyphsBuiltForPage = box->currentPage;
}
int32_t uiTextboxGetPageCharCount(const uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
int32_t first = box->currentPage * box->linesPerPage;
int32_t last = first + box->linesPerPage;
if(last > box->lineCount) last = box->lineCount;
int32_t total = 0;
for(int32_t i = first; i < last; i++) {
total += box->lines[i].count;
}
return total;
}
bool_t uiTextboxPageIsComplete(const uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
return box->scroll >= uiTextboxGetPageCharCount(box);
}
bool_t uiTextboxHasNextPage(const uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
return box->currentPage + 1 < box->pageCount;
}
void uiTextboxNextPage(uitextbox_t *box) {
assertNotNull(box, "Textbox cannot be NULL");
if(!uiTextboxHasNextPage(box)) return;
box->currentPage++;
box->scroll = 0;
}
+175
View File
@@ -0,0 +1,175 @@
/**
* 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 "ui/frame/uiframe.h"
#include "display/spritebatch/spritebatchsprite.h"
#define UI_TEXTBOX_LINES_PER_PAGE_MAX 4
#define UI_TEXTBOX_SCROLL_CHARS_PER_TICK 1
#define UI_TEXTBOX_LINE_SPACING 0.0f
// Fixed capacity for a page's cached glyph sprites (see uitextboxglyph_t).
// Sized generously above UI_TEXTBOX_LINES_PER_PAGE_MAX worth of glyphs at
// typical textbox widths; uiTextboxBuildPageGlyphs asserts if a page
// somehow produces more than this.
#define UI_TEXTBOX_PAGE_GLYPHS_MAX 512
typedef struct {
int32_t start;
int32_t count;
} uitextboxline_t;
// A single visible glyph's cached sprite (relative to the textbox's
// content origin, i.e. (0,0)) plus the scroll value at/after which it
// becomes visible -- lets uiTextboxDraw turn the typewriter scroll into
// a simple prefix-count instead of recomputing glyph geometry every
// frame.
typedef struct {
spritebatchsprite_t sprite;
int32_t revealAt;
} uitextboxglyph_t;
typedef struct {
char_t *text;
uint32_t maxLength;
uitextboxline_t *lines;
uint32_t linesMax;
int32_t lineCount;
int32_t charsPerLine;
int32_t linesPerPage;
int32_t pageCount;
// last dimensions used for layout; rebuild triggers when these change
float_t layoutWidth;
float_t layoutHeight;
int32_t currentPage;
int32_t scroll;
// Cached glyph sprites for the current page (see uitextboxglyph_t),
// rebuilt only when currentPage no longer matches
// glyphsBuiltForPage -- not every frame/scroll tick.
uitextboxglyph_t glyphs[UI_TEXTBOX_PAGE_GLYPHS_MAX];
int32_t glyphCount;
int32_t glyphsBuiltForPage;
uiframecache_t frameCache;
} uitextbox_t;
/**
* Initializes a textbox, zeroing all state and binding it to caller-owned
* text and line storage.
*
* @param box The textbox to initialize.
* @param text Caller-owned buffer the textbox copies its text into.
* @param maxLength Capacity of text, in characters.
* @param lines Caller-owned buffer the textbox lays lines out into.
* @param linesMax Capacity of lines, in entries.
*/
void uiTextboxInit(
uitextbox_t *box,
char_t *text,
const uint32_t maxLength,
uitextboxline_t *lines,
const uint32_t linesMax
);
/**
* Copies text into the textbox and marks layout as dirty.
* Resets currentPage and scroll to 0.
*
* @param box The textbox to update.
* @param text Null-terminated source string.
*/
void uiTextboxSetText(uitextbox_t *box, const char_t *text);
/**
* Rebuilds word-wrap and page layout for the given draw dimensions.
* Called automatically by uiTextboxDraw when width or height changes.
*
* @param box The textbox to rebuild.
* @param width Available content width in pixels.
* @param height Available content height in pixels.
*/
void uiTextboxBuildLayout(
uitextbox_t *box,
const float_t width,
const float_t height
);
/**
* Advances the typewriter scroll by UI_TEXTBOX_SCROLL_CHARS_PER_TICK.
* Skipped on dynamic ticks.
*
* @param box The textbox to update.
* @returns Any error that occurs.
*/
errorret_t uiTextboxUpdate(uitextbox_t *box);
/**
* Draws the textbox frame and visible text. Rebuilds layout automatically
* if width or height differs from the last draw call.
*
* @param box The textbox to draw.
* @param x Screen x position.
* @param y Screen y position.
* @param width Draw width in pixels.
* @param height Draw height in pixels.
* @returns Any error that occurs.
*/
errorret_t uiTextboxDraw(
uitextbox_t *box,
const float_t x,
const float_t y,
const float_t width,
const float_t height
);
/**
* Returns the total visible char count for the current page.
*
* @param box The textbox to query.
* @returns Total chars on the current page.
*/
int32_t uiTextboxGetPageCharCount(const uitextbox_t *box);
/**
* Returns true when scroll has fully revealed the current page.
*
* @param box The textbox to query.
* @returns True if the current page is fully visible.
*/
bool_t uiTextboxPageIsComplete(const uitextbox_t *box);
/**
* Returns true when there is at least one more page after the current one.
*
* @param box The textbox to query.
* @returns True if a next page exists.
*/
bool_t uiTextboxHasNextPage(const uitextbox_t *box);
/**
* Advances to the next page and resets scroll to 0.
* Has no effect if already on the last page.
*
* @param box The textbox to advance.
*/
void uiTextboxNextPage(uitextbox_t *box);
/**
* Rebuilds the cached glyph sprites (see uitextboxglyph_t) for the
* current page from its line layout. Called automatically by
* uiTextboxDraw whenever currentPage no longer matches the page the
* cache was last built for.
*
* @param box The textbox to rebuild.
*/
void uiTextboxBuildPageGlyphs(uitextbox_t *box);
+121
View File
@@ -0,0 +1,121 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitextboxmain.h"
#include "ui/focus/uifocus.h"
#include "display/screen/screen.h"
#include "display/text/text.h"
#include "display/color.h"
#include "display/spritebatch/spritebatch.h"
#include "display/shader/shaderunlit.h"
#include "ui/frame/uiframe.h"
uitextboxmain_t UI_TEXTBOX_MAIN;
static uifocusitem_t *focusItem = NULL;
errorret_t uiTextboxMainInit(void) {
uiTextboxInit(
&UI_TEXTBOX_MAIN.box,
UI_TEXTBOX_MAIN.text, UI_TEXTBOX_MAIN_TEXT_MAX,
UI_TEXTBOX_MAIN.lines, UI_TEXTBOX_MAIN_LINES_MAX
);
errorOk();
}
void uiTextboxMainSetText(const char_t *text) {
uiTextboxSetText(&UI_TEXTBOX_MAIN.box, text);
if(focusItem != NULL) return;
focusItem = uiFocusPush(
1, 1,
uiTextboxMainFocusSelected,
NULL,
uiTextboxMainFocusClosed,
NULL,
NULL
);
}
errorret_t uiTextboxMainUpdate(void) {
if(focusItem == NULL) errorOk();
return uiTextboxUpdate(&UI_TEXTBOX_MAIN.box);
}
errorret_t uiTextboxMainDraw(void) {
if(focusItem == NULL) errorOk();
float_t fontH = (float_t)FONT_DEFAULT.tileset->tileHeight;
float_t h = (float_t)UI_TEXTBOX_MAIN_LINES * fontH +
(float_t)(UI_TEXTBOX_MAIN_LINES - 1) * UI_TEXTBOX_LINE_SPACING +
2.0f * (float_t)UI_FRAME_START_Y;
float_t w = (float_t)SCREEN.scanWidth;
float_t x = (float_t)SCREEN.scanX;
float_t y = (float_t)(SCREEN.scanY + SCREEN.scanHeight) - h;
errorChain(uiTextboxDraw(&UI_TEXTBOX_MAIN.box, x, y, w, h));
if(!uiTextboxPageIsComplete(&UI_TEXTBOX_MAIN.box)) errorOk();
float_t fontW = (float_t)FONT_DEFAULT.tileset->tileWidth;
float_t contentX = x + (float_t)UI_FRAME_START_X;
float_t contentY = y + (float_t)UI_FRAME_START_Y;
float_t contentW = w - 2.0f * (float_t)UI_FRAME_START_X;
float_t contentH = h - 2.0f * (float_t)UI_FRAME_START_Y;
shadermaterial_t material = {
.unlit = {
.color = COLOR_WHITE,
.texture = FONT_DEFAULT.texture
}
};
spritebatchsprite_t caret = textGetSprite(
(vec2){
contentX + contentW - fontW,
contentY + contentH - fontH
},
'v',
&FONT_DEFAULT
);
errorChain(spriteBatchBuffer(&caret, 1, &SHADER_UNLIT, material));
errorOk();
}
bool_t uiTextboxMainPageIsComplete(void) {
return uiTextboxPageIsComplete(&UI_TEXTBOX_MAIN.box);
}
bool_t uiTextboxMainHasNextPage(void) {
return uiTextboxHasNextPage(&UI_TEXTBOX_MAIN.box);
}
void uiTextboxMainNextPage(void) {
uiTextboxNextPage(&UI_TEXTBOX_MAIN.box);
}
bool_t uiTextboxMainIsActive(void) {
return focusItem != NULL;
}
bool_t uiTextboxMainFocusSelected(const uifocusitem_t *item) {
if(!uiTextboxPageIsComplete(&UI_TEXTBOX_MAIN.box)) {
UI_TEXTBOX_MAIN.box.scroll =
uiTextboxGetPageCharCount(&UI_TEXTBOX_MAIN.box);
return true;
}
if(uiTextboxHasNextPage(&UI_TEXTBOX_MAIN.box)) {
uiTextboxNextPage(&UI_TEXTBOX_MAIN.box);
return true;
}
uiFocusPopItem(focusItem);
return true;
}
bool_t uiTextboxMainFocusClosed(const uifocusitem_t *item) {
focusItem = NULL;
return true;
}
@@ -0,0 +1,94 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "uitextbox.h"
#include "ui/focus/uifocusitem.h"
#define UI_TEXTBOX_MAIN_LINES 4
#define UI_TEXTBOX_MAIN_TEXT_MAX 1024
#define UI_TEXTBOX_MAIN_LINES_MAX 64
typedef struct {
uitextbox_t box;
char_t text[UI_TEXTBOX_MAIN_TEXT_MAX];
uitextboxline_t lines[UI_TEXTBOX_MAIN_LINES_MAX];
} uitextboxmain_t;
extern uitextboxmain_t UI_TEXTBOX_MAIN;
/**
* Initializes UI_TEXTBOX_MAIN.
*
* @returns Any error that occurs.
*/
errorret_t uiTextboxMainInit(void);
/**
* Copies text into UI_TEXTBOX_MAIN and resets page and scroll.
*
* @param text Null-terminated source string.
*/
void uiTextboxMainSetText(const char_t *text);
/**
* Advances the typewriter scroll for UI_TEXTBOX_MAIN.
*
* @returns Any error that occurs.
*/
errorret_t uiTextboxMainUpdate(void);
/**
* Draws UI_TEXTBOX_MAIN full-width at the bottom of the screen.
* Position and size are derived from SCREEN each call.
*
* @returns Any error that occurs.
*/
errorret_t uiTextboxMainDraw(void);
/**
* Returns true when the current page is fully scrolled in.
*
* @returns True if the current page is complete.
*/
bool_t uiTextboxMainPageIsComplete(void);
/**
* Returns true when at least one more page follows the current one.
*
* @returns True if a next page exists.
*/
bool_t uiTextboxMainHasNextPage(void);
/**
* Advances UI_TEXTBOX_MAIN to the next page and resets scroll.
* Has no effect if already on the last page.
*/
void uiTextboxMainNextPage(void);
/**
* Returns true when UI_TEXTBOX_MAIN has focus (is visible and active).
*
* @returns True if the textbox is currently active.
*/
bool_t uiTextboxMainIsActive(void);
/**
* Internal focus callback - skip scroll or advance page or dismiss.
*
* @param item The active focus item.
* @returns True.
*/
bool_t uiTextboxMainFocusSelected(const uifocusitem_t *item);
/**
* Internal focus callback - clears the focus item pointer on dismiss.
*
* @param item The focus item being closed.
* @returns True.
*/
bool_t uiTextboxMainFocusClosed(const uifocusitem_t *item);
+35
View File
@@ -0,0 +1,35 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "uitestlabel.h"
#include "ui/widget/uilabel.h"
#include "display/text/text.h"
#include "display/screen/screen.h"
#include "engine/engine.h"
uilabel_t UI_TEST_LABEL;
errorret_t uiTestLabelInit() {
uiLabelInit(&UI_TEST_LABEL, &FONT_DEFAULT);
uiLabelSetText(&UI_TEST_LABEL, "duskrpg");
errorOk();
}
errorret_t uiTestLabelDraw() {
int32_t versionWidth, versionHeight;
textMeasure(ENGINE.version, &FONT_DEFAULT, &versionWidth, &versionHeight);
errorChain(uiLabelDraw(
&UI_TEST_LABEL,
(float_t)(SCREEN.scanX + SCREEN.scanWidth - UI_TEST_LABEL.width),
(float_t)(
SCREEN.scanY + SCREEN.scanHeight - versionHeight -
UI_TEST_LABEL.height
)
));
errorOk();
}
+24
View File
@@ -0,0 +1,24 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
/**
* Initializes the test label, a smoke test for the duskrpg-side UI
* element extension point (uielementgame.h).
*
* @return Any error that occurs.
*/
errorret_t uiTestLabelInit();
/**
* Draws the test label above the engine's debug version number.
*
* @return Any error that occurs.
*/
errorret_t uiTestLabelDraw();
-57
View File
@@ -1,57 +0,0 @@
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import (
QApplication, QVBoxLayout, QPushButton,
QDialog
)
from OpenGL.GL import *
from OpenGL.GLU import *
from tools.editor.maptool import MapWindow
from tools.editor.langtool import LangToolWindow
from tools.editor.cutscenetool import CutsceneToolWindow
DEFAULT_TOOL = None
DEFAULT_TOOL = "map"
# DEFAULT_TOOL = "cutscene"
TOOLS = [
("Map Editor", "map", MapWindow),
("Language Editor", "language", LangToolWindow),
("Cutscene Editor", "cutscene", CutsceneToolWindow),
]
class EditorChoiceDialog(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle("Choose Tool")
layout = QVBoxLayout(self)
self.selected = None
for label, key, win_cls in TOOLS:
btn = QPushButton(label)
btn.clicked.connect(lambda checked, w=win_cls: self.choose_tool(w))
layout.addWidget(btn)
def choose_tool(self, win_cls):
self.selected = win_cls
self.accept()
def get_choice(self):
return self.selected
def main():
app = QApplication(sys.argv)
tool_map = { key: win_cls for _, key, win_cls in TOOLS }
if DEFAULT_TOOL in tool_map:
win_cls = tool_map[DEFAULT_TOOL]
else:
choice_dialog = EditorChoiceDialog()
if choice_dialog.exec_() == QDialog.Accepted:
win_cls = choice_dialog.get_choice()
else:
sys.exit(0)
win = win_cls()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

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