24 Commits

Author SHA1 Message Date
YourWishes 2ca6780305 Just trying to fix things now 2026-06-08 09:39:09 -05:00
YourWishes be68fe5a35 Emdashless 2026-06-07 21:27:59 -05:00
YourWishes dc41c0e302 Cleanup 2026-06-07 21:16:46 -05:00
YourWishes 51388c90d5 we ball I guess 2026-06-07 19:51:54 -05:00
YourWishes f8c9d33df2 Fix some script bugs 2026-06-07 18:47:34 -05:00
YourWishes ed0420fdce Cleanup of script modules. 2026-06-07 12:59:17 -05:00
YourWishes 47a6f396fa Fix typedefs 2026-06-06 19:06:52 -05:00
YourWishes 9edb2aa0c1 Example scene working 2026-06-06 18:46:08 -05:00
YourWishes 003b647d83 Fix tests 2026-06-06 17:36:13 -05:00
YourWishes 2849ff8844 Fix linux? 2026-06-06 17:14:42 -05:00
YourWishes 9f3089742a Fixed ISO builds. 2026-06-06 17:07:30 -05:00
YourWishes b286a9bbcd Fixed wii build 2026-06-06 16:53:06 -05:00
YourWishes 6204e745ba Fixed gamecube building. 2026-06-06 16:47:07 -05:00
YourWishes bbe0e48d23 Builds again? 2026-06-06 16:42:12 -05:00
YourWishes 79054080c0 Cleanup a bit. 2026-06-06 16:39:27 -05:00
YourWishes 81024c4c09 Require async 2026-06-06 10:55:10 -05:00
YourWishes 9068d96130 Add timeouts 2026-06-06 10:38:10 -05:00
YourWishes 6f47543720 Update jerryscript each frame. 2026-06-06 10:30:22 -05:00
YourWishes 5a08384ae1 start async 2026-06-05 19:42:24 -05:00
YourWishes 45d8fda0e4 require() working as I like 2026-06-05 18:49:10 -05:00
YourWishes a9e664492f First round of asset refactoring 2026-06-05 13:18:08 -05:00
YourWishes 3c8b6cb2cc Scene script code 2026-06-04 13:36:35 -05:00
YourWishes 2b3abbe13b ABout to try scene and script merger 2026-06-02 16:46:39 -05:00
YourWishes 241a52b94a nuke unused overworld code 2026-06-02 13:23:11 -05:00
266 changed files with 8858 additions and 4655 deletions
+432
View File
@@ -0,0 +1,432 @@
# 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`.
+6 -4
View File
@@ -1,5 +1,3 @@
Console.print('This is called from JavaScript');
const platformNames = { const platformNames = {
[System.PLATFORM_LINUX]: 'Linux', [System.PLATFORM_LINUX]: 'Linux',
[System.PLATFORM_KNULLI]: 'Knulli', [System.PLATFORM_KNULLI]: 'Knulli',
@@ -8,5 +6,9 @@ const platformNames = {
[System.PLATFORM_WII]: 'Wii', [System.PLATFORM_WII]: 'Wii',
}; };
const platformName = platformNames[System.platform] || 'Unknown'; Console.print('Platform: ' + (platformNames[System.platform] || 'Unknown'));
Console.print('Platform: ' + platformName);
requireAsync('testscene.js').then(Scene.set).catch(err => {
Console.print('Error loading scene: ' + err);
Engine.exit();
});
+63
View File
@@ -0,0 +1,63 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
const PLAYER_SPEED = 5.0;
// 1 world unit = 16 pixels.
const PIXEL_SCALE = 1.0 / 16.0;
// Player sprite is 32x32 px (test.png dimensions).
const PLAYER_W = 32 * PIXEL_SCALE;
const PLAYER_H = 32 * PIXEL_SCALE;
var player = {};
player.getAssets = () => {
return [
{ path: 'test.png', type: Asset.TYPE_TEXTURE, format: Texture.FORMAT_RGBA }
];
}
player.init = function(scene) {
var texture = scene.assets.getAssetByPath('test.png');
Console.print('Player init: got texture ' + texture);
_entity = Entity.create();
_position = _entity.add(Component.POSITION);
_physics = _entity.add(Component.PHYSICS);
_physics.bodyType = Physics.DYNAMIC;
_physics.shape = Physics.SHAPE_CUBE;
_physics.gravityScale = 1.0;
var r = _entity.add(Component.RENDERABLE);
r.texture = texture.texture;
r.type = Renderable.SPRITEBATCH;
r.color = new Color(220, 80, 80);
// Upright quad centered on X, bottom-aligned on Y.
r.sprites = [[-PLAYER_W/2, 0, 0, PLAYER_W/2, PLAYER_H, 0, 0, 1, 1, 0]];
_position.localPosition = new Vec3(0, PLAYER_H, 0);
};
player.getPosition = function() {
return _position;
};
player.update = function() {
if(!_physics) return;
var vx = Input.axis(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT) * PLAYER_SPEED;
var vz = Input.axis(INPUT_ACTION_DOWN, INPUT_ACTION_UP) * PLAYER_SPEED;
// Preserve vertical velocity so gravity and landing work correctly.
var vy = _physics.velocity.y;
_physics.velocity = new Vec3(vx, vy, vz);
};
player.dispose = function() {
Entity.dispose(_entity);
_entity = null;
_position = null;
_physics = null;
};
module.exports = player;
-24
View File
@@ -1,24 +0,0 @@
// Load rosa.
Console.print('Asset time');
const entry = Asset.lock('test.png', Asset.TYPE_TEXTURE, Texture.FORMAT_RGBA);
Asset.requireLoaded(entry);
Console.print('Asset loaded');
// Camera at (3,3,3) looking at origin
const cam = Entity.create();
const camPos = cam.add(Component.POSITION);
cam.add(Component.CAMERA);
camPos.localPosition = new Vec3(3, 3, 3);
camPos.lookAt(new Vec3(0, 0, 0));
// Test entity at origin
const testEntity = Entity.create();
const testPos = testEntity.add(Component.POSITION);
/** @type {RenderableSpritebatch} */
const testRenderable = testEntity.add(Component.RENDERABLE);
testRenderable.texture = entry.texture;
testRenderable.sprites = [
[0, 0, 1, 1, 0, 1, 1, 0]
];
testPos.localPosition = new Vec3(0, 0, 0);
+40
View File
@@ -0,0 +1,40 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var scene = {};
// Pokemon DS-style camera: ~34 degrees elevation (atan(6/9)).
// CAM_HEIGHT / CAM_DIST ratio controls the tilt - keep it under 0.7 for
// the characteristically shallow DS angle.
const CAM_HEIGHT = 6;
const CAM_DIST = 9;
scene.init = async function() {
// Camera
scene.cam = Entity.create();
var camPos = scene.cam.add(Component.POSITION);
var cam = scene.cam.add(Component.CAMERA);
camPos.localPosition = new Vec3(3, 3, 3);
camPos.lookAt(new Vec3(0, 0, 0));
// Floor - large flat slab, no texture needed.
scene.floor = Entity.create();
var floorPos = scene.floor.add(Component.POSITION);
var floorR = scene.floor.add(Component.RENDERABLE);
floorR.type = Renderable.SHADER_MATERIAL;
floorR.color = Color.BLUE;
// floorPos.localScale = new Vec3(16, 0.2, 16);
// floorPos.localPosition = new Vec3(0, -0.1, 0);
};
scene.update = function() {
};
scene.dispose = function() {
Entity.dispose(scene.floor);
Entity.dispose(scene.cam);
};
module.exports = scene;
+43
View File
@@ -0,0 +1,43 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# dusk_embed_js(TARGET JS_FILE [NAME identifier])
#
# Converts a JS file into a C string header in DUSK_GENERATED_HEADERS_DIR.
# The generated header defines:
# static const char <NAME>[] = "...";
# static const size_t <NAME>_SIZE = sizeof(<NAME>) - 1;
#
# NAME defaults to the uppercase stem + "_JS" (e.g. scene.js -> SCENE_JS).
function(dusk_embed_js TARGET JS_FILE)
cmake_parse_arguments(ARG "" "NAME" "" ${ARGN})
get_filename_component(JS_ABS "${JS_FILE}" ABSOLUTE)
get_filename_component(JS_STEM "${JS_FILE}" NAME_WE)
set(OUTPUT_HEADER "${DUSK_GENERATED_HEADERS_DIR}/${JS_STEM}_js.h")
set(NAME_ARG "")
if(ARG_NAME)
set(NAME_ARG "--name" "${ARG_NAME}")
endif()
add_custom_command(
OUTPUT "${OUTPUT_HEADER}"
COMMAND ${Python3_EXECUTABLE} -m tools.js2c
--input "${JS_ABS}"
--output "${OUTPUT_HEADER}"
${NAME_ARG}
WORKING_DIRECTORY "${DUSK_ROOT_DIR}"
DEPENDS "${JS_ABS}"
COMMENT "js2c: ${JS_STEM}.js -> ${JS_STEM}_js.h"
VERBATIM
)
file(RELATIVE_PATH JS_REL "${DUSK_ROOT_DIR}" "${JS_ABS}")
string(MAKE_C_IDENTIFIER "dusk_js2c_${JS_REL}" JS_TARGET)
add_custom_target(${JS_TARGET} DEPENDS "${OUTPUT_HEADER}")
add_dependencies(${TARGET} ${JS_TARGET})
endfunction()
+8 -5
View File
@@ -1,15 +1,18 @@
# Build type: FAT (SD/USB via libfat) or ISO (DVD disc via libogc DVD driver) # Build type: DOL (SD/USB via libfat) or ISO (DVD disc via libogc DVD driver)
set(DUSK_DOLPHIN_BUILD_TYPE "FAT" CACHE STRING "Dolphin asset source: FAT (SD/USB) or ISO (DVD disc)") set(DUSK_DOLPHIN_BUILD_TYPE "DOL" CACHE STRING "Dolphin asset source: DOL (SD/USB) or ISO (DVD disc)")
set_property(CACHE DUSK_DOLPHIN_BUILD_TYPE PROPERTY STRINGS "FAT" "ISO") set_property(CACHE DUSK_DOLPHIN_BUILD_TYPE PROPERTY STRINGS "DOL" "ISO")
# Target definitions # Numeric tokens so #if DUSK_DOLPHIN_BUILD_TYPE == DOL works in C.
# DUSK_DOLPHIN_BUILD_TYPE is passed without quotes so it expands to the identifier.
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_DOLPHIN DUSK_DOLPHIN
DUSK_INPUT_GAMEPAD DUSK_INPUT_GAMEPAD
DUSK_DISPLAY_WIDTH=640 DUSK_DISPLAY_WIDTH=640
DUSK_DISPLAY_HEIGHT=480 DUSK_DISPLAY_HEIGHT=480
DUSK_THREAD_PTHREAD DUSK_THREAD_PTHREAD
DUSK_DOLPHIN_BUILD_TYPE="${DUSK_DOLPHIN_BUILD_TYPE}" DOL=1
ISO=2
DUSK_DOLPHIN_BUILD_TYPE=${DUSK_DOLPHIN_BUILD_TYPE}
) )
# Custom compiler flags # Custom compiler flags
+1
View File
@@ -7,6 +7,7 @@ fi
mkdir -p build-gamecube mkdir -p build-gamecube
cmake -S. -Bbuild-gamecube \ cmake -S. -Bbuild-gamecube \
-DDUSK_TARGET_SYSTEM=gamecube \ -DDUSK_TARGET_SYSTEM=gamecube \
-DDUSK_DOLPHIN_BUILD_TYPE=DOL \
-DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/GameCube.cmake" \ -DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/GameCube.cmake" \
-DDKP_OGC_PLATFORM_LIBRARY=libogc2 -DDKP_OGC_PLATFORM_LIBRARY=libogc2
cd build-gamecube cd build-gamecube
+4 -1
View File
@@ -5,7 +5,10 @@ if [ -z "$DEVKITPRO" ]; then
fi fi
mkdir -p build-wii mkdir -p build-wii
cmake -S. -Bbuild-wii -DDUSK_TARGET_SYSTEM=wii -DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/Wii.cmake" cmake -S. -Bbuild-wii \
-DDUSK_TARGET_SYSTEM=wii \
-DCMAKE_TOOLCHAIN_FILE="$DEVKITPRO/cmake/Wii.cmake" \
-DDUSK_DOLPHIN_BUILD_TYPE=DOL
cd build-wii cd build-wii
make -j$(nproc) VERBOSE=1 make -j$(nproc) VERBOSE=1
mv Dusk.dol boot.dol mv Dusk.dol boot.dol
+4 -4
View File
@@ -5,7 +5,7 @@
#include "easing.h" #include "easing.h"
#include "assert/assert.h" #include "assert/assert.h"
#include <math.h> #include "util/math.h"
const easingfn_t EASING_FUNCTIONS[EASING_COUNT] = { const easingfn_t EASING_FUNCTIONS[EASING_COUNT] = {
easingLinear, easingLinear,
@@ -36,15 +36,15 @@ float_t easingLinear(const float_t t) {
} }
float_t easingInSine(const float_t t) { float_t easingInSine(const float_t t) {
return 1.0f - cosf(t * EASING_PI * 0.5f); return 1.0f - cosf(t * MATH_PI * 0.5f);
} }
float_t easingOutSine(const float_t t) { float_t easingOutSine(const float_t t) {
return sinf(t * EASING_PI * 0.5f); return sinf(t * MATH_PI * 0.5f);
} }
float_t easingInOutSine(const float_t t) { float_t easingInOutSine(const float_t t) {
return -(cosf(EASING_PI * t) - 1.0f) * 0.5f; return -(cosf(MATH_PI * t) - 1.0f) * 0.5f;
} }
float_t easingInQuad(const float_t t) { float_t easingInQuad(const float_t t) {
+36 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2023 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -10,7 +10,17 @@
#include "util/string.h" #include "util/string.h"
#include "util/memory.h" #include "util/memory.h"
#ifdef DUSK_THREAD_PTHREAD
pthread_t ASSERT_MAIN_THREAD_ID = 0;
#endif
#ifndef DUSK_ASSERTIONS_FAKED #ifndef DUSK_ASSERTIONS_FAKED
void assertInit(void) {
#ifdef DUSK_THREAD_PTHREAD
ASSERT_MAIN_THREAD_ID = pthread_self();
#endif
}
#ifdef DUSK_TEST_ASSERT #ifdef DUSK_TEST_ASSERT
void assertTrueImpl( void assertTrueImpl(
const char *file, const char *file,
@@ -132,4 +142,29 @@
) { ) {
assertTrueImpl(file, line, stringCompare(a, b) == 0, message); assertTrueImpl(file, line, stringCompare(a, b) == 0, message);
} }
void assertIsMainThreadImpl(
const char *file,
const int32_t line,
const char *message
) {
#ifdef DUSK_THREAD_PTHREAD
assertTrueImpl(
file, line, pthread_self() == ASSERT_MAIN_THREAD_ID, message
);
#endif
}
void assertNotMainThreadImpl(
const char *file,
const int32_t line,
const char *message
) {
#ifdef DUSK_THREAD_PTHREAD
assertTrueImpl(
file, line, pthread_self() != ASSERT_MAIN_THREAD_ID, message
);
#endif
}
#endif #endif
+57 -2
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2023 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -16,7 +16,18 @@
#endif #endif
#endif #endif
#ifdef DUSK_THREAD_PTHREAD
#include "thread/thread.h"
extern pthread_t ASSERT_MAIN_THREAD_ID;
#endif
#ifndef DUSK_ASSERTIONS_FAKED #ifndef DUSK_ASSERTIONS_FAKED
/**
* Initializes the assert system. Must be the very first call in engine
* startup.
*/
void assertInit(void);
/** /**
* Assert a given value to be true. * Assert a given value to be true.
* *
@@ -121,6 +132,28 @@
const char *message const char *message
); );
/**
* Asserts that the current thread is the main thread.
*
* @param message Message to throw against assertion failure.
*/
void assertIsMainThreadImpl(
const char *file,
const int32_t line,
const char *message
);
/**
* Asserts that the current thread is NOT the main thread.
*
* @param message Message to throw against assertion failure.
*/
void assertNotMainThreadImpl(
const char *file,
const int32_t line,
const char *message
);
/** /**
* Asserts a given value to be true. * Asserts a given value to be true.
* *
@@ -205,8 +238,28 @@
#define assertStringEqual(a, b, message) \ #define assertStringEqual(a, b, message) \
assertStringEqualImpl(__FILE__, __LINE__, a, b, message) assertStringEqualImpl(__FILE__, __LINE__, a, b, message)
/**
* Asserts that the current thread is the main thread.
*
* @param message Message to throw against assertion failure.
*/
#define assertIsMainThread(message) \
assertIsMainThreadImpl(__FILE__, __LINE__, message)
/**
* Asserts that the current thread is NOT the main thread.
*
* @param message Message to throw against assertion failure.
*/
#define assertNotMainThread(message) \
assertNotMainThreadImpl(__FILE__, __LINE__, message)
#else #else
// If assertions are faked, we define the macros to do nothing. // If assertions are faked, we define the macros to do nothing.
#define assertInit() ((void)0)
#define assertMainThreadInit() ((void)0)
#define assertIsMainThread(message) ((void)0)
#define assertNotMainThread(message) ((void)0)
#define assertTrue(x, message) ((void)0) #define assertTrue(x, message) ((void)0)
#define assertFalse(x, message) ((void)0) #define assertFalse(x, message) ((void)0)
#define assertUnreachable(message) ((void)0) #define assertUnreachable(message) ((void)0)
@@ -215,11 +268,13 @@
#define assertDeprecated(message) ((void)0) #define assertDeprecated(message) ((void)0)
#define assertStrLenMax(str, len, message) ((void)0) #define assertStrLenMax(str, len, message) ((void)0)
#define assertStrLenMin(str, len, message) ((void)0) #define assertStrLenMin(str, len, message) ((void)0)
#define assertStringEqual(a, b, message) ((void)0)
#define assertIsMainThread(message) ((void)0)
#define assertNotMainThread(message) ((void)0)
#endif #endif
// Static Assertions // Static Assertions
#define assertStructSize(struct, size) \ #define assertStructSize(struct, size) \
_Static_assert(sizeof(struct) == size, "Size of " #struct " must be " #size) _Static_assert(sizeof(struct) == size, "Size of " #struct " must be " #size)
+99 -12
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -78,9 +78,28 @@ assetentry_t * assetGetEntry(
return NULL; return NULL;
} }
uint32_t assetGetEntriesOfType(
assetentry_t **outEntries,
const assetloadertype_t type
) {
assertNotNull(outEntries, "Output entries cannot be NULL.");
uint32_t count = 0;
assetentry_t *entry = ASSET.entries;
do {
if(entry->type == type) {
outEntries[count++] = entry;
}
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
return count;
}
errorret_t assetRequireLoaded(assetentry_t *entry) { errorret_t assetRequireLoaded(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL."); assertNotNull(entry, "Entry cannot be NULL.");
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type."); assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
assertIsMainThread("Currently only works on main thread.");
if(entry->state == ASSET_ENTRY_STATE_LOADED) { if(entry->state == ASSET_ENTRY_STATE_LOADED) {
errorOk(); errorOk();
@@ -102,6 +121,43 @@ errorret_t assetRequireLoaded(assetentry_t *entry) {
errorOk(); errorOk();
} }
errorret_t assetRequireDisposed(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL.");
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
assertIsMainThread("Currently only works on main thread.");
if(entry->type == ASSET_LOADER_TYPE_NULL) {
errorOk();
}
if(
entry->state == ASSET_ENTRY_STATE_NOT_STARTED ||
entry->state == ASSET_ENTRY_STATE_ERROR
) {
errorOk();
}
assertTrue(
entry->refs.count == 0,
"Cannot require disposal of an entry with active references."
);
// Lock to prevent the reaper from collecting the entry mid-spin.
assetEntryLock(entry);
while(entry->type != ASSET_LOADER_TYPE_NULL) {
usleep(1000);
errorret_t ret = assetUpdate();
if(errorIsNotOk(ret)) {
assetEntryUnlock(entry);
errorChain(ret);
}
}
assetEntryUnlock(entry);
errorOk();
}
assetentry_t * assetLock( assetentry_t * assetLock(
const char_t *name, const char_t *name,
const assetloadertype_t type, const assetloadertype_t type,
@@ -114,14 +170,19 @@ assetentry_t * assetLock(
void assetUnlock(const char_t *name) { void assetUnlock(const char_t *name) {
assertNotNull(name, "Name cannot be NULL."); assertNotNull(name, "Name cannot be NULL.");
assetentry_t *entry = ASSET.entries; assetentry_t *entry = ASSET.entries;
do { do {
if(entry->type != ASSET_LOADER_TYPE_NULL && stringEquals(entry->name, name)) { if(
entry->type != ASSET_LOADER_TYPE_NULL &&
stringEquals(entry->name, name)
) {
assetEntryUnlock(entry); assetEntryUnlock(entry);
return; return;
} }
entry++; entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX); } while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
assertUnreachable("Asset entry not found for unlock."); assertUnreachable("Asset entry not found for unlock.");
} }
@@ -131,6 +192,8 @@ void assetUnlockEntry(assetentry_t *entry) {
} }
errorret_t assetUpdate(void) { errorret_t assetUpdate(void) {
assertIsMainThread("assetUpdate must be called from the main thread.");
// Determine how many available loading slots we have. // Determine how many available loading slots we have.
assetloading_t *availableLoading[ASSET_LOADING_COUNT_MAX]; assetloading_t *availableLoading[ASSET_LOADING_COUNT_MAX];
uint8_t availableLoadingCount = 0; uint8_t availableLoadingCount = 0;
@@ -222,6 +285,8 @@ errorret_t assetUpdate(void) {
loading->entry->state == ASSET_ENTRY_STATE_ERROR, loading->entry->state == ASSET_ENTRY_STATE_ERROR,
"Loader did not set entry state to error on failed load." "Loader did not set entry state to error on failed load."
); );
} else if(loading->entry->state == ASSET_ENTRY_STATE_LOADED) {
eventInvoke(&loading->entry->onLoaded, loading->entry);
} }
loading++; loading++;
@@ -241,10 +306,14 @@ errorret_t assetUpdate(void) {
loading++; loading++;
break; break;
case ASSET_ENTRY_STATE_ERROR: case ASSET_ENTRY_STATE_ERROR: {
assetentry_t *errEntry = loading->entry;
loading->entry = NULL;
threadMutexUnlock(&loading->mutex); threadMutexUnlock(&loading->mutex);
eventInvoke(&errEntry->onError, errEntry);
errorThrow("Failed to load asset asynchronously."); errorThrow("Failed to load asset asynchronously.");
break; break;
}
default: default:
threadMutexUnlock(&loading->mutex); threadMutexUnlock(&loading->mutex);
@@ -254,9 +323,7 @@ errorret_t assetUpdate(void) {
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX); } while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
// Reap entries that have no external locks (refs.count == 0) AND have been // Reap unused entries.
// explicitly locked at least once. Entries that were never locked are left
// alone — raw-pointer callers hold no ref but should not lose the entry.
entry = ASSET.entries; entry = ASSET.entries;
do { do {
if(entry->state != ASSET_ENTRY_STATE_LOADED) { if(entry->state != ASSET_ENTRY_STATE_LOADED) {
@@ -269,11 +336,6 @@ errorret_t assetUpdate(void) {
continue; continue;
} }
if(!entry->wasLocked) {
entry++;
continue;
}
if(entry->refs.count > 0) { if(entry->refs.count > 0) {
entry++; entry++;
continue; continue;
@@ -288,6 +350,8 @@ errorret_t assetUpdate(void) {
} }
void assetUpdateAsync(thread_t *thread) { void assetUpdateAsync(thread_t *thread) {
assertNotMainThread("assetUpdateAsync must not run on the main thread.");
while(!threadShouldStop(thread)) { while(!threadShouldStop(thread)) {
// Walk over each asset // Walk over each asset
assetloading_t *loading; assetloading_t *loading;
@@ -344,12 +408,35 @@ void assetUpdateAsync(thread_t *thread) {
} }
errorret_t assetDispose(void) { errorret_t assetDispose(void) {
assertIsMainThread("Must be called from the main thread.");
threadStop(&ASSET.loadThread); threadStop(&ASSET.loadThread);
// Free any script read-buffers left behind by an in-flight async load
// that was interrupted before the sync eval phase ran.
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) { for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
threadMutexDispose(&ASSET.loading[i].mutex); assetloading_t *loading = &ASSET.loading[i];
if(
loading->entry != NULL &&
loading->type == ASSET_LOADER_TYPE_SCRIPT &&
loading->loading.script.buffer != NULL
) {
memoryFree(loading->loading.script.buffer);
loading->loading.script.buffer = NULL;
}
threadMutexDispose(&loading->mutex);
} }
// Dispose every non-null entry so type-specific dispose callbacks
// (e.g. assetScriptDispose freeing jerry values) run before the
// scripting engine is torn down.
assetentry_t *entry = ASSET.entries;
do {
if(entry->type != ASSET_LOADER_TYPE_NULL) {
errorChain(assetEntryDispose(entry));
}
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
// Cleanup zip file. // Cleanup zip file.
if(ASSET.zip != NULL) { if(ASSET.zip != NULL) {
if(zip_close(ASSET.zip) != 0) { if(zip_close(ASSET.zip) != 0) {
+23 -2
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -56,7 +56,7 @@ errorret_t assetInit(void);
bool_t assetFileExists(const char_t *filename); bool_t assetFileExists(const char_t *filename);
/** /**
* Gets, or creates, a new asset entry. Internal prefer assetLock. * Gets, or creates, a new asset entry. Internal - prefer assetLock.
* *
* @param name Filename of the asset. * @param name Filename of the asset.
* @param type Type of the asset. * @param type Type of the asset.
@@ -68,6 +68,18 @@ assetentry_t * assetGetEntry(
assetloaderinput_t *input assetloaderinput_t *input
); );
/**
* Gets all asset entries of a given type.
*
* @param outEntries Output array to write the entries to.
* @param type Type of the asset entries to get.
* @return The number of entries written to outEntries.
*/
uint32_t assetGetEntriesOfType(
assetentry_t **outEntries,
const assetloadertype_t type
);
/** /**
* Gets, creates, and locks an asset entry. The asset will begin loading on * Gets, creates, and locks an asset entry. The asset will begin loading on
* the next assetUpdate. Call assetUnlock when done to allow the entry to be * the next assetUpdate. Call assetUnlock when done to allow the entry to be
@@ -109,6 +121,15 @@ void assetUnlockEntry(assetentry_t *entry);
*/ */
errorret_t assetRequireLoaded(assetentry_t *entry); errorret_t assetRequireLoaded(assetentry_t *entry);
/**
* Requires an asset entry to be disposed. This will block until the asset entry
* is fully disposed.
*
* @param entry The asset entry to require disposal of.
* @return An error code if the asset entry could not be disposed properly.
*/
errorret_t assetRequireDisposed(assetentry_t *entry);
/** /**
* Updates the asset system. * Updates the asset system.
* *
+75 -4
View File
@@ -19,15 +19,53 @@ void assetBatchInit(
assertNotNull(batch, "Batch cannot be NULL."); assertNotNull(batch, "Batch cannot be NULL.");
assertNotNull(descs, "Descs cannot be NULL."); assertNotNull(descs, "Descs cannot be NULL.");
assertTrue(count > 0, "Count must be greater than 0."); assertTrue(count > 0, "Count must be greater than 0.");
assertTrue(count <= ASSET_BATCH_COUNT_MAX, "Count exceeds ASSET_BATCH_COUNT_MAX."); assertTrue(
count <= ASSET_BATCH_COUNT_MAX, "Count exceeds ASSET_BATCH_COUNT_MAX."
);
memoryZero(batch, sizeof(assetbatch_t)); memoryZero(batch, sizeof(assetbatch_t));
batch->count = count; batch->count = count;
eventInit(
&batch->onLoaded,
batch->onLoadedCallbacks, batch->onLoadedUsers, ASSET_BATCH_EVENT_MAX
);
eventInit(
&batch->onEntryLoaded,
batch->onEntryLoadedCallbacks,
batch->onEntryLoadedUsers,
ASSET_BATCH_EVENT_MAX
);
eventInit(
&batch->onError,
batch->onErrorCallbacks, batch->onErrorUsers, ASSET_BATCH_EVENT_MAX
);
eventInit(
&batch->onEntryError,
batch->onEntryErrorCallbacks,
batch->onEntryErrorUsers,
ASSET_BATCH_EVENT_MAX
);
for(uint16_t i = 0; i < count; i++) { for(uint16_t i = 0; i < count; i++) {
// Copy input into batch-owned storage so the descriptor need not persist.
batch->inputs[i] = descs[i].input; batch->inputs[i] = descs[i].input;
batch->entries[i] = assetLock(descs[i].path, descs[i].type, &batch->inputs[i]); batch->entries[i] = assetLock(
descs[i].path, descs[i].type, &batch->inputs[i]
);
if(batch->entries[i]->state == ASSET_ENTRY_STATE_LOADED) {
// Already loaded (cached) - count it now, no subscription needed.
batch->loadedCount++;
} else if(batch->entries[i]->state == ASSET_ENTRY_STATE_ERROR) {
batch->errorCount++;
} else {
eventSubscribe(
&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb, batch
);
eventSubscribe(
&batch->entries[i]->onError, assetBatchEntryOnErrorCb, batch
);
}
} }
} }
@@ -88,7 +126,40 @@ errorret_t assetBatchRequireLoaded(assetbatch_t *batch) {
void assetBatchDispose(assetbatch_t *batch) { void assetBatchDispose(assetbatch_t *batch) {
assertNotNull(batch, "Batch cannot be NULL."); assertNotNull(batch, "Batch cannot be NULL.");
for(uint16_t i = 0; i < batch->count; i++) { for(uint16_t i = 0; i < batch->count; i++) {
assetUnlockEntry(batch->entries[i]); if(batch->entries[i]) {
// Unsubscribe while we still hold a lock so the entry is live.
eventUnsubscribe(&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb);
eventUnsubscribe(&batch->entries[i]->onError, assetBatchEntryOnErrorCb);
assetUnlockEntry(batch->entries[i]);
}
} }
memoryZero(batch, sizeof(assetbatch_t)); memoryZero(batch, sizeof(assetbatch_t));
} }
void assetBatchEntryOnLoadedCb(void *params, void *user) {
assetentry_t *entry = (assetentry_t *)params;
assetbatch_t *batch = (assetbatch_t *)user;
batch->loadedCount++;
eventInvoke(&batch->onEntryLoaded, entry);
if((uint16_t)(batch->loadedCount + batch->errorCount) >= batch->count) {
if(batch->errorCount == 0) {
eventInvoke(&batch->onLoaded, batch);
} else {
eventInvoke(&batch->onError, batch);
}
}
}
void assetBatchEntryOnErrorCb(void *params, void *user) {
assetentry_t *entry = (assetentry_t *)params;
assetbatch_t *batch = (assetbatch_t *)user;
batch->errorCount++;
eventInvoke(&batch->onEntryError, entry);
if((uint16_t)(batch->loadedCount + batch->errorCount) >= batch->count) {
eventInvoke(&batch->onError, batch);
}
}
+43 -1
View File
@@ -8,8 +8,10 @@
#pragma once #pragma once
#include "asset/loader/assetentry.h" #include "asset/loader/assetentry.h"
#include "asset/loader/assetloader.h" #include "asset/loader/assetloader.h"
#include "event/event.h"
#define ASSET_BATCH_COUNT_MAX 64 #define ASSET_BATCH_COUNT_MAX 64
#define ASSET_BATCH_EVENT_MAX 4
typedef struct { typedef struct {
const char_t *path; const char_t *path;
@@ -21,6 +23,28 @@ typedef struct {
assetentry_t *entries[ASSET_BATCH_COUNT_MAX]; assetentry_t *entries[ASSET_BATCH_COUNT_MAX];
assetloaderinput_t inputs[ASSET_BATCH_COUNT_MAX]; assetloaderinput_t inputs[ASSET_BATCH_COUNT_MAX];
uint16_t count; uint16_t count;
uint16_t loadedCount;
uint16_t errorCount;
/** Fires once when every entry loaded. params = assetbatch_t * */
event_t onLoaded;
eventcallback_t onLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
void *onLoadedUsers[ASSET_BATCH_EVENT_MAX];
/** Fires each time a single entry loads. params = assetentry_t * */
event_t onEntryLoaded;
eventcallback_t onEntryLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
void *onEntryLoadedUsers[ASSET_BATCH_EVENT_MAX];
/** Fires when all entries finish (any with errors). params: assetbatch_t * */
event_t onError;
eventcallback_t onErrorCallbacks[ASSET_BATCH_EVENT_MAX];
void *onErrorUsers[ASSET_BATCH_EVENT_MAX];
/** Fires each time a single entry errors. params = assetentry_t * */
event_t onEntryError;
eventcallback_t onEntryErrorCallbacks[ASSET_BATCH_EVENT_MAX];
void *onEntryErrorUsers[ASSET_BATCH_EVENT_MAX];
} assetbatch_t; } assetbatch_t;
/** /**
@@ -80,3 +104,21 @@ errorret_t assetBatchRequireLoaded(assetbatch_t *batch);
* @param batch Batch to dispose. * @param batch Batch to dispose.
*/ */
void assetBatchDispose(assetbatch_t *batch); void assetBatchDispose(assetbatch_t *batch);
/**
* Event trampoline invoked when a batch entry finishes loading.
* Increments the loaded counter and fires batch-level events.
*
* @param params The loaded assetentry_t pointer.
* @param user The owning assetbatch_t pointer.
*/
void assetBatchEntryOnLoadedCb(void *params, void *user);
/**
* Event trampoline invoked when a batch entry fails to load.
* Increments the error counter and fires batch-level events.
*
* @param params The errored assetentry_t pointer.
* @param user The owning assetbatch_t pointer.
*/
void assetBatchEntryOnErrorCb(void *params, void *user);
+45
View File
@@ -117,6 +117,51 @@ errorret_t assetFileDispose(assetfile_t *file) {
errorOk(); errorOk();
} }
errorret_t assetFileReadEntire(
assetfile_t *file,
uint8_t **outBuffer,
size_t *outSize
) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(outBuffer, "outBuffer cannot be NULL.");
assertNotNull(outSize, "outSize cannot be NULL.");
assertTrue(
file->size > 0,
"Asset file has no size; call assetFileInit first."
);
// File should be closed currently.
assertNull(file->zipFile, "Asset file must be closed before reading entire.");
// Open file
errorret_t ret = assetFileOpen(file);
if(errorIsNotOk(ret)) {
errorChain(ret);
}
// Set output.
size_t size = (size_t)file->size;
uint8_t *buffer = (uint8_t *)memoryAllocate(size);
// Read entire file.
ret = assetFileRead(file, buffer, size);
if(errorIsNotOk(ret)) {
memoryFree(buffer);
errorChain(ret);
}
// Close the file.
ret = assetFileClose(file);
if(errorIsNotOk(ret)) {
memoryFree(buffer);
errorChain(ret);
}
*outBuffer = buffer;
*outSize = size;
errorOk();
}
// Line Reader; // Line Reader;
void assetFileLineReaderInit( void assetFileLineReaderInit(
assetfilelinereader_t *reader, assetfilelinereader_t *reader,
+15
View File
@@ -92,6 +92,21 @@ errorret_t assetFileClose(assetfile_t *file);
*/ */
errorret_t assetFileDispose(assetfile_t *file); errorret_t assetFileDispose(assetfile_t *file);
/**
* Reads the entire contents of the asset file into a newly allocated buffer.
* The caller is responsible for freeing the buffer with memoryFree.
*
* @param file The asset file to read. Must be initialized but not open.
* @param outBuffer Receives a pointer to the allocated buffer.
* @param outSize Receives the number of bytes written to the buffer.
* @return An error code if the file could not be read.
*/
errorret_t assetFileReadEntire(
assetfile_t *file,
uint8_t **outBuffer,
size_t *outSize
);
typedef struct { typedef struct {
assetfile_t *file; assetfile_t *file;
uint8_t *readBuffer; uint8_t *readBuffer;
+29 -2
View File
@@ -21,6 +21,7 @@ void assetEntryInit(
assertStrLenMax(name, ASSET_FILE_NAME_MAX - 1, "Name too long"); assertStrLenMax(name, ASSET_FILE_NAME_MAX - 1, "Name too long");
assertTrue(type != ASSET_LOADER_TYPE_NULL, "Invalid loader type."); assertTrue(type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
assertTrue(type < ASSET_LOADER_TYPE_COUNT, "Invalid loader type."); assertTrue(type < ASSET_LOADER_TYPE_COUNT, "Invalid loader type.");
assertIsMainThread("Must be called from the main thread.");
memoryZero(entry, sizeof(assetentry_t)); memoryZero(entry, sizeof(assetentry_t));
stringCopy(entry->name, name, ASSET_FILE_NAME_MAX); stringCopy(entry->name, name, ASSET_FILE_NAME_MAX);
@@ -29,20 +30,40 @@ void assetEntryInit(
if(input) { if(input) {
entry->inputData = *input; entry->inputData = *input;
entry->input = &entry->inputData; entry->input = &entry->inputData;
} else {
memoryZero(&entry->inputData, sizeof(assetloaderinput_t));
entry->input = NULL;
} }
refInit(&entry->refs, entry, NULL, NULL, NULL); refInit(&entry->refs, entry, NULL, NULL, NULL);
eventInit(
&entry->onLoaded,
entry->onLoadedCallbacks, entry->onLoadedUsers,
ASSET_ENTRY_EVENT_MAX
);
eventInit(
&entry->onUnloaded,
entry->onUnloadedCallbacks, entry->onUnloadedUsers,
ASSET_ENTRY_EVENT_MAX
);
eventInit(
&entry->onError,
entry->onErrorCallbacks, entry->onErrorUsers,
ASSET_ENTRY_EVENT_MAX
);
} }
void assetEntryLock(assetentry_t *entry) { void assetEntryLock(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL"); assertNotNull(entry, "Entry cannot be NULL");
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type."); assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
entry->wasLocked = true;
refLock(&entry->refs); refLock(&entry->refs);
} }
void assetEntryUnlock(assetentry_t *entry) { void assetEntryUnlock(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL"); assertNotNull(entry, "Entry cannot be NULL");
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type."); assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
refUnlock(&entry->refs); refUnlock(&entry->refs);
} }
@@ -57,6 +78,7 @@ void assetEntryStartLoading(
entry->state == ASSET_ENTRY_STATE_NOT_STARTED, entry->state == ASSET_ENTRY_STATE_NOT_STARTED,
"Can only start loading from NOT_STARTED state." "Can only start loading from NOT_STARTED state."
); );
assertIsMainThread("Must be called from the main thread.");
entry->state = ASSET_ENTRY_STATE_PENDING_SYNC; entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
memoryZero(&loading->loading, sizeof(assetloaderloading_t)); memoryZero(&loading->loading, sizeof(assetloaderloading_t));
@@ -67,10 +89,15 @@ void assetEntryStartLoading(
errorret_t assetEntryDispose(assetentry_t *entry) { errorret_t assetEntryDispose(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL"); assertNotNull(entry, "Entry cannot be NULL");
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type."); assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
assertTrue(entry->type < ASSET_LOADER_TYPE_COUNT, "Invalid loader type."); assertTrue(entry->type < ASSET_LOADER_TYPE_COUNT, "Invalid loader type.");
assertIsMainThread("Must be called from the main thread.");
assertTrue(
entry->refs.count == 0,
"Asset entry still refed at dispose time."
);
eventInvoke(&entry->onUnloaded, entry);
errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry)); errorChain(ASSET_LOADER_CALLBACKS[entry->type].dispose(entry));
memoryZero(entry, sizeof(assetentry_t)); memoryZero(entry, sizeof(assetentry_t));
errorOk(); errorOk();
+34 -15
View File
@@ -7,6 +7,7 @@
#pragma once #pragma once
#include "asset/loader/assetloading.h" #include "asset/loader/assetloading.h"
#include "event/event.h"
#include "util/ref.h" #include "util/ref.h"
typedef enum { typedef enum {
@@ -19,27 +20,44 @@ typedef enum {
ASSET_ENTRY_STATE_ERROR ASSET_ENTRY_STATE_ERROR
} assetentrystate_t; } assetentrystate_t;
typedef struct assetentry_s { /** Maximum number of subscribers for each per-entry event. */
// Filename and cache key #define ASSET_ENTRY_EVENT_MAX 2
typedef struct assetentry_s assetentry_t;
struct assetentry_s {
char_t name[ASSET_FILE_NAME_MAX]; char_t name[ASSET_FILE_NAME_MAX];
// What type of asset is this?
assetloadertype_t type; assetloadertype_t type;
// Data
assetloaderoutput_t data; assetloaderoutput_t data;
// What state is this asset entry in currently?
assetentrystate_t state; assetentrystate_t state;
// What is referencing this asset entry.
ref_t refs; ref_t refs;
// True once assetEntryLock has been called at least once. The reaper only
// collects entries that have been explicitly locked (and later unlocked to
// zero). Entries that nobody has ever locked are left alone so raw-pointer
// callers (tests, requireLoaded before locking) are not surprised.
bool_t wasLocked;
// Owned copy of the loader input. input points here when non-NULL.
assetloaderinput_t inputData;
// Pointer to inputData, or NULL if no input was provided.
assetloaderinput_t *input; assetloaderinput_t *input;
} assetentry_t; assetloaderinput_t inputData;
/**
* Fired once when loading completes successfully (params = assetentry_t *).
* Always invoked on the main thread.
*/
event_t onLoaded;
eventcallback_t onLoadedCallbacks[ASSET_ENTRY_EVENT_MAX];
void *onLoadedUsers[ASSET_ENTRY_EVENT_MAX];
/**
* Fired once when the entry is disposed/reaped (params = assetentry_t *).
* The asset data is still accessible when the callback runs.
* Always invoked on the main thread.
*/
event_t onUnloaded;
eventcallback_t onUnloadedCallbacks[ASSET_ENTRY_EVENT_MAX];
void *onUnloadedUsers[ASSET_ENTRY_EVENT_MAX];
/**
* Fired once when loading fails (params = assetentry_t *).
* Always invoked on the main thread.
*/
event_t onError;
eventcallback_t onErrorCallbacks[ASSET_ENTRY_EVENT_MAX];
void *onErrorUsers[ASSET_ENTRY_EVENT_MAX];
};
/** /**
* Initializes an asset entry with the given name and type. This does not load * Initializes an asset entry with the given name and type. This does not load
@@ -86,6 +104,7 @@ void assetEntryStartLoading(assetentry_t *entry, assetloading_t *loading);
/** /**
* Disposes an asset entry, freeing any resources it holds. * Disposes an asset entry, freeing any resources it holds.
* Fires the onUnloaded event before releasing asset data.
* *
* @param entry The asset entry to dispose. * @param entry The asset entry to dispose.
* @return Any error that occurs during disposal. * @return Any error that occurs during disposal.
-4
View File
@@ -13,13 +13,9 @@
typedef struct assetentry_s assetentry_t; typedef struct assetentry_s assetentry_t;
typedef struct assetloading_s { typedef struct assetloading_s {
// Protects entry pointer and entry->state from concurrent access.
threadmutex_t mutex; threadmutex_t mutex;
// What type of asset is being loaded.
assetloadertype_t type; assetloadertype_t type;
// Referral back to the asset entry that will be kept alive after load done.
assetentry_t *entry; assetentry_t *entry;
// Information used during the load operation only.
assetloaderloading_t loading; assetloaderloading_t loading;
} assetloading_t; } assetloading_t;
@@ -21,9 +21,11 @@ errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
assetmeshoutput_t *out = &loading->entry->data.mesh; assetmeshoutput_t *out = &loading->entry->data.mesh;
assetfile_t *file = &loading->loading.mesh.file; assetfile_t *file = &loading->loading.mesh.file;
assetmeshinputaxis_t axis = loading->entry->input->mesh; assetmeshinputaxis_t axis = loading->entry->inputData.mesh;
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL)); assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
assetLoaderErrorChain(loading, assetFileOpen(file)); assetLoaderErrorChain(loading, assetFileOpen(file));
// Skip the 80-byte STL header. // Skip the 80-byte STL header.
@@ -33,7 +35,9 @@ errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
} }
uint32_t triangleCount; uint32_t triangleCount;
assetLoaderErrorChain(loading, assetFileRead(file, &triangleCount, sizeof(uint32_t))); assetLoaderErrorChain(loading,
assetFileRead(file, &triangleCount, sizeof(uint32_t))
);
if(file->lastRead != sizeof(uint32_t)) { if(file->lastRead != sizeof(uint32_t)) {
assetLoaderErrorThrow(loading, "Failed to read tri count"); assetLoaderErrorThrow(loading, "Failed to read tri count");
} }
@@ -75,7 +79,9 @@ errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
verts[i * 3 + j].uv[1] = 0.0f; verts[i * 3 + j].uv[1] = 0.0f;
for(uint8_t k = 0; k < 3; k++) { for(uint8_t k = 0; k < 3; k++) {
verts[i * 3 + j].pos[k] = endianLittleToHostFloat(triData.positions[j][k]); verts[i * 3 + j].pos[k] = endianLittleToHostFloat(
triData.positions[j][k]
);
} }
switch(axis) { switch(axis) {
@@ -54,6 +54,7 @@ int assetTextureEOF(void *user) {
errorret_t assetTextureLoaderAsync(assetloading_t *loading) { errorret_t assetTextureLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread.");
// Only care about loading pixels. // Only care about loading pixels.
if(loading->loading.texture.state != ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS){ if(loading->loading.texture.state != ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS){
@@ -76,7 +77,7 @@ errorret_t assetTextureLoaderAsync(assetloading_t *loading) {
// Determine channels // Determine channels
int channelsDesired; int channelsDesired;
switch(loading->entry->input->texture) { switch(loading->entry->inputData.texture) {
case TEXTURE_FORMAT_RGBA: case TEXTURE_FORMAT_RGBA:
channelsDesired = 4; channelsDesired = 4;
break; break;
@@ -102,7 +103,9 @@ errorret_t assetTextureLoaderAsync(assetloading_t *loading) {
// Ensure we loaded correctly. // Ensure we loaded correctly.
if(loading->loading.texture.data == NULL) { if(loading->loading.texture.data == NULL) {
const char_t *errorStr = stbi_failure_reason(); const char_t *errorStr = stbi_failure_reason();
assetLoaderErrorThrow(loading, "Failed to load texture from file %s.", errorStr); assetLoaderErrorThrow(
loading, "Failed to load texture from file %s.", errorStr
);
} }
// Fixes a specific bug probably with Dolphin but for now just assuming endian // Fixes a specific bug probably with Dolphin but for now just assuming endian
@@ -122,6 +125,7 @@ errorret_t assetTextureLoaderAsync(assetloading_t *loading) {
errorret_t assetTextureLoaderSync(assetloading_t *loading) { errorret_t assetTextureLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.texture.state) { switch(loading->loading.texture.state) {
case ASSET_TEXTURE_LOADING_STATE_INITIAL: case ASSET_TEXTURE_LOADING_STATE_INITIAL:
@@ -146,7 +150,7 @@ errorret_t assetTextureLoaderSync(assetloading_t *loading) {
(texture_t*)&loading->entry->data.texture, (texture_t*)&loading->entry->data.texture,
loading->loading.texture.width, loading->loading.texture.width,
loading->loading.texture.height, loading->loading.texture.height,
loading->entry->input->texture, loading->entry->inputData.texture,
(texturedata_t){ (texturedata_t){
.rgbaColors = (color_t*)loading->loading.texture.data .rgbaColors = (color_t*)loading->loading.texture.data
} }
@@ -161,5 +165,7 @@ errorret_t assetTextureLoaderSync(assetloading_t *loading) {
errorret_t assetTextureDispose(assetentry_t *entry) { errorret_t assetTextureDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL"); assertNotNull(entry, "Asset entry cannot be NULL");
assertIsMainThread("Must be called from the main thread.");
return textureDispose(&entry->data.texture); return textureDispose(&entry->data.texture);
} }
@@ -14,6 +14,7 @@
errorret_t assetTilesetLoaderAsync(assetloading_t *loading) { errorret_t assetTilesetLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread.");
if(loading->loading.tileset.state != ASSET_TILESET_LOADING_STATE_READ_FILE) { if(loading->loading.tileset.state != ASSET_TILESET_LOADING_STATE_READ_FILE) {
errorOk(); errorOk();
@@ -22,14 +23,19 @@ errorret_t assetTilesetLoaderAsync(assetloading_t *loading) {
assertNull(loading->loading.tileset.data, "Data already defined?"); assertNull(loading->loading.tileset.data, "Data already defined?");
assetfile_t *file = &loading->loading.tileset.file; assetfile_t *file = &loading->loading.tileset.file;
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL)); assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *data = memoryAllocate(file->size); uint8_t *data = memoryAllocate(file->size);
assetLoaderErrorChain(loading, assetFileOpen(file)); assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size)); assetLoaderErrorChain(loading, assetFileRead(file, data, file->size));
assetLoaderErrorChain(loading, assetFileClose(file)); assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file)); assetLoaderErrorChain(loading, assetFileDispose(file));
assertTrue(file->lastRead == file->size, "Failed to read entire tileset file."); assertTrue(
file->lastRead == file->size,
"Failed to read entire tileset file."
);
loading->loading.tileset.data = data; loading->loading.tileset.data = data;
loading->loading.tileset.state = ASSET_TILESET_LOADING_STATE_PARSE; loading->loading.tileset.state = ASSET_TILESET_LOADING_STATE_PARSE;
@@ -40,6 +46,7 @@ errorret_t assetTilesetLoaderAsync(assetloading_t *loading) {
errorret_t assetTilesetLoaderSync(assetloading_t *loading) { errorret_t assetTilesetLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_TILESET, "Invalid type."); assertTrue(loading->type == ASSET_LOADER_TYPE_TILESET, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.tileset.state) { switch(loading->loading.tileset.state) {
case ASSET_TILESET_LOADING_STATE_INITIAL: case ASSET_TILESET_LOADING_STATE_INITIAL:
@@ -111,5 +118,7 @@ errorret_t assetTilesetLoaderSync(assetloading_t *loading) {
errorret_t assetTilesetDispose(assetentry_t *entry) { errorret_t assetTilesetDispose(assetentry_t *entry) {
assertNotNull(entry, "Entry cannot be NULL"); assertNotNull(entry, "Entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_TILESET, "Invalid type."); assertTrue(entry->type == ASSET_LOADER_TYPE_TILESET, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
errorOk(); errorOk();
} }
+8 -1
View File
@@ -13,6 +13,7 @@
errorret_t assetJsonLoaderAsync(assetloading_t *loading) { errorret_t assetJsonLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(loading->loading.json.state != ASSET_JSON_LOADING_STATE_READ_FILE) { if(loading->loading.json.state != ASSET_JSON_LOADING_STATE_READ_FILE) {
errorOk(); errorOk();
@@ -21,7 +22,9 @@ errorret_t assetJsonLoaderAsync(assetloading_t *loading) {
assertNull(loading->loading.json.buffer, "Buffer already defined?"); assertNull(loading->loading.json.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.json.file; assetfile_t *file = &loading->loading.json.file;
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL)); assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
if(file->size > ASSET_JSON_FILE_SIZE_MAX) { if(file->size > ASSET_JSON_FILE_SIZE_MAX) {
assetLoaderErrorThrow(loading, "JSON exceeds maximum allowed size"); assetLoaderErrorThrow(loading, "JSON exceeds maximum allowed size");
@@ -45,6 +48,7 @@ errorret_t assetJsonLoaderAsync(assetloading_t *loading) {
errorret_t assetJsonLoaderSync(assetloading_t *loading) { errorret_t assetJsonLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_JSON, "Invalid type."); assertTrue(loading->type == ASSET_LOADER_TYPE_JSON, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.json.state) { switch(loading->loading.json.state) {
case ASSET_JSON_LOADING_STATE_INITIAL: case ASSET_JSON_LOADING_STATE_INITIAL:
@@ -82,7 +86,10 @@ errorret_t assetJsonLoaderSync(assetloading_t *loading) {
errorret_t assetJsonDispose(assetentry_t *entry) { errorret_t assetJsonDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL"); assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_JSON, "Invalid type."); assertTrue(entry->type == ASSET_LOADER_TYPE_JSON, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
yyjson_doc_free(entry->data.json); yyjson_doc_free(entry->data.json);
entry->data.json = NULL; entry->data.json = NULL;
errorOk(); errorOk();
} }
@@ -16,6 +16,7 @@
errorret_t assetLocaleLoaderAsync(assetloading_t *loading) { errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(loading->loading.locale.state != ASSET_LOCALE_LOADER_STATE_LOAD_HEADER) { if(loading->loading.locale.state != ASSET_LOCALE_LOADER_STATE_LOAD_HEADER) {
errorOk(); errorOk();
@@ -23,12 +24,18 @@ errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
assetlocalefile_t *localeFile = &loading->entry->data.locale; assetlocalefile_t *localeFile = &loading->entry->data.locale;
memoryZero(localeFile, sizeof(assetlocalefile_t)); memoryZero(localeFile, sizeof(assetlocalefile_t));
assetLoaderErrorChain(loading, assetFileInit(&localeFile->file, loading->entry->name, NULL, NULL)); assetLoaderErrorChain(loading, assetFileInit(
&localeFile->file, loading->entry->name, NULL, NULL
));
assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file)); assetLoaderErrorChain(loading, assetFileOpen(&localeFile->file));
char_t buffer[1024]; char_t buffer[1024];
assetLoaderErrorChain(loading, assetLocaleGetString(localeFile, "", 0, buffer, sizeof(buffer))); assetLoaderErrorChain(loading, assetLocaleGetString(
assetLoaderErrorChain(loading, assetLocaleParseHeader(localeFile, buffer, sizeof(buffer))); localeFile, "", 0, buffer, sizeof(buffer)
));
assetLoaderErrorChain(loading, assetLocaleParseHeader(
localeFile, buffer, sizeof(buffer)
));
loading->loading.locale.state = ASSET_LOCALE_LOADER_STATE_DONE; loading->loading.locale.state = ASSET_LOCALE_LOADER_STATE_DONE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC; loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
@@ -38,6 +45,7 @@ errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
errorret_t assetLocaleLoaderSync(assetloading_t *loading) { errorret_t assetLocaleLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type."); assertTrue(loading->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.locale.state) { switch(loading->loading.locale.state) {
case ASSET_LOCALE_LOADER_STATE_INITIAL: case ASSET_LOCALE_LOADER_STATE_INITIAL:
@@ -60,11 +68,14 @@ errorret_t assetLocaleLoaderSync(assetloading_t *loading) {
errorret_t assetLocaleDispose(assetentry_t *entry) { errorret_t assetLocaleDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL"); assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type."); assertTrue(entry->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
assetlocalefile_t *localeFile = &entry->data.locale; assetlocalefile_t *localeFile = &entry->data.locale;
errorChain(assetFileClose(&localeFile->file)); errorChain(assetFileClose(&localeFile->file));
return assetFileDispose(&localeFile->file); return assetFileDispose(&localeFile->file);
} }
// These functions probably need some cleaning;
errorret_t assetLocaleParseHeader( errorret_t assetLocaleParseHeader(
assetlocalefile_t *localeFile, assetlocalefile_t *localeFile,
char_t *headerBuffer, char_t *headerBuffer,
@@ -11,7 +11,7 @@
typedef struct assetloading_s assetloading_t; typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t; typedef struct assetentry_s assetentry_t;
/** Input passed to the locale loader currently unused. */ /** Input passed to the locale loader - currently unused. */
typedef struct { void *nothing; } assetlocaleloaderinput_t; typedef struct { void *nothing; } assetlocaleloaderinput_t;
typedef enum { typedef enum {
@@ -100,7 +100,7 @@ typedef struct {
uint8_t pluralDefaultIndex; uint8_t pluralDefaultIndex;
} assetlocalefile_t; } assetlocalefile_t;
/** Convenience alias the loaded output type of a locale asset entry. */ /** Convenience alias - the loaded output type of a locale asset entry. */
typedef assetlocalefile_t assetlocaleoutput_t; typedef assetlocalefile_t assetlocaleoutput_t;
/** /**
@@ -189,7 +189,7 @@ errorret_t assetLocaleLineSkipBlanks(
* *
* @param reader Line reader positioned at the line containing the opening * @param reader Line reader positioned at the line containing the opening
* quote (e.g. `msgstr "..."`). * quote (e.g. `msgstr "..."`).
* @param lineBuffer Buffer the reader fills on each @ref assetFileLineReaderNext * @param lineBuffer Buffer filled on each @ref assetFileLineReaderNext
* call; also used to detect continuation lines. * call; also used to detect continuation lines.
* @param stringBuffer Destination for the unescaped string content. * @param stringBuffer Destination for the unescaped string content.
* @param stringBufferSize Capacity of `stringBuffer` in bytes. * @param stringBufferSize Capacity of `stringBuffer` in bytes.
@@ -9,12 +9,14 @@
#include "asset/loader/assetloading.h" #include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h" #include "asset/loader/assetentry.h"
#include "asset/loader/assetloader.h" #include "asset/loader/assetloader.h"
#include "script/module/require/modulerequire.h"
#include "util/memory.h" #include "util/memory.h"
#include "assert/assert.h" #include "assert/assert.h"
#include <jerryscript.h> #include <jerryscript.h>
errorret_t assetScriptLoaderAsync(assetloading_t *loading) { errorret_t assetScriptLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(loading->loading.script.state != ASSET_SCRIPT_LOADING_STATE_READ_FILE) { if(loading->loading.script.state != ASSET_SCRIPT_LOADING_STATE_READ_FILE) {
errorOk(); errorOk();
@@ -23,33 +25,21 @@ errorret_t assetScriptLoaderAsync(assetloading_t *loading) {
assertNull(loading->loading.script.buffer, "Buffer already defined?"); assertNull(loading->loading.script.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.script.file; assetfile_t *file = &loading->loading.script.file;
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL)); assetLoaderErrorChain(
assetLoaderErrorChain(loading, assetFileOpen(file)); loading, assetFileInit(file, loading->entry->name, NULL, NULL)
);
size_t capacity = ASSET_SCRIPT_CHUNK_SIZE; uint8_t *buffer = NULL;
uint8_t *buffer = memoryAllocate(capacity + 1); size_t size = 0;
size_t offset = 0; assetLoaderErrorChain(loading, assetFileReadEntire(file, &buffer, &size));
while(1) {
if(offset + ASSET_SCRIPT_CHUNK_SIZE > capacity) {
size_t oldCapacity = capacity + 1;
capacity += ASSET_SCRIPT_CHUNK_SIZE;
memoryResize((void **)&buffer, oldCapacity, capacity + 1);
}
assetLoaderErrorChain(loading, assetFileRead(
file, buffer + offset, ASSET_SCRIPT_CHUNK_SIZE
));
size_t chunk = (size_t)file->lastRead;
offset += chunk;
if(chunk == 0) break;
}
buffer[offset] = '\0';
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file)); assetLoaderErrorChain(loading, assetFileDispose(file));
// Null-terminate for jerry_eval.
memoryResize((void **)&buffer, size, size + 1);
buffer[size] = '\0';
loading->loading.script.buffer = buffer; loading->loading.script.buffer = buffer;
loading->loading.script.size = offset; loading->loading.script.size = size;
loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_EXEC; loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_EXEC;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC; loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk(); errorOk();
@@ -58,6 +48,7 @@ errorret_t assetScriptLoaderAsync(assetloading_t *loading) {
errorret_t assetScriptLoaderSync(assetloading_t *loading) { errorret_t assetScriptLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type."); assertTrue(loading->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.script.state) { switch(loading->loading.script.state) {
case ASSET_SCRIPT_LOADING_STATE_INITIAL: case ASSET_SCRIPT_LOADING_STATE_INITIAL:
@@ -73,34 +64,58 @@ errorret_t assetScriptLoaderSync(assetloading_t *loading) {
errorOk(); errorOk();
} }
// Get read buffer
uint8_t *buffer = loading->loading.script.buffer; uint8_t *buffer = loading->loading.script.buffer;
assertNotNull(buffer, "Script buffer should have been loaded by now."); assertNotNull(buffer, "Script buffer should have been loaded by now.");
// Get the current global script realm
jerry_value_t global = jerry_current_realm();
// Replace globalThis.module with a new `module = {}`
jerry_value_t oldModule = jerry_object_get_sz(global, "module");
jerry_value_t module = jerry_object();
jerry_object_set_sz(global, "module", module);
// Eval the script, we handle failure later down the code.
jerry_value_t result = jerry_eval( jerry_value_t result = jerry_eval(
(const jerry_char_t *)buffer, buffer,
loading->loading.script.size, loading->loading.script.size,
JERRY_PARSE_NO_OPTS JERRY_PARSE_NO_OPTS
); );
// Free the read buffer
memoryFree(buffer); memoryFree(buffer);
loading->loading.script.buffer = NULL; loading->loading.script.buffer = NULL;
// Restore globalThis.module
jerry_object_set_sz(global, "module", oldModule);
jerry_value_free(oldModule);
jerry_value_free(global);
if(jerry_value_is_exception(result)) { if(jerry_value_is_exception(result)) {
jerry_value_t errVal = jerry_exception_value(result, false); jerry_value_free(module);
jerry_value_t errStr = jerry_value_to_string(errVal);
loading->entry->data.script.exports = jerry_undefined();
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
// Get error string
char_t buf[256]; char_t buf[256];
jerry_size_t len = jerry_string_to_buffer( moduleBaseExceptionMessage(result, buf, sizeof(buf));
errStr, JERRY_ENCODING_UTF8, (jerry_char_t *)buf, sizeof(buf) - 1
);
buf[len] = '\0';
jerry_value_free(errStr);
jerry_value_free(errVal);
jerry_value_free(result); jerry_value_free(result);
assetLoaderErrorThrow(loading, "Script error in '%s': %s", assetLoaderErrorThrow(
loading->entry->name, buf loading,
"Script execution failed: %s: %s", loading->entry->name, buf
); );
} }
loading->entry->data.script = (assetscriptoutput_t)result; // Get module.exports
jerry_value_t exports = jerry_object_get_sz(module, "exports");
jerry_value_free(result);
jerry_value_free(module);
// Store the exports.
loading->entry->data.script.exports = exports;
loading->entry->state = ASSET_ENTRY_STATE_LOADED; loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk(); errorOk();
} }
@@ -108,9 +123,15 @@ errorret_t assetScriptLoaderSync(assetloading_t *loading) {
errorret_t assetScriptDispose(assetentry_t *entry) { errorret_t assetScriptDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL"); assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type."); assertTrue(entry->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
if(entry->data.script != 0) { assertIsMainThread("Must be called from the main thread.");
jerry_value_free((jerry_value_t)entry->data.script);
entry->data.script = 0; if(
entry->data.script.exports != 0 &&
!jerry_value_is_undefined(entry->data.script.exports)
) {
jerry_value_free(entry->data.script.exports);
entry->data.script.exports = 0;
} }
errorOk(); errorOk();
} }
@@ -7,14 +7,18 @@
#pragma once #pragma once
#include "asset/assetfile.h" #include "asset/assetfile.h"
#include "script/scriptmodule.h"
#define ASSET_SCRIPT_CHUNK_SIZE 1024 #define ASSET_SCRIPT_CHUNK_SIZE 1024
typedef struct assetloading_s assetloading_t; typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t; typedef struct assetentry_s assetentry_t;
typedef struct { void *nothing; } assetscriptloaderinput_t; typedef struct {
typedef uint32_t assetscriptoutput_t; void *nothing;
} assetscriptloaderinput_t;
typedef scriptmodule_t assetscriptoutput_t;
typedef enum { typedef enum {
ASSET_SCRIPT_LOADING_STATE_INITIAL, ASSET_SCRIPT_LOADING_STATE_INITIAL,
@@ -30,6 +34,27 @@ typedef struct {
size_t size; size_t size;
} assetscriptloaderloading_t; } assetscriptloaderloading_t;
/**
* Asynchronous loader for a script asset/module.
*
* @param loading The loading context.
* @returns An error code and state.
*/
errorret_t assetScriptLoaderAsync(assetloading_t *loading); errorret_t assetScriptLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader for a script asset/module. This executes the script after
* it has been loaded by the async loader.
*
* @param loading The loading context.
* @returns An error code and state.
*/
errorret_t assetScriptLoaderSync(assetloading_t *loading); errorret_t assetScriptLoaderSync(assetloading_t *loading);
/**
* Disposes of a loaded script asset/module.
*
* @param entry The asset entry to dispose.
* @returns An error code and state.
*/
errorret_t assetScriptDispose(assetentry_t *entry); errorret_t assetScriptDispose(assetentry_t *entry);
+1
View File
@@ -20,6 +20,7 @@ console_t CONSOLE;
void consoleInit(void) { void consoleInit(void) {
memoryZero(&CONSOLE, sizeof(console_t)); memoryZero(&CONSOLE, sizeof(console_t));
CONSOLE.visible = true;
#ifdef DUSK_CONSOLE_POSIX #ifdef DUSK_CONSOLE_POSIX
threadMutexInit(&CONSOLE.printMutex); threadMutexInit(&CONSOLE.printMutex);
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2025 Dominic Masters // Copyright (c) 2026 Dominic Masters
// //
// This software is released under the MIT License. // This software is released under the MIT License.
// https://opensource.org/licenses/MIT // https://opensource.org/licenses/MIT
+1 -1
View File
@@ -74,7 +74,7 @@ void planeBuffer(
const float_t u0 = uvMin[0], u1 = uvMax[0]; const float_t u0 = uvMin[0], u1 = uvMax[0];
const float_t v0 = uvMin[1], v1 = uvMax[1]; const float_t v0 = uvMin[1], v1 = uvMax[1];
switch (axis) { switch(axis) {
case PLANE_AXIS_XY: { case PLANE_AXIS_XY: {
/* Flat in XY at z = min[2]; spans X and Y. */ /* Flat in XY at z = min[2]; spans X and Y. */
const float_t z = min[2]; const float_t z = min[2];
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+2 -2
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -47,7 +47,7 @@ errorret_t spriteBatchInit();
/** /**
* Lowest-level buffer function. Writes sprites into the internal vertex buffer. * Lowest-level buffer function. Writes sprites into the internal vertex buffer.
* Flushes automatically when the per-flush capacity is reached. Does not * Flushes automatically when the per-flush capacity is reached. Does not
* modify material state call spriteBatchSetState or use a high-level push * modify material state - call spriteBatchSetState or use a high-level push
* function before buffering. * function before buffering.
* *
* @param sprites Pointer to the sprite array. * @param sprites Pointer to the sprite array.
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+6 -6
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -30,6 +30,7 @@
engine_t ENGINE; engine_t ENGINE;
errorret_t engineInit(const int32_t argc, const char_t **argv) { errorret_t engineInit(const int32_t argc, const char_t **argv) {
assertInit();
memoryZero(&ENGINE, sizeof(engine_t)); memoryZero(&ENGINE, sizeof(engine_t));
ENGINE.running = true; ENGINE.running = true;
ENGINE.argc = argc; ENGINE.argc = argc;
@@ -48,17 +49,15 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorChain(uiInit()); errorChain(uiInit());
errorChain(uiTextboxInit()); errorChain(uiTextboxInit());
errorChain(cutsceneInit()); errorChain(cutsceneInit());
errorChain(sceneInit());
entityManagerInit(); entityManagerInit();
backpackInit(); backpackInit();
physicsManagerInit(); physicsManagerInit();
errorChain(networkInit()); errorChain(networkInit());
errorChain(scriptInit()); errorChain(scriptInit());
errorChain(sceneInit());
consolePrint("Engine initialized"); consolePrint("Engine initialized");
errorChain(scriptExecFile("init.js")); errorChain(scriptExecFile("init.js"));
sceneSet(SCENE_TYPE_INITIAL);
errorOk(); errorOk();
} }
@@ -77,6 +76,7 @@ errorret_t engineUpdate(void) {
errorChain(cutsceneUpdate()); errorChain(cutsceneUpdate());
errorChain(sceneUpdate()); errorChain(sceneUpdate());
errorChain(assetUpdate()); errorChain(assetUpdate());
errorChain(scriptUpdate());
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false; if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
errorOk(); errorOk();
@@ -89,7 +89,8 @@ void engineExit(void) {
errorret_t engineDispose(void) { errorret_t engineDispose(void) {
uiTextboxDispose(); uiTextboxDispose();
cutsceneDispose(); cutsceneDispose();
sceneDispose(); errorChain(sceneDispose());
errorChain(scriptDispose());
errorChain(networkDispose()); errorChain(networkDispose());
entityManagerDispose(); entityManagerDispose();
localeManagerDispose(); localeManagerDispose();
@@ -98,7 +99,6 @@ errorret_t engineDispose(void) {
errorChain(displayDispose()); errorChain(displayDispose());
// errorChain(saveDispose()); // errorChain(saveDispose());
errorChain(assetDispose()); errorChain(assetDispose());
errorChain(scriptDispose());
errorOk(); errorOk();
} }
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+3 -1
View File
@@ -119,7 +119,9 @@ errorret_t componentRenderAll(void) {
for(entityid_t eid = 0; eid < ENTITY_COUNT_MAX; eid++) { for(entityid_t eid = 0; eid < ENTITY_COUNT_MAX; eid++) {
if(!(ENTITY_MANAGER.entities[eid].state & ENTITY_STATE_ACTIVE)) continue; if(!(ENTITY_MANAGER.entities[eid].state & ENTITY_STATE_ACTIVE)) continue;
for(componentid_t cid = 0; cid < ENTITY_COMPONENT_COUNT_MAX; cid++) { for(componentid_t cid = 0; cid < ENTITY_COMPONENT_COUNT_MAX; cid++) {
component_t *cmp = &ENTITY_MANAGER.components[componentGetIndex(eid, cid)]; component_t *cmp = &ENTITY_MANAGER.components[
componentGetIndex(eid, cid)
];
if(cmp->type == COMPONENT_TYPE_NULL) continue; if(cmp->type == COMPONENT_TYPE_NULL) continue;
if(!COMPONENT_DEFINITIONS[cmp->type].render) continue; if(!COMPONENT_DEFINITIONS[cmp->type].render) continue;
errorChain(COMPONENT_DEFINITIONS[cmp->type].render(eid, cid)); errorChain(COMPONENT_DEFINITIONS[cmp->type].render(eid, cid));
-2
View File
@@ -4,7 +4,5 @@
# https://opensource.org/licenses/MIT # https://opensource.org/licenses/MIT
add_subdirectory(display) add_subdirectory(display)
add_subdirectory(overworld)
add_subdirectory(physics) add_subdirectory(physics)
add_subdirectory(script)
add_subdirectory(trigger) add_subdirectory(trigger)
@@ -22,12 +22,12 @@ static void entityPositionEnsureLocal(entityposition_t *pos) {
if(!dirty) return; if(!dirty) return;
if(dirty & ENTITY_POSITION_FLAG_ROTATION_DIRTY) { if(dirty & ENTITY_POSITION_FLAG_ROTATION_DIRTY) {
// Rotation or scale changed: rebuild columns 0-2 analytically (XYZ euler order). // Rotation or scale changed: rebuild cols 0-2 analytically (XYZ euler).
const float c0 = cosf(pos->rotation[0]), s0 = sinf(pos->rotation[0]); const float_t c0 = cosf(pos->rotation[0]), s0 = sinf(pos->rotation[0]);
const float c1 = cosf(pos->rotation[1]), s1 = sinf(pos->rotation[1]); const float_t c1 = cosf(pos->rotation[1]), s1 = sinf(pos->rotation[1]);
const float c2 = cosf(pos->rotation[2]), s2 = sinf(pos->rotation[2]); const float_t c2 = cosf(pos->rotation[2]), s2 = sinf(pos->rotation[2]);
const float s0s1 = s0 * s1; const float_t s0s1 = s0 * s1;
const float c0s1 = c0 * s1; const float_t c0s1 = c0 * s1;
pos->localTransform[0][0] = c1 * c2 * pos->scale[0]; pos->localTransform[0][0] = c1 * c2 * pos->scale[0];
pos->localTransform[0][1] = (c0 * s2 + s0s1 * c2) * pos->scale[0]; pos->localTransform[0][1] = (c0 * s2 + s0s1 * c2) * pos->scale[0];
@@ -53,7 +53,9 @@ static void entityPositionEnsureLocal(entityposition_t *pos) {
pos->localTransform[3][3] = 1.0f; pos->localTransform[3][3] = 1.0f;
} }
pos->flags &= ~(ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY); pos->flags &= ~(
ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY
);
} }
// Recompute worldTransform from the parent chain. Only called when WORLD_DIRTY. // Recompute worldTransform from the parent chain. Only called when WORLD_DIRTY.
@@ -62,13 +64,15 @@ static void entityPositionEnsureWorld(entityposition_t *pos) {
entityPositionEnsureLocal(pos); entityPositionEnsureLocal(pos);
if(pos->parentEntityId != ENTITY_ID_INVALID) { if(pos->parentEntityId != ENTITY_ID_INVALID) {
// Parented: world = parent.world × local. worldTransform must be written // Parented: world = parent.world x local. worldTransform must be written
// because children (and this node's getters) read it. // because children (and this node's getters) read it.
entityposition_t *parent = componentGetData( entityposition_t *parent = componentGetData(
pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
); );
entityPositionEnsureWorld(parent); entityPositionEnsureWorld(parent);
glm_mat4_mul(parent->worldTransform, pos->localTransform, pos->worldTransform); glm_mat4_mul(
parent->worldTransform, pos->localTransform, pos->worldTransform
);
} else if(pos->childCount > 0) { } else if(pos->childCount > 0) {
// Parentless root with children: children need a valid worldTransform to // Parentless root with children: children need a valid worldTransform to
// multiply against, but world == local, so just copy. // multiply against, but world == local, so just copy.
@@ -123,7 +127,8 @@ void entityPositionLookAt(
glm_lookat(eye, target, up, pos->localTransform); glm_lookat(eye, target, up, pos->localTransform);
// localTransform is now authoritative; PRS cache is stale. // localTransform is now authoritative; PRS cache is stale.
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_PRS_DIRTY) pos->flags = (pos->flags | ENTITY_POSITION_FLAG_PRS_DIRTY)
& ~(ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY); & ~(ENTITY_POSITION_FLAG_ROTATION_DIRTY |
ENTITY_POSITION_FLAG_POSITION_DIRTY);
entityPositionMarkDirty(pos); entityPositionMarkDirty(pos);
} }
@@ -137,7 +142,8 @@ void entityPositionGetTransform(
); );
entityPositionEnsureWorld(pos); entityPositionEnsureWorld(pos);
glm_mat4_copy( glm_mat4_copy(
pos->parentEntityId == ENTITY_ID_INVALID ? pos->localTransform : pos->worldTransform, pos->parentEntityId == ENTITY_ID_INVALID
? pos->localTransform : pos->worldTransform,
dest dest
); );
} }
@@ -254,20 +260,26 @@ void entityPositionGetWorldRotation(
return; return;
} }
entityPositionEnsureWorld(pos); entityPositionEnsureWorld(pos);
const float (*wt)[4] = pos->worldTransform; const float_t (*wt)[4] = pos->worldTransform;
const float sx = sqrtf(wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]); const float_t sx = sqrtf(
const float sy = sqrtf(wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][2]); wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]
const float sz = sqrtf(wt[2][0]*wt[2][0] + wt[2][1]*wt[2][1] + wt[2][2]*wt[2][2]); );
const float r00 = sx > 0.0f ? wt[0][0]/sx : 0.0f; const float_t sy = sqrtf(
const float r10 = sy > 0.0f ? wt[1][0]/sy : 0.0f; wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][2]
const float r20 = sz > 0.0f ? wt[2][0]/sz : 0.0f; );
const float r01 = sx > 0.0f ? wt[0][1]/sx : 0.0f; const float_t sz = sqrtf(
const float r11 = sy > 0.0f ? wt[1][1]/sy : 0.0f; wt[2][0]*wt[2][0] + wt[2][1]*wt[2][1] + wt[2][2]*wt[2][2]
const float r21 = sz > 0.0f ? wt[2][1]/sz : 0.0f; );
const float r22 = sz > 0.0f ? wt[2][2]/sz : 0.0f; const float_t r00 = sx > 0.0f ? wt[0][0]/sx : 0.0f;
const float sinBeta = glm_clamp(r20, -1.0f, 1.0f); const float_t r10 = sy > 0.0f ? wt[1][0]/sy : 0.0f;
const float_t r20 = sz > 0.0f ? wt[2][0]/sz : 0.0f;
const float_t r01 = sx > 0.0f ? wt[0][1]/sx : 0.0f;
const float_t r11 = sy > 0.0f ? wt[1][1]/sy : 0.0f;
const float_t r21 = sz > 0.0f ? wt[2][1]/sz : 0.0f;
const float_t r22 = sz > 0.0f ? wt[2][2]/sz : 0.0f;
const float_t sinBeta = glm_clamp(r20, -1.0f, 1.0f);
dest[1] = asinf(sinBeta); dest[1] = asinf(sinBeta);
const float cosBeta = cosf(dest[1]); const float_t cosBeta = cosf(dest[1]);
if(fabsf(cosBeta) > 1e-6f) { if(fabsf(cosBeta) > 1e-6f) {
dest[0] = atan2f(-r21, r22); dest[0] = atan2f(-r21, r22);
dest[2] = atan2f(-r10, r00); dest[2] = atan2f(-r10, r00);
@@ -312,29 +324,41 @@ void entityPositionSetWorldRotation(
entityPositionEnsureWorld(parent); entityPositionEnsureWorld(parent);
// Build target world rotation matrix (unit scale) from XYZ euler. // Build target world rotation matrix (unit scale) from XYZ euler.
const float c0 = cosf(rotation[0]), s0 = sinf(rotation[0]); const float_t c0 = cosf(rotation[0]), s0 = sinf(rotation[0]);
const float c1 = cosf(rotation[1]), s1 = sinf(rotation[1]); const float_t c1 = cosf(rotation[1]), s1 = sinf(rotation[1]);
const float c2 = cosf(rotation[2]), s2 = sinf(rotation[2]); const float_t c2 = cosf(rotation[2]), s2 = sinf(rotation[2]);
const float s0s1 = s0*s1, c0s1 = c0*s1; const float_t s0s1 = s0*s1, c0s1 = c0*s1;
// Named wr[col_stored][row_stored] matching cglm column-major layout. // Named wr[col_stored][row_stored] matching cglm column-major layout.
const float wr00 = c1*c2, wr01 = c0*s2 + s0s1*c2, wr02 = s0*s2 - c0s1*c2; const float_t wr00 = c1*c2;
const float wr10 = -c1*s2, wr11 = c0*c2 - s0s1*s2, wr12 = s0*c2 + c0s1*s2; const float_t wr01 = c0*s2 + s0s1*c2;
const float wr20 = s1, wr21 = -s0*c1, wr22 = c0*c1; const float_t wr02 = s0*s2 - c0s1*c2;
const float_t wr10 = -c1*s2;
const float_t wr11 = c0*c2 - s0s1*s2;
const float_t wr12 = s0*c2 + c0s1*s2;
const float_t wr20 = s1;
const float_t wr21 = -s0*c1;
const float_t wr22 = c0*c1;
// Normalize parent world columns to extract pure rotation. // Normalize parent world columns to extract pure rotation.
const float (*pt)[4] = parent->worldTransform; const float_t (*pt)[4] = parent->worldTransform;
const float psx = sqrtf(pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]); const float_t psx = sqrtf(
const float psy = sqrtf(pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]); pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]
const float psz = sqrtf(pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]); );
const float pr00 = psx > 0.f ? pt[0][0]/psx : 0.f; const float_t psy = sqrtf(
const float pr01 = psx > 0.f ? pt[0][1]/psx : 0.f; pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]
const float pr02 = psx > 0.f ? pt[0][2]/psx : 0.f; );
const float pr10 = psy > 0.f ? pt[1][0]/psy : 0.f; const float_t psz = sqrtf(
const float pr11 = psy > 0.f ? pt[1][1]/psy : 0.f; pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]
const float pr12 = psy > 0.f ? pt[1][2]/psy : 0.f; );
const float pr20 = psz > 0.f ? pt[2][0]/psz : 0.f; const float_t pr00 = psx > 0.f ? pt[0][0]/psx : 0.f;
const float pr21 = psz > 0.f ? pt[2][1]/psz : 0.f; const float_t pr01 = psx > 0.f ? pt[0][1]/psx : 0.f;
const float pr22 = psz > 0.f ? pt[2][2]/psz : 0.f; const float_t pr02 = psx > 0.f ? pt[0][2]/psx : 0.f;
const float_t pr10 = psy > 0.f ? pt[1][0]/psy : 0.f;
const float_t pr11 = psy > 0.f ? pt[1][1]/psy : 0.f;
const float_t pr12 = psy > 0.f ? pt[1][2]/psy : 0.f;
const float_t pr20 = psz > 0.f ? pt[2][0]/psz : 0.f;
const float_t pr21 = psz > 0.f ? pt[2][1]/psz : 0.f;
const float_t pr22 = psz > 0.f ? pt[2][2]/psz : 0.f;
// local_R = parent_R^T * world_R (R^-1 == R^T for orthogonal matrices). // local_R = parent_R^T * world_R (R^-1 == R^T for orthogonal matrices).
// Compute only the 7 entries of the local rotation matrix needed for XYZ // Compute only the 7 entries of the local rotation matrix needed for XYZ
@@ -343,23 +367,24 @@ void entityPositionSetWorldRotation(
// r21/r22 = stored[2][1..2] = math[1..2][2] // r21/r22 = stored[2][1..2] = math[1..2][2]
// r10/r00 = stored[1][0], stored[0][0] = math[0][1], math[0][0] // r10/r00 = stored[1][0], stored[0][0] = math[0][1], math[0][0]
// gimbal = stored[0][1], stored[1][1] = math[1][0], math[1][1] // gimbal = stored[0][1], stored[1][1] = math[1][0], math[1][1]
const float lr00 = pr00*wr00 + pr01*wr10 + pr02*wr20; // math[0][0] const float_t lr00 = pr00*wr00 + pr01*wr10 + pr02*wr20; // math[0][0]
const float lr10 = pr00*wr01 + pr01*wr11 + pr02*wr21; // math[0][1] const float_t lr10 = pr00*wr01 + pr01*wr11 + pr02*wr21; // math[0][1]
const float lr20 = pr00*wr02 + pr01*wr12 + pr02*wr22; // math[0][2] sinBeta const float_t lr20 = pr00*wr02 + pr01*wr12 + pr02*wr22; // [0][2] -> sinBeta
const float lr01 = pr10*wr00 + pr11*wr10 + pr12*wr20; // math[1][0] const float_t lr01 = pr10*wr00 + pr11*wr10 + pr12*wr20; // math[1][0]
const float lr11 = pr10*wr01 + pr11*wr11 + pr12*wr21; // math[1][1] const float_t lr11 = pr10*wr01 + pr11*wr11 + pr12*wr21; // math[1][1]
const float lr21 = pr10*wr02 + pr11*wr12 + pr12*wr22; // math[1][2] r21 const float_t lr21 = pr10*wr02 + pr11*wr12 + pr12*wr22; // [1][2] -> r21
const float lr22 = pr20*wr02 + pr21*wr12 + pr22*wr22; // math[2][2] r22 const float_t lr22 = pr20*wr02 + pr21*wr12 + pr22*wr22; // [2][2] -> r22
const float sinBeta = glm_clamp(lr20, -1.0f, 1.0f); const float_t sinBeta = glm_clamp(lr20, -1.0f, 1.0f);
pos->rotation[1] = asinf(sinBeta); pos->rotation[1] = asinf(sinBeta);
const float cosBeta = cosf(pos->rotation[1]); const float_t cosBeta = cosf(pos->rotation[1]);
if(fabsf(cosBeta) > 1e-6f) { if(fabsf(cosBeta) > 1e-6f) {
pos->rotation[0] = atan2f(-lr21, lr22); pos->rotation[0] = atan2f(-lr21, lr22);
pos->rotation[2] = atan2f(-lr10, lr00); pos->rotation[2] = atan2f(-lr10, lr00);
} else { } else {
pos->rotation[2] = 0.0f; pos->rotation[2] = 0.0f;
pos->rotation[0] = (sinBeta > 0.0f) ? atan2f(lr01, lr11) : -atan2f(lr01, lr11); pos->rotation[0] = (sinBeta > 0.0f)
? atan2f(lr01, lr11) : -atan2f(lr01, lr11);
} }
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY) pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY; & ~ENTITY_POSITION_FLAG_PRS_DIRTY;
@@ -392,7 +417,7 @@ void entityPositionGetWorldScale(
return; return;
} }
entityPositionEnsureWorld(pos); entityPositionEnsureWorld(pos);
const float (*wt)[4] = pos->worldTransform; const float_t (*wt)[4] = pos->worldTransform;
dest[0] = sqrtf(wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]); dest[0] = sqrtf(wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]);
dest[1] = sqrtf(wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][2]); dest[1] = sqrtf(wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][2]);
dest[2] = sqrtf(wt[2][0]*wt[2][0] + wt[2][1]*wt[2][1] + wt[2][2]*wt[2][2]); dest[2] = sqrtf(wt[2][0]*wt[2][0] + wt[2][1]*wt[2][1] + wt[2][2]*wt[2][2]);
@@ -431,10 +456,16 @@ void entityPositionSetWorldScale(
pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
); );
entityPositionEnsureWorld(parent); entityPositionEnsureWorld(parent);
const float (*pt)[4] = parent->worldTransform; const float_t (*pt)[4] = parent->worldTransform;
const float psx = sqrtf(pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]); const float_t psx = sqrtf(
const float psy = sqrtf(pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]); pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]
const float psz = sqrtf(pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]); );
const float_t psy = sqrtf(
pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]
);
const float_t psz = sqrtf(
pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]
);
pos->scale[0] = psx > 0.0f ? scale[0] / psx : scale[0]; pos->scale[0] = psx > 0.0f ? scale[0] / psx : scale[0];
pos->scale[1] = psy > 0.0f ? scale[1] / psy : scale[1]; pos->scale[1] = psy > 0.0f ? scale[1] / psy : scale[1];
pos->scale[2] = psz > 0.0f ? scale[2] / psz : scale[2]; pos->scale[2] = psz > 0.0f ? scale[2] / psz : scale[2];
@@ -501,8 +532,11 @@ entityposition_t *entityPositionGet(
} }
void entityPositionRebuild(entityposition_t *pos) { void entityPositionRebuild(entityposition_t *pos) {
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY) pos->flags = (
& ~ENTITY_POSITION_FLAG_PRS_DIRTY; pos->flags |
ENTITY_POSITION_FLAG_ROTATION_DIRTY |
ENTITY_POSITION_FLAG_POSITION_DIRTY
) & ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(pos); entityPositionMarkDirty(pos);
} }
@@ -514,7 +548,9 @@ void entityPositionDisposeDeep(
// Detach from parent so the parent's child list stays consistent. // Detach from parent so the parent's child list stays consistent.
if(pos->parentEntityId != ENTITY_ID_INVALID) { if(pos->parentEntityId != ENTITY_ID_INVALID) {
entityPositionSetParent(entityId, componentId, ENTITY_ID_INVALID, COMPONENT_ID_INVALID); entityPositionSetParent(
entityId, componentId, ENTITY_ID_INVALID, COMPONENT_ID_INVALID
);
} }
// Copy the child list before disposing self (entityDispose invalidates pos). // Copy the child list before disposing self (entityDispose invalidates pos).
@@ -524,8 +560,10 @@ void entityPositionDisposeDeep(
for(uint8_t i = 0; i < childCount; i++) { for(uint8_t i = 0; i < childCount; i++) {
childEntityIds[i] = pos->childEntityIds[i]; childEntityIds[i] = pos->childEntityIds[i];
childComponentIds[i] = pos->childComponentIds[i]; childComponentIds[i] = pos->childComponentIds[i];
// Sever the child's parent link so it won't try to modify our disposed data. // Sever child's parent link so it won't try to modify our disposed data.
entityposition_t *child = entityPositionGet(childEntityIds[i], childComponentIds[i]); entityposition_t *child = entityPositionGet(
childEntityIds[i], childComponentIds[i]
);
child->parentEntityId = ENTITY_ID_INVALID; child->parentEntityId = ENTITY_ID_INVALID;
child->parentComponentId = COMPONENT_ID_INVALID; child->parentComponentId = COMPONENT_ID_INVALID;
} }
@@ -560,24 +598,24 @@ void entityPositionDecompose(entityposition_t *pos) {
pos->localTransform[2][2] * pos->localTransform[2][2] pos->localTransform[2][2] * pos->localTransform[2][2]
); );
// Normalize columns to isolate the rotation matrix (9 floats, no mat4 needed). // Normalize columns to isolate the rotation matrix (no mat4 needed).
const float invS0 = pos->scale[0] > 0.0f ? 1.0f / pos->scale[0] : 0.0f; const float_t invS0 = pos->scale[0] > 0.0f ? 1.0f / pos->scale[0] : 0.0f;
const float invS1 = pos->scale[1] > 0.0f ? 1.0f / pos->scale[1] : 0.0f; const float_t invS1 = pos->scale[1] > 0.0f ? 1.0f / pos->scale[1] : 0.0f;
const float invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f; const float_t invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f;
const float r00 = pos->localTransform[0][0] * invS0; const float_t r00 = pos->localTransform[0][0] * invS0;
const float r01 = pos->localTransform[0][1] * invS0; const float_t r01 = pos->localTransform[0][1] * invS0;
const float r02 = pos->localTransform[0][2] * invS0; const float_t r02 = pos->localTransform[0][2] * invS0;
const float r10 = pos->localTransform[1][0] * invS1; const float_t r10 = pos->localTransform[1][0] * invS1;
const float r11 = pos->localTransform[1][1] * invS1; const float_t r11 = pos->localTransform[1][1] * invS1;
const float r20 = pos->localTransform[2][0] * invS2; const float_t r20 = pos->localTransform[2][0] * invS2;
const float r21 = pos->localTransform[2][1] * invS2; const float_t r21 = pos->localTransform[2][1] * invS2;
const float r22 = pos->localTransform[2][2] * invS2; const float_t r22 = pos->localTransform[2][2] * invS2;
// Extract XYZ euler angles (R = Rx * Ry * Rz, column-major) // Extract XYZ euler angles (R = Rx * Ry * Rz, column-major)
const float sinBeta = glm_clamp(r20, -1.0f, 1.0f); const float_t sinBeta = glm_clamp(r20, -1.0f, 1.0f);
pos->rotation[1] = asinf(sinBeta); pos->rotation[1] = asinf(sinBeta);
const float cosBeta = cosf(pos->rotation[1]); const float_t cosBeta = cosf(pos->rotation[1]);
if(fabsf(cosBeta) > 1e-6f) { if(fabsf(cosBeta) > 1e-6f) {
pos->rotation[0] = atan2f(-r21, r22); pos->rotation[0] = atan2f(-r21, r22);
@@ -32,21 +32,21 @@
/** /**
* worldTransform is stale. Either the local matrix changed or an ancestor * worldTransform is stale. Either the local matrix changed or an ancestor
* moved; the full parent-chain multiply must be rerun before world data is read. * moved; worldTransform must be recomputed before world data can be read.
*/ */
#define ENTITY_POSITION_FLAG_WORLD_DIRTY (1 << 3) #define ENTITY_POSITION_FLAG_WORLD_DIRTY (1 << 3)
typedef struct { typedef struct {
/* /*
* Hot fields flag checks and parent/child traversal (markDirty, ensureWorld) * Hot fields - flag checks, parent/child traversal (markDirty, ensureWorld)
* only touch these. Kept at the front so they share the first cache line. * only touch these. Kept at the front so they share the first cache line.
*/ */
/** Bitmask of ENTITY_POSITION_FLAG_* values describing which caches are stale. */ /** ENTITY_POSITION_FLAG_* bitmask; describes which caches are stale. */
uint8_t flags; uint8_t flags;
/** Entity ID of the parent node, or ENTITY_ID_INVALID if none. */ /** Entity ID of the parent node, or ENTITY_ID_INVALID if none. */
entityid_t parentEntityId; entityid_t parentEntityId;
/** Component ID of the parent position component, or COMPONENT_ID_INVALID if none. */ /** Component ID of the parent position, or COMPONENT_ID_INVALID if none. */
componentid_t parentComponentId; componentid_t parentComponentId;
/** Number of currently registered children. */ /** Number of currently registered children. */
uint8_t childCount; uint8_t childCount;
@@ -56,19 +56,19 @@ typedef struct {
componentid_t childComponentIds[ENTITY_POSITION_CHILDREN_MAX]; componentid_t childComponentIds[ENTITY_POSITION_CHILDREN_MAX];
/* /*
* Warm fields read/written by PRS getters/setters. * Warm fields - read/written by PRS getters/setters.
* Accessed more often than the matrices but less often than flags. * Accessed more often than the matrices but less often than flags.
*/ */
/** Cached local position (XYZ). May be stale when ENTITY_POSITION_FLAG_PRS_DIRTY is set. */ /** Cached local position (XYZ). Stale when PRS_DIRTY is set. */
vec3 position; vec3 position;
/** Cached local euler rotation (XYZ, radians). May be stale when ENTITY_POSITION_FLAG_PRS_DIRTY is set. */ /** Cached local rotation (XYZ euler, radians). Stale when PRS_DIRTY. */
vec3 rotation; vec3 rotation;
/** Cached local scale (XYZ). May be stale when ENTITY_POSITION_FLAG_PRS_DIRTY is set. */ /** Cached local scale (XYZ). Stale when PRS_DIRTY is set. */
vec3 scale; vec3 scale;
/* /*
* Cold fields only touched when actually rebuilding transforms. * Cold fields - only touched when actually rebuilding transforms.
*/ */
/** Local transform matrix, rebuilt lazily from position/rotation/scale. */ /** Local transform matrix, rebuilt lazily from position/rotation/scale. */
@@ -338,7 +338,7 @@ entityposition_t *entityPositionGet(
* Signals that the PRS cache was modified externally. Sets both * Signals that the PRS cache was modified externally. Sets both
* ENTITY_POSITION_FLAG_ROTATION_DIRTY and ENTITY_POSITION_FLAG_POSITION_DIRTY * ENTITY_POSITION_FLAG_ROTATION_DIRTY and ENTITY_POSITION_FLAG_POSITION_DIRTY
* so all of localTransform is rebuilt lazily on the next read, clears * so all of localTransform is rebuilt lazily on the next read, clears
* ENTITY_POSITION_FLAG_PRS_DIRTY, and propagates ENTITY_POSITION_FLAG_WORLD_DIRTY * ENTITY_POSITION_FLAG_PRS_DIRTY, propagates ENTITY_POSITION_FLAG_WORLD_DIRTY
* to self and all descendants. * to self and all descendants.
* *
* @param pos The position component whose PRS was modified. * @param pos The position component whose PRS was modified.
@@ -1,49 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityinteractable.h"
#include "entity/entitymanager.h"
void entityInteractableInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityinteractable_t *inter = entityInteractableGet(entityId, componentId);
inter->onInteract = NULL;
inter->user = NULL;
}
entityinteractable_t * entityInteractableGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(entityId, componentId, COMPONENT_TYPE_INTERACTABLE);
}
void entityInteractableSetCallback(
const entityid_t entityId,
const componentid_t componentId,
void (*onInteract)(
const entityid_t entityId,
const componentid_t componentId,
void *user
),
void *user
) {
entityinteractable_t *inter = entityInteractableGet(entityId, componentId);
inter->onInteract = onInteract;
inter->user = user;
}
void entityInteractableTrigger(
const entityid_t entityId,
const componentid_t componentId
) {
entityinteractable_t *inter = entityInteractableGet(entityId, componentId);
if(inter->onInteract == NULL) return;
inter->onInteract(entityId, componentId, inter->user);
}
@@ -1,71 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
typedef struct {
void (*onInteract)(
const entityid_t entityId,
const componentid_t componentId,
void *user
);
void *user;
} entityinteractable_t;
/**
* Initializes the interactable component, clearing the callback and user pointer.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
*/
void entityInteractableInit(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Returns a pointer to the interactable component data.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @return Pointer to the entityinteractable_t data.
*/
entityinteractable_t * entityInteractableGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the callback invoked when this interactable is triggered.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @param onInteract Function called on interaction, or NULL to clear.
* @param user Arbitrary pointer forwarded to the callback.
*/
void entityInteractableSetCallback(
const entityid_t entityId,
const componentid_t componentId,
void (*onInteract)(
const entityid_t entityId,
const componentid_t componentId,
void *user
),
void *user
);
/**
* Fires the interactable's callback if one is set.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
*/
void entityInteractableTrigger(
const entityid_t entityId,
const componentid_t componentId
);
@@ -1,55 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityoverworld.h"
#include "entity/entitymanager.h"
#include "entity/component/display/entityrenderable.h"
#include "display/shader/shaderunlit.h"
#include "display/mesh/cube.h"
void entityOverworldInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityoverworld_t *ow = entityOverworldGet(entityId, componentId);
ow->type = OVERWORLD_ENTITY_TYPE_NPC;
ow->facing = FACING_DIR_DOWN;
ow->renderCompId = entityGetComponent(entityId, COMPONENT_TYPE_RENDERABLE);
if(ow->renderCompId != COMPONENT_ID_INVALID) {
entityRenderableSetDraw(entityId, ow->renderCompId, entityOverworldDraw, NULL);
}
ow->physCompId = entityGetComponent(entityId, COMPONENT_TYPE_PHYSICS);
}
entityoverworld_t * entityOverworldGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(entityId, componentId, COMPONENT_TYPE_OVERWORLD);
}
void entityOverworldSetType(
const entityid_t entityId,
const componentid_t componentId,
const entityoverworldtype_t type
) {
entityOverworldGet(entityId, componentId)->type = type;
}
errorret_t entityOverworldDraw(
const entityid_t entityId,
const componentid_t componentId,
void *user
) {
componentid_t owCompId = entityGetComponent(entityId, COMPONENT_TYPE_OVERWORLD);
entityoverworld_t *ow = entityOverworldGet(entityId, owCompId);
color_t col = ow->type == OVERWORLD_ENTITY_TYPE_PLAYER ? COLOR_WHITE : COLOR_BLUE;
errorChain(shaderSetColor(&SHADER_UNLIT, SHADER_UNLIT_COLOR, col));
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, NULL));
return meshDraw(&CUBE_MESH_SIMPLE, 0, -1);
}
@@ -1,74 +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 "entity/entitybase.h"
#include "overworld/facingdir.h"
typedef enum {
OVERWORLD_ENTITY_TYPE_PLAYER = 0,
OVERWORLD_ENTITY_TYPE_NPC = 1,
} entityoverworldtype_t;
typedef struct {
entityoverworldtype_t type;
facingdir_t facing;
componentid_t renderCompId;
componentid_t physCompId;
} entityoverworld_t;
/**
* Initializes the overworld component, wiring up the draw callback if a
* renderable component is already present on the entity.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
*/
void entityOverworldInit(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Returns a pointer to the overworld component data.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @return Pointer to the entityoverworld_t data.
*/
entityoverworld_t * entityOverworldGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the overworld entity type.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @param type The type to assign.
*/
void entityOverworldSetType(
const entityid_t entityId,
const componentid_t componentId,
const entityoverworldtype_t type
);
/**
* Draw callback registered on the renderable component.
*
* @param entityId The owning entity.
* @param componentId The renderable component's ID.
* @param user Unused.
* @return Error result.
*/
errorret_t entityOverworldDraw(
const entityid_t entityId,
const componentid_t componentId,
void *user
);
@@ -1,66 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityoverworldcamera.h"
#include "entity/entitymanager.h"
#include "entity/component/display/entityposition.h"
#include "entity/component/display/entitycamera.h"
void entityOverworldCameraInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityoverworldcamera_t *cam = entityOverworldCameraGet(entityId, componentId);
cam->targetEntityId = ENTITY_ID_INVALID;
cam->targetPosCompId = COMPONENT_ID_INVALID;
glm_vec3_zero(cam->targetOffset);
glm_vec3_zero(cam->eyeOffset);
cam->scale = 1.0f;
}
entityoverworldcamera_t * entityOverworldCameraGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(entityId, componentId, COMPONENT_TYPE_OVERWORLD_CAMERA);
}
void entityOverworldCameraSetTarget(
const entityid_t entityId,
const componentid_t componentId,
const entityid_t targetEntityId,
const componentid_t targetPosCompId
) {
entityoverworldcamera_t *cam = entityOverworldCameraGet(entityId, componentId);
cam->targetEntityId = targetEntityId;
cam->targetPosCompId = targetPosCompId;
}
errorret_t entityOverworldCameraRender(
const entityid_t entityId,
const componentid_t componentId
) {
entityoverworldcamera_t *cam = entityOverworldCameraGet(entityId, componentId);
vec3 targetPos;
entityPositionGetWorldPosition(
cam->targetEntityId, cam->targetPosCompId, targetPos
);
vec3 center = {
targetPos[0] + cam->targetOffset[0],
targetPos[1] + cam->targetOffset[1],
targetPos[2] + cam->targetOffset[2]
};
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
componentid_t camComp = entityGetComponent(entityId, COMPONENT_TYPE_CAMERA);
entityCameraLookAtPixelPerfect(
entityId, posComp, camComp, center, cam->eyeOffset, cam->scale
);
errorOk();
}
@@ -1,69 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "error/error.h"
typedef struct {
entityid_t targetEntityId;
componentid_t targetPosCompId;
vec3 targetOffset;
vec3 eyeOffset;
float_t scale;
} entityoverworldcamera_t;
/**
* Initializes the overworld camera component.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
*/
void entityOverworldCameraInit(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Returns a pointer to the overworld camera component data.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @return Pointer to the entityoverworldcamera_t data.
*/
entityoverworldcamera_t * entityOverworldCameraGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the entity and position component the camera will follow.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @param targetEntityId Entity to follow.
* @param targetPosCompId Position component on the target entity.
*/
void entityOverworldCameraSetTarget(
const entityid_t entityId,
const componentid_t componentId,
const entityid_t targetEntityId,
const componentid_t targetPosCompId
);
/**
* Render callback: updates the camera position to track the target entity.
* Called automatically each frame via componentRenderAll.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @return Error state.
*/
errorret_t entityOverworldCameraRender(
const entityid_t entityId,
const componentid_t componentId
);
@@ -1,83 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityoverworldtrigger.h"
#include "entity/entitymanager.h"
#include "entity/component/display/entityposition.h"
static void entityOverworldTriggerUpdate(
const entityid_t entityId,
const componentid_t componentId,
void *user
) {
entityoverworldtrigger_t *t = entityOverworldTriggerGet(entityId, componentId);
// Find the player position.
vec3 playerPos;
bool_t playerFound = false;
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) == 0) continue;
if(entityGetComponent(i, COMPONENT_TYPE_PLAYER) == COMPONENT_ID_INVALID) continue;
componentid_t posComp = entityGetComponent(i, COMPONENT_TYPE_POSITION);
if(posComp == COMPONENT_ID_INVALID) continue;
entityPositionGetWorldPosition(i, posComp, playerPos);
playerFound = true;
break;
}
bool_t wasInside = t->playerInside;
bool_t nowInside = playerFound && (
playerPos[0] >= t->min[0] && playerPos[0] <= t->max[0] &&
playerPos[1] >= t->min[1] && playerPos[1] <= t->max[1] &&
playerPos[2] >= t->min[2] && playerPos[2] <= t->max[2]
);
t->playerInside = nowInside;
if(nowInside) {
if(!wasInside && t->onEnter) t->onEnter(entityId, componentId, t->user);
if(t->onStay) t->onStay(entityId, componentId, t->user);
} else {
if(wasInside && t->onExit) t->onExit(entityId, componentId, t->user);
if(t->onOutside) t->onOutside(entityId, componentId, t->user);
}
}
void entityOverworldTriggerInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityoverworldtrigger_t *t = entityOverworldTriggerGet(entityId, componentId);
glm_vec3_zero(t->min);
glm_vec3_zero(t->max);
t->playerInside = false;
t->onEnter = NULL;
t->onExit = NULL;
t->onStay = NULL;
t->onOutside = NULL;
t->user = NULL;
entityUpdateAdd(entityId, entityOverworldTriggerUpdate, componentId, NULL);
}
entityoverworldtrigger_t * entityOverworldTriggerGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(
entityId, componentId, COMPONENT_TYPE_OVERWORLD_TRIGGER
);
}
void entityOverworldTriggerSetBounds(
const entityid_t entityId,
const componentid_t componentId,
const vec3 min,
const vec3 max
) {
entityoverworldtrigger_t *t = entityOverworldTriggerGet(entityId, componentId);
glm_vec3_copy((float_t*)min, t->min);
glm_vec3_copy((float_t*)max, t->max);
}
@@ -1,54 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
typedef void (*entityoverworldtriggercallback_t)(
const entityid_t entityId,
const componentid_t componentId,
void *user
);
typedef struct {
vec3 min;
vec3 max;
bool_t playerInside;
entityoverworldtriggercallback_t onEnter;
entityoverworldtriggercallback_t onExit;
entityoverworldtriggercallback_t onStay;
entityoverworldtriggercallback_t onOutside;
void *user;
} entityoverworldtrigger_t;
/**
* Initializes the overworld trigger component and registers its update
* callback with the entity manager. The trigger is entirely self-contained
* after init — no scene-level wiring required.
*/
void entityOverworldTriggerInit(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Returns a pointer to the overworld trigger component data.
*/
entityoverworldtrigger_t * entityOverworldTriggerGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the trigger AABB bounds.
*/
void entityOverworldTriggerSetBounds(
const entityid_t entityId,
const componentid_t componentId,
const vec3 min,
const vec3 max
);
@@ -1,103 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityplayer.h"
#include "entity/entitymanager.h"
#include "entity/component/display/entityposition.h"
#include "entity/component/physics/entityphysics.h"
#include "entity/component/overworld/entityoverworld.h"
#include "entity/component/overworld/entityinteractable.h"
#include "input/input.h"
void entityPlayerInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityplayer_t *player = entityPlayerGet(entityId, componentId);
player->speed = ENTITY_PLAYER_SPEED;
player->runSpeed = ENTITY_PLAYER_RUN_SPEED;
}
entityplayer_t * entityPlayerGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(entityId, componentId, COMPONENT_TYPE_PLAYER);
}
void entityPlayerUpdate(
const entityid_t entityId,
const componentid_t componentId
) {
entityplayer_t *player = entityPlayerGet(entityId, componentId);
vec2 dir;
inputAngle2D(
INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT,
INPUT_ACTION_UP, INPUT_ACTION_DOWN,
dir
);
float_t speed = (
inputIsDown(INPUT_ACTION_CANCEL) ? player->runSpeed : player->speed
);
componentid_t owCompId = entityGetComponent(entityId, COMPONENT_TYPE_OVERWORLD);
entityoverworld_t *ow = entityOverworldGet(entityId, owCompId);
if(ow && glm_vec2_norm(dir) > 0.0f) {
if(fabsf(dir[0]) >= fabsf(dir[1])) {
ow->facing = dir[0] > 0.0f ? FACING_DIR_RIGHT : FACING_DIR_LEFT;
} else {
ow->facing = dir[1] > 0.0f ? FACING_DIR_DOWN : FACING_DIR_UP;
}
}
vec3 vel;
entityPhysicsGetVelocity(entityId, ow->physCompId, vel);
vel[0] = dir[0] * speed;
vel[2] = dir[1] * speed;
entityPhysicsSetVelocity(entityId, ow->physCompId, vel);
if(!inputPressed(INPUT_ACTION_ACCEPT)) return;
vec3 playerPos;
componentid_t playerPosCompId = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
if(playerPosCompId == COMPONENT_ID_INVALID) return;
entityPositionGetWorldPosition(entityId, playerPosCompId, playerPos);
vec2 facingDir;
facingDirToVec2(ow ? ow->facing : FACING_DIR_DOWN, facingDir);
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) == 0) continue;
if(i == entityId) continue;
componentid_t interComp = entityGetComponent(i, COMPONENT_TYPE_INTERACTABLE);
if(interComp == COMPONENT_ID_INVALID) continue;
componentid_t posComp = entityGetComponent(i, COMPONENT_TYPE_POSITION);
if(posComp == COMPONENT_ID_INVALID) continue;
vec3 targetPos;
entityPositionGetWorldPosition(i, posComp, targetPos);
vec2 toTarget = {
targetPos[0] - playerPos[0],
targetPos[2] - playerPos[2],
};
float_t forward = glm_vec2_dot(facingDir, toTarget);
if(forward <= 0.0f || forward > ENTITY_PLAYER_INTERACT_RANGE) continue;
float_t lateral = fabsf(
facingDir[0] * toTarget[1] - facingDir[1] * toTarget[0]
);
if(lateral > ENTITY_PLAYER_INTERACT_LATERAL) continue;
entityInteractableTrigger(i, interComp);
}
}
@@ -1,52 +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 "entity/entitybase.h"
#define ENTITY_PLAYER_SPEED 4.0f
#define ENTITY_PLAYER_RUN_SPEED 8.0f
#define ENTITY_PLAYER_INTERACT_RANGE 1.5f
#define ENTITY_PLAYER_INTERACT_LATERAL 0.6f
typedef struct {
float_t speed;
float_t runSpeed;
} entityplayer_t;
/**
* Initializes the player component.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
*/
void entityPlayerInit(const entityid_t entityId, const componentid_t componentId);
/**
* Returns a pointer to the player component data.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
* @return Pointer to the entityplayer_t data.
*/
entityplayer_t * entityPlayerGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Reads input, moves the player, updates facing direction, and checks for
* interactable entities in front of the player when accept is pressed.
*
* @param entityId The owning entity.
* @param componentId This component's ID.
*/
void entityPlayerUpdate(
const entityid_t entityId,
const componentid_t componentId
);
+4 -12
View File
@@ -10,11 +10,6 @@
#include "entity/component/display/entityrenderable.h" #include "entity/component/display/entityrenderable.h"
#include "entity/component/physics/entityphysics.h" #include "entity/component/physics/entityphysics.h"
#include "entity/component/trigger/entitytrigger.h" #include "entity/component/trigger/entitytrigger.h"
#include "entity/component/overworld/entityoverworld.h"
#include "entity/component/overworld/entityoverworldtrigger.h"
#include "entity/component/overworld/entityplayer.h"
#include "entity/component/overworld/entityinteractable.h"
#include "entity/component/overworld/entityoverworldcamera.h"
// Name (Uppercase) // Name (Uppercase)
// Structure // Structure
@@ -25,11 +20,8 @@
X(POSITION, entityposition_t, position, entityPositionInit, NULL, NULL) X(POSITION, entityposition_t, position, entityPositionInit, NULL, NULL)
X(CAMERA, entitycamera_t, camera, entityCameraInit, NULL, NULL) X(CAMERA, entitycamera_t, camera, entityCameraInit, NULL, NULL)
X(RENDERABLE, entityrenderable_t, renderable, entityRenderableInit, entityRenderableDispose, NULL) X(RENDERABLE, entityrenderable_t, renderable,
X(PHYSICS, entityphysics_t, physics, entityPhysicsInit, entityPhysicsDispose, NULL) entityRenderableInit, entityRenderableDispose, NULL)
X(PHYSICS, entityphysics_t, physics,
entityPhysicsInit, entityPhysicsDispose, NULL)
X(TRIGGER, entitytrigger_t, trigger, entityTriggerInit, NULL, NULL) X(TRIGGER, entitytrigger_t, trigger, entityTriggerInit, NULL, NULL)
X(OVERWORLD, entityoverworld_t, overworld, entityOverworldInit, NULL, NULL)
X(PLAYER, entityplayer_t, player, entityPlayerInit, NULL, NULL)
X(INTERACTABLE, entityinteractable_t, interactable, entityInteractableInit, NULL, NULL)
X(OVERWORLD_CAMERA, entityoverworldcamera_t, overworldCamera, entityOverworldCameraInit, NULL, entityOverworldCameraRender)
X(OVERWORLD_TRIGGER, entityoverworldtrigger_t, overworldTrigger, entityOverworldTriggerInit, NULL, NULL)
+11 -3
View File
@@ -92,7 +92,9 @@ void entityDispose(const entityid_t entityId) {
entity_t *ent = &ENTITY_MANAGER.entities[entityId]; entity_t *ent = &ENTITY_MANAGER.entities[entityId];
for(uint8_t i = 0; i < ent->disposeCount; i++) { for(uint8_t i = 0; i < ent->disposeCount; i++) {
ent->onDispose[i](entityId, ent->disposeComponentId[i], ent->disposeUser[i]); ent->onDispose[i](
entityId, ent->disposeComponentId[i], ent->disposeUser[i]
);
} }
for(componentid_t i = 0; i < ENTITY_COMPONENT_COUNT_MAX; i++) { for(componentid_t i = 0; i < ENTITY_COMPONENT_COUNT_MAX; i++) {
@@ -125,7 +127,10 @@ void entityUpdateAdd(
ent->updateCount++; ent->updateCount++;
} }
void entityUpdateRemove(const entityid_t entityId, const entitycallback_t callback) { void entityUpdateRemove(
const entityid_t entityId,
const entitycallback_t callback
) {
entity_t *ent = &ENTITY_MANAGER.entities[entityId]; entity_t *ent = &ENTITY_MANAGER.entities[entityId];
for(uint8_t i = 0; i < ent->updateCount; i++) { for(uint8_t i = 0; i < ent->updateCount; i++) {
if(ent->onUpdate[i] != callback) continue; if(ent->onUpdate[i] != callback) continue;
@@ -156,7 +161,10 @@ void entityDisposeAdd(
ent->disposeCount++; ent->disposeCount++;
} }
void entityDisposeRemove(const entityid_t entityId, const entitycallback_t callback) { void entityDisposeRemove(
const entityid_t entityId,
const entitycallback_t callback
) {
entity_t *ent = &ENTITY_MANAGER.entities[entityId]; entity_t *ent = &ENTITY_MANAGER.entities[entityId];
for(uint8_t i = 0; i < ent->disposeCount; i++) { for(uint8_t i = 0; i < ent->disposeCount; i++) {
if(ent->onDispose[i] != callback) continue; if(ent->onDispose[i] != callback) continue;
+8 -2
View File
@@ -106,7 +106,10 @@ void entityUpdateAdd(
* @param entityId The entity to remove from. * @param entityId The entity to remove from.
* @param callback The function to remove. * @param callback The function to remove.
*/ */
void entityUpdateRemove(const entityid_t entityId, const entitycallback_t callback); void entityUpdateRemove(
const entityid_t entityId,
const entitycallback_t callback
);
/** /**
* Registers a dispose callback, invoked at the start of entityDispose before * Registers a dispose callback, invoked at the start of entityDispose before
@@ -128,4 +131,7 @@ void entityDisposeAdd(
* @param entityId The entity to remove from. * @param entityId The entity to remove from.
* @param callback The function to remove. * @param callback The function to remove.
*/ */
void entityDisposeRemove(const entityid_t entityId, const entitycallback_t callback); void entityDisposeRemove(
const entityid_t entityId,
const entitycallback_t callback
);
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+6 -1
View File
@@ -9,7 +9,12 @@
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
void eventInit(event_t *event, eventcallback_t *callbacks, void **users, size_t size) { void eventInit(
event_t *event,
eventcallback_t *callbacks,
void **users,
size_t size
) {
assertNotNull(event, "event must not be NULL"); assertNotNull(event, "event must not be NULL");
assertNotNull((void *)callbacks, "callbacks must not be NULL"); assertNotNull((void *)callbacks, "callbacks must not be NULL");
assertTrue(size > 0, "size must be greater than 0"); assertTrue(size > 0, "size must be greater than 0");
+15 -3
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -22,8 +22,20 @@ errorret_t inputInit(void) {
INPUT.actions[i].action = (inputaction_t)i; INPUT.actions[i].action = (inputaction_t)i;
INPUT.actions[i].lastValue = 0.0f; INPUT.actions[i].lastValue = 0.0f;
INPUT.actions[i].currentValue = 0.0f; INPUT.actions[i].currentValue = 0.0f;
eventInit(&INPUT.actions[i].onPressed, INPUT.actions[i].onPressedCallbacks, INPUT.actions[i].onPressedUsers, 4);
eventInit(&INPUT.actions[i].onReleased, INPUT.actions[i].onReleasedCallbacks, INPUT.actions[i].onReleasedUsers, 4); eventInit(
&INPUT.actions[i].onPressed,
INPUT.actions[i].onPressedCallbacks,
INPUT.actions[i].onPressedUsers,
INPUT_ACTION_CALLBACK_COUNT_MAX
);
eventInit(
&INPUT.actions[i].onReleased,
INPUT.actions[i].onReleasedCallbacks,
INPUT.actions[i].onReleasedUsers,
INPUT_ACTION_CALLBACK_COUNT_MAX
);
} }
#ifdef inputInitPlatform #ifdef inputInitPlatform
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+7 -5
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
@@ -10,6 +10,8 @@
#include "input/inputactiondefs.h" #include "input/inputactiondefs.h"
#include "event/event.h" #include "event/event.h"
#define INPUT_ACTION_CALLBACK_COUNT_MAX 4
typedef struct { typedef struct {
inputaction_t action; inputaction_t action;
float_t lastValue; float_t lastValue;
@@ -20,11 +22,11 @@ typedef struct {
float_t currentDynamicValue; float_t currentDynamicValue;
#endif #endif
eventcallback_t onPressedCallbacks[4]; eventcallback_t onPressedCallbacks[INPUT_ACTION_CALLBACK_COUNT_MAX];
void *onPressedUsers[4]; void *onPressedUsers[INPUT_ACTION_CALLBACK_COUNT_MAX];
event_t onPressed; event_t onPressed;
eventcallback_t onReleasedCallbacks[4]; eventcallback_t onReleasedCallbacks[INPUT_ACTION_CALLBACK_COUNT_MAX];
void *onReleasedUsers[4]; void *onReleasedUsers[INPUT_ACTION_CALLBACK_COUNT_MAX];
event_t onReleased; event_t onReleased;
} inputactiondata_t; } inputactiondata_t;
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2026 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
+1 -1
View File
@@ -23,6 +23,6 @@ typedef enum {
* Converts a facing direction to a normalized XZ vec2. * Converts a facing direction to a normalized XZ vec2.
* *
* @param facing The facing direction. * @param facing The facing direction.
* @param dest Output vec2 [0] is X, [1] is Z. * @param dest Output vec2 - [0] is X, [1] is Z.
*/ */
void facingDirToVec2(facingdir_t facing, vec2 dest); void facingDirToVec2(facingdir_t facing, vec2 dest);
+18 -18
View File
@@ -7,7 +7,7 @@
#include "physicstest.h" #include "physicstest.h"
bool physicsTestAabbVsAabb( bool_t physicsTestAabbVsAabb(
const vec3 ac, const vec3 ah, const vec3 ac, const vec3 ah,
const vec3 bc, const vec3 bh, const vec3 bc, const vec3 bh,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -36,7 +36,7 @@ bool physicsTestAabbVsAabb(
return true; return true;
} }
bool physicsTestSphereVsSphere( bool_t physicsTestSphereVsSphere(
const vec3 ac, const float_t ar, const vec3 ac, const float_t ar,
const vec3 bc, const float_t br, const vec3 bc, const float_t br,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -61,7 +61,7 @@ bool physicsTestSphereVsSphere(
return true; return true;
} }
bool physicsTestSphereVsAabb( bool_t physicsTestSphereVsAabb(
const vec3 sc, const float_t sr, const vec3 sc, const float_t sr,
const vec3 ac, const vec3 ah, const vec3 ac, const vec3 ah,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -76,7 +76,7 @@ bool physicsTestSphereVsAabb(
glm_vec3_sub((float_t *)sc, closest, diff); glm_vec3_sub((float_t *)sc, closest, diff);
float_t dist2 = glm_vec3_norm2(diff); float_t dist2 = glm_vec3_norm2(diff);
bool inside = (dist2 < 1e-10f); bool_t inside = (dist2 < 1e-10f);
if(!inside && dist2 >= sr * sr) return false; if(!inside && dist2 >= sr * sr) return false;
if(!inside) { if(!inside) {
@@ -95,8 +95,8 @@ bool physicsTestSphereVsAabb(
const float_t normals[6][3] = { const float_t normals[6][3] = {
{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1} {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}
}; };
int mi = 0; int_t mi = 0;
for(int k = 1; k < 6; k++) { for(int_t k = 1; k < 6; k++) {
if(faces[k] < faces[mi]) mi = k; if(faces[k] < faces[mi]) mi = k;
} }
*outDepth = sr + faces[mi]; *outDepth = sr + faces[mi];
@@ -107,7 +107,7 @@ bool physicsTestSphereVsAabb(
return true; return true;
} }
bool physicsTestSphereVsPlane( bool_t physicsTestSphereVsPlane(
const vec3 sc, const float_t sr, const vec3 sc, const float_t sr,
const vec3 pn, const float_t pd, const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -119,7 +119,7 @@ bool physicsTestSphereVsPlane(
return true; return true;
} }
bool physicsTestAabbVsPlane( bool_t physicsTestAabbVsPlane(
const vec3 ac, const vec3 ah, const vec3 ac, const vec3 ah,
const vec3 pn, const float_t pd, const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -189,7 +189,7 @@ void physicsTestClosestPointsBetweenSegments(
glm_vec3_lerp((float_t *)a2, (float_t *)b2, s, outP2); glm_vec3_lerp((float_t *)a2, (float_t *)b2, s, outP2);
} }
bool physicsTestCapsuleVsSphere( bool_t physicsTestCapsuleVsSphere(
const vec3 cc, const float_t cr, const float_t chh, const vec3 cc, const float_t cr, const float_t chh,
const vec3 sc, const float_t sr, const vec3 sc, const float_t sr,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -203,7 +203,7 @@ bool physicsTestCapsuleVsSphere(
); );
} }
bool physicsTestCapsuleVsAabb( bool_t physicsTestCapsuleVsAabb(
const vec3 cc, const float_t cr, const float_t chh, const vec3 cc, const float_t cr, const float_t chh,
const vec3 ac, const vec3 ah, const vec3 ac, const vec3 ah,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -217,7 +217,7 @@ bool physicsTestCapsuleVsAabb(
); );
} }
bool physicsTestCapsuleVsPlane( bool_t physicsTestCapsuleVsPlane(
const vec3 cc, const float_t cr, const float_t chh, const vec3 cc, const float_t cr, const float_t chh,
const vec3 pn, const float_t pd, const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -233,7 +233,7 @@ bool physicsTestCapsuleVsPlane(
return true; return true;
} }
bool physicsTestCapsuleVsCapsule( bool_t physicsTestCapsuleVsCapsule(
const vec3 c1, const float_t r1, const float_t hh1, const vec3 c1, const float_t r1, const float_t hh1,
const vec3 c2, const float_t r2, const float_t hh2, const vec3 c2, const float_t r2, const float_t hh2,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -247,7 +247,7 @@ bool physicsTestCapsuleVsCapsule(
return physicsTestSphereVsSphere(p1, r1, p2, r2, outNormal, outDepth); return physicsTestSphereVsSphere(p1, r1, p2, r2, outNormal, outDepth);
} }
bool physicsTestDispatch( bool_t physicsTestDispatch(
const vec3 aPos, const physicsshape_t aShape, const vec3 aPos, const physicsshape_t aShape,
const vec3 bPos, const physicsshape_t bShape, const vec3 bPos, const physicsshape_t bShape,
vec3 outNormal, float_t *outDepth vec3 outNormal, float_t *outDepth
@@ -258,7 +258,7 @@ bool physicsTestDispatch(
if(tb == PHYSICS_SHAPE_PLANE) { if(tb == PHYSICS_SHAPE_PLANE) {
const float_t *pn = bShape.data.plane.normal; const float_t *pn = bShape.data.plane.normal;
const float_t pd = bShape.data.plane.distance; const float_t pd = bShape.data.plane.distance;
switch (ta) { switch(ta) {
case PHYSICS_SHAPE_CUBE: case PHYSICS_SHAPE_CUBE:
return physicsTestAabbVsPlane( return physicsTestAabbVsPlane(
aPos, aShape.data.cube.halfExtents, aPos, aShape.data.cube.halfExtents,
@@ -291,11 +291,11 @@ bool physicsTestDispatch(
return true; return true;
} }
switch (ta) { switch(ta) {
case PHYSICS_SHAPE_CUBE: { case PHYSICS_SHAPE_CUBE: {
const float_t *ac = aPos; const float_t *ac = aPos;
const float_t *ah = aShape.data.cube.halfExtents; const float_t *ah = aShape.data.cube.halfExtents;
switch (tb) { switch(tb) {
case PHYSICS_SHAPE_CUBE: case PHYSICS_SHAPE_CUBE:
return physicsTestAabbVsAabb( return physicsTestAabbVsAabb(
ac, ah, ac, ah,
@@ -330,7 +330,7 @@ bool physicsTestDispatch(
case PHYSICS_SHAPE_SPHERE: { case PHYSICS_SHAPE_SPHERE: {
const float_t sr = aShape.data.sphere.radius; const float_t sr = aShape.data.sphere.radius;
switch (tb) { switch(tb) {
case PHYSICS_SHAPE_CUBE: case PHYSICS_SHAPE_CUBE:
return physicsTestSphereVsAabb( return physicsTestSphereVsAabb(
aPos, sr, aPos, sr,
@@ -362,7 +362,7 @@ bool physicsTestDispatch(
case PHYSICS_SHAPE_CAPSULE: { case PHYSICS_SHAPE_CAPSULE: {
const float_t cr = aShape.data.capsule.radius; const float_t cr = aShape.data.capsule.radius;
const float_t chh = aShape.data.capsule.halfHeight; const float_t chh = aShape.data.capsule.halfHeight;
switch (tb) { switch(tb) {
case PHYSICS_SHAPE_CUBE: case PHYSICS_SHAPE_CUBE:
return physicsTestCapsuleVsAabb( return physicsTestCapsuleVsAabb(
aPos, cr, chh, aPos, cr, chh,
+1 -1
View File
@@ -44,7 +44,7 @@ void physicsWorldStep(const float_t dt) {
physBodies[i] = entityPhysicsGet(physEnts[i], physComps[i]); physBodies[i] = entityPhysicsGet(physEnts[i], physComps[i]);
} }
/* Phase 1: integrate dynamic bodies (gravity + velocity position). /* Phase 1: integrate dynamic bodies (gravity + velocity -> position).
* Writes directly to pos->position, matrix rebuilt at end. */ * Writes directly to pos->position, matrix rebuilt at end. */
for(entityid_t i = 0; i < physCount; i++) { for(entityid_t i = 0; i < physCount; i++) {
if(!positions[i]) continue; if(!positions[i]) continue;
+2 -2
View File
@@ -8,7 +8,7 @@
#pragma once #pragma once
#include "dusk.h" #include "dusk.h"
/** Format version written into every save file. Increment on breaking change. */ /** Save file format version. Increment on breaking change. */
#define SAVE_FILE_VERSION 1 #define SAVE_FILE_VERSION 1
/** Magic bytes that identify a Dusk save file. */ /** Magic bytes that identify a Dusk save file. */
@@ -25,6 +25,6 @@ typedef struct {
char_t header[SAVE_FILE_HEADER_SIZE]; char_t header[SAVE_FILE_HEADER_SIZE];
/** Format version read from the file; used to branch on older layouts. */ /** Format version read from the file; used to branch on older layouts. */
uint32_t version; uint32_t version;
/** Runtime flag true if this slot was successfully loaded or written. */ /** Runtime flag - true if this slot was successfully loaded or written. */
bool_t exists; bool_t exists;
} savefile_t; } savefile_t;
+18 -6
View File
@@ -98,7 +98,9 @@ errorret_t saveStreamWriteHeaderImpl(
)); ));
uint32_t placeholder = 0; uint32_t placeholder = 0;
errorChain(saveStreamWriteBytesRawImpl(stream, &placeholder, sizeof(uint32_t))); errorChain(saveStreamWriteBytesRawImpl(
stream, &placeholder, sizeof(uint32_t)
));
stream->checksum = cryptCRC32Begin(); stream->checksum = cryptCRC32Begin();
errorOk(); errorOk();
} }
@@ -146,7 +148,9 @@ errorret_t saveStreamReadUInt8Impl(savestream_t *stream, uint8_t *out) {
errorOk(); errorOk();
} }
errorret_t saveStreamWriteUInt8Impl(savestream_t *stream, const uint8_t *input) { errorret_t saveStreamWriteUInt8Impl(
savestream_t *stream, const uint8_t *input
) {
errorChain(saveStreamWriteBytesImpl(stream, input, sizeof(uint8_t))); errorChain(saveStreamWriteBytesImpl(stream, input, sizeof(uint8_t)));
errorOk(); errorOk();
} }
@@ -159,7 +163,9 @@ errorret_t saveStreamReadInt16Impl(savestream_t *stream, int16_t *out) {
errorOk(); errorOk();
} }
errorret_t saveStreamWriteInt16Impl(savestream_t *stream, const int16_t *input) { errorret_t saveStreamWriteInt16Impl(
savestream_t *stream, const int16_t *input
) {
uint16_t raw; uint16_t raw;
memoryCopy(&raw, input, sizeof(int16_t)); memoryCopy(&raw, input, sizeof(int16_t));
raw = endianLittleToHost16(raw); raw = endianLittleToHost16(raw);
@@ -190,7 +196,9 @@ errorret_t saveStreamReadInt32Impl(savestream_t *stream, int32_t *out) {
errorOk(); errorOk();
} }
errorret_t saveStreamWriteInt32Impl(savestream_t *stream, const int32_t *input) { errorret_t saveStreamWriteInt32Impl(
savestream_t *stream, const int32_t *input
) {
uint32_t raw; uint32_t raw;
memoryCopy(&raw, input, sizeof(int32_t)); memoryCopy(&raw, input, sizeof(int32_t));
raw = endianLittleToHost32(raw); raw = endianLittleToHost32(raw);
@@ -221,7 +229,9 @@ errorret_t saveStreamReadInt64Impl(savestream_t *stream, int64_t *out) {
errorOk(); errorOk();
} }
errorret_t saveStreamWriteInt64Impl(savestream_t *stream, const int64_t *input) { errorret_t saveStreamWriteInt64Impl(
savestream_t *stream, const int64_t *input
) {
uint64_t raw; uint64_t raw;
memoryCopy(&raw, input, sizeof(int64_t)); memoryCopy(&raw, input, sizeof(int64_t));
raw = endianLittleToHost64(raw); raw = endianLittleToHost64(raw);
@@ -251,7 +261,9 @@ errorret_t saveStreamReadFloatImpl(savestream_t *stream, float_t *out) {
errorOk(); errorOk();
} }
errorret_t saveStreamWriteFloatImpl(savestream_t *stream, const float_t *input) { errorret_t saveStreamWriteFloatImpl(
savestream_t *stream, const float_t *input
) {
float_t raw = endianLittleToHostFloat(*input); float_t raw = endianLittleToHostFloat(*input);
errorChain(saveStreamWriteBytesImpl(stream, &raw, sizeof(float_t))); errorChain(saveStreamWriteBytesImpl(stream, &raw, sizeof(float_t)));
errorOk(); errorOk();
+6 -7
View File
@@ -1,16 +1,15 @@
# Copyright (c) 2025 Dominic Masters # Copyright (c) 2026 Dominic Masters
# #
# This software is released under the MIT License. # This software is released under the MIT License.
# https://opensource.org/licenses/MIT # https://opensource.org/licenses/MIT
# Sources include(duskjs2c)
dusk_embed_js(${DUSK_LIBRARY_TARGET_NAME}
${CMAKE_CURRENT_SOURCE_DIR}/scene.js
)
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
scene.c scene.c
scenerenderpipeline.c scenerenderpipeline.c
) )
# Subdirectories
add_subdirectory(initial)
add_subdirectory(test)
add_subdirectory(overworld)
-28
View File
@@ -1,28 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "initialscene.h"
#include "console/console.h"
#include "scene/scene.h"
#include "script/script.h"
#include "entity/entitymanager.h"
#include "entity/entity.h"
#include "entity/component/display/entityposition.h"
#include "entity/component/display/entityrenderable.h"
void initialSceneInit(void) {
consolePrint("Initial scene initialized");
errorCatch(errorPrint(scriptExecFile("testentity.js")));
}
errorret_t initialSceneUpdate(void) {
errorOk();
}
void initialSceneDispose(void) {
entityDispose(SCENE.data.initial.cubeEntityId);
}
-18
View File
@@ -1,18 +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 "entity/entitybase.h"
typedef struct {
entityid_t cubeEntityId;
} initialscene_t;
void initialSceneInit(void);
errorret_t initialSceneUpdate(void);
void initialSceneDispose(void);
@@ -1,49 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "overworldground.h"
#include "entity/entitymanager.h"
#include "entity/component/physics/entityphysics.h"
#define OVERWORLD_GROUND_SIZE 20.0f
void overworldGroundAdd(overworldground_t *ground) {
ground->entityId = entityManagerAdd();
ground->posCompId = entityAddComponent(
ground->entityId, COMPONENT_TYPE_POSITION
);
entityAddComponent(ground->entityId, COMPONENT_TYPE_RENDERABLE);
vec3 pos = { -OVERWORLD_GROUND_SIZE, 0.0f, -OVERWORLD_GROUND_SIZE };
vec3 scale = { OVERWORLD_GROUND_SIZE * 2.0f, 1.0f, OVERWORLD_GROUND_SIZE * 2.0f };
entityPositionSetLocalPosition(ground->entityId, ground->posCompId, pos);
entityPositionSetLocalScale(ground->entityId, ground->posCompId, scale);
// Separate physics entity centered on the finite ground area.
// The visual entity's position is its corner {-size, 0, -size}, not its
// center, so a box collider on it would be misplaced. This entity sits at
// the true center {0, -0.5, 0} with halfExtents matching the visual extent.
ground->floorEntityId = entityManagerAdd();
componentid_t floorPosComp = entityAddComponent(
ground->floorEntityId, COMPONENT_TYPE_POSITION
);
componentid_t floorPhysComp = entityAddComponent(
ground->floorEntityId, COMPONENT_TYPE_PHYSICS
);
vec3 floorPos = { 0.0f, -0.5f, 0.0f };
entityPositionSetLocalPosition(ground->floorEntityId, floorPosComp, floorPos);
entityPhysicsSetBodyType(ground->floorEntityId, floorPhysComp, PHYSICS_BODY_STATIC);
physicsshape_t shape = {
.type = PHYSICS_SHAPE_CUBE,
.data.cube = { .halfExtents = {
OVERWORLD_GROUND_SIZE,
0.5f,
OVERWORLD_GROUND_SIZE
}}
};
entityPhysicsSetShape(ground->floorEntityId, floorPhysComp, shape);
}
@@ -1,22 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
typedef struct {
entityid_t entityId;
componentid_t posCompId;
entityid_t floorEntityId;
} overworldground_t;
/**
* Creates the ground entity and adds it to the world.
*
* @param ground The ground state to initialize.
*/
void overworldGroundAdd(overworldground_t *ground);
-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 "overworldnpc.h"
#include "entity/entitymanager.h"
#include "entity/component/physics/entityphysics.h"
#include "entity/component/trigger/entitytrigger.h"
#include "entity/component/overworld/entityoverworld.h"
#include "entity/component/overworld/entityinteractable.h"
void overworldNpcAdd(overworldnpc_t *npc, vec3 position) {
npc->entityId = entityManagerAdd();
npc->posCompId = entityAddComponent(npc->entityId, COMPONENT_TYPE_POSITION);
entityAddComponent(npc->entityId, COMPONENT_TYPE_RENDERABLE);
entityAddComponent(npc->entityId, COMPONENT_TYPE_PHYSICS);
npc->overworldCompId = entityAddComponent(npc->entityId, COMPONENT_TYPE_OVERWORLD);
npc->triggerCompId = entityAddComponent(npc->entityId, COMPONENT_TYPE_TRIGGER);
npc->interactableCompId = entityAddComponent(
npc->entityId, COMPONENT_TYPE_INTERACTABLE
);
entityPositionSetLocalPosition(npc->entityId, npc->posCompId, position);
componentid_t physCompId = entityOverworldGet(npc->entityId, npc->overworldCompId)->physCompId;
entityPhysicsSetBodyType(npc->entityId, physCompId, PHYSICS_BODY_STATIC);
physicsshape_t shape = {
.type = PHYSICS_SHAPE_CAPSULE,
.data.capsule = { .radius = 0.4f, .halfHeight = 0.1f }
};
entityPhysicsSetShape(npc->entityId, physCompId, shape);
vec3 min = {
position[0] - OVERWORLD_NPC_INTERACT_RANGE,
position[1] - OVERWORLD_NPC_INTERACT_RANGE,
position[2] - OVERWORLD_NPC_INTERACT_RANGE
};
vec3 max = {
position[0] + OVERWORLD_NPC_INTERACT_RANGE,
position[1] + OVERWORLD_NPC_INTERACT_RANGE,
position[2] + OVERWORLD_NPC_INTERACT_RANGE
};
entityTriggerSetBounds(npc->entityId, npc->triggerCompId, min, max);
}
-27
View File
@@ -1,27 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#define OVERWORLD_NPC_INTERACT_RANGE 1.5f
typedef struct {
entityid_t entityId;
componentid_t posCompId;
componentid_t overworldCompId;
componentid_t triggerCompId;
componentid_t interactableCompId;
} overworldnpc_t;
/**
* Creates the NPC entity at the given world position.
*
* @param npc The NPC state to initialize.
* @param position World-space position to spawn the NPC at.
*/
void overworldNpcAdd(overworldnpc_t *npc, vec3 position);
@@ -1,38 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "overworldplayer.h"
#include "entity/entitymanager.h"
#include "entity/component/physics/entityphysics.h"
#include "entity/component/overworld/entityoverworld.h"
#include "entity/component/overworld/entityplayer.h"
void overworldPlayerAdd(overworldplayer_t *player) {
player->entityId = entityManagerAdd();
player->posCompId = entityAddComponent(player->entityId, COMPONENT_TYPE_POSITION);
entityAddComponent(player->entityId, COMPONENT_TYPE_RENDERABLE);
entityAddComponent(player->entityId, COMPONENT_TYPE_PHYSICS);
componentid_t owCompId = entityAddComponent(player->entityId, COMPONENT_TYPE_OVERWORLD);
entityOverworldSetType(player->entityId, owCompId, OVERWORLD_ENTITY_TYPE_PLAYER);
player->playerCompId = entityAddComponent(player->entityId, COMPONENT_TYPE_PLAYER);
vec3 pos = { 0.0f, 0.5f, 0.0f };
entityPositionSetLocalPosition(player->entityId, player->posCompId, pos);
componentid_t physCompId = entityOverworldGet(player->entityId, owCompId)->physCompId;
entityPhysicsSetBodyType(player->entityId, physCompId, PHYSICS_BODY_DYNAMIC);
physicsshape_t shape = {
.type = PHYSICS_SHAPE_CAPSULE,
.data.capsule = { .radius = 0.4f, .halfHeight = 0.1f }
};
entityPhysicsSetShape(player->entityId, physCompId, shape);
entityPhysicsGet(player->entityId, physCompId)->gravityScale = 1.0f;
}
void overworldPlayerUpdate(overworldplayer_t *player) {
entityPlayerUpdate(player->entityId, player->playerCompId);
}
@@ -1,29 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
typedef struct {
entityid_t entityId;
componentid_t posCompId;
componentid_t playerCompId;
} overworldplayer_t;
/**
* Creates the player entity and adds it to the world.
*
* @param player The player state to initialize.
*/
void overworldPlayerAdd(overworldplayer_t *player);
/**
* Updates the player entity, reading input and moving on the XZ plane.
*
* @param player The player state to update.
*/
void overworldPlayerUpdate(overworldplayer_t *player);
-173
View File
@@ -1,173 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "overworldscene.h"
#include "overworldplayer.h"
#include "overworldground.h"
#include "overworldnpc.h"
#include "console/console.h"
#include "entity/entitymanager.h"
#include "entity/component/display/entityrenderable.h"
#include "display/shader/shaderlist.h"
#include "entity/component/overworld/entityinteractable.h"
#include "entity/component/overworld/entityoverworldcamera.h"
#include "entity/component/overworld/entityoverworldtrigger.h"
#include "display/mesh/cube.h"
#include "display/mesh/plane.h"
#include "display/displaystate.h"
#include "scene/scene.h"
#include "assert/assert.h"
#define OVERWORLD (SCENE.data.overworld)
static void overworldSceneTestTriggerEnter(
const entityid_t entityId,
const componentid_t componentId,
void *user
) {
consolePrint("Test trigger: player entered");
}
static void overworldSceneTestTriggerExit(
const entityid_t entityId,
const componentid_t componentId,
void *user
) {
consolePrint("Test trigger: player exited");
}
static void overworldSceneNpcInteract(
const entityid_t entityId,
const componentid_t componentId,
void *user
) {
consolePrint("NPC interacted with!");
}
void overworldSceneConfigureShaderMaterial(
const entityid_t entityId,
const color_t color,
mesh_t *mesh
) {
assertNotNull(mesh, "Mesh cannot be null");
componentid_t renderComp = entityGetComponent(
entityId, COMPONENT_TYPE_RENDERABLE
);
entityRenderableSetType(entityId, renderComp, ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL);
entityrenderable_t *r = componentGetData(
entityId, renderComp, COMPONENT_TYPE_RENDERABLE
);
r->data.material.shaderType = SHADER_LIST_SHADER_UNLIT;
r->data.material.material.unlit.color = color;
r->data.material.material.unlit.texture = NULL;
r->data.material.state.flags = DISPLAY_STATE_FLAG_DEPTH_TEST;
r->data.material.meshes[0] = mesh;
r->data.material.meshOffsets[0] = 0;
r->data.material.meshCounts[0] = -1;
r->data.material.meshCount = 1;
}
void overworldSceneConfigureSprite(
const entityid_t entityId,
const color_t color,
texture_t *texture
) {
componentid_t renderComp = entityGetComponent(
entityId, COMPONENT_TYPE_RENDERABLE
);
entityRenderableSetType(entityId, renderComp, ENTITY_RENDERABLE_TYPE_SPRITEBATCH);
entityrenderable_t *r = componentGetData(
entityId, renderComp, COMPONENT_TYPE_RENDERABLE
);
r->data.spritebatch.texture = texture;
r->data.spritebatch.spriteCount = 1;
r->data.spritebatch.sprites[0].min[0] = -0.5f;
r->data.spritebatch.sprites[0].min[1] = -0.0f;
r->data.spritebatch.sprites[0].min[2] = -0.5f;
r->data.spritebatch.sprites[0].max[0] = 0.5f;
r->data.spritebatch.sprites[0].max[1] = 0.0f;
r->data.spritebatch.sprites[0].max[2] = 0.5f;
r->data.spritebatch.sprites[0].uvMin[0] = 0.0f;
r->data.spritebatch.sprites[0].uvMin[1] = 0.0f;
r->data.spritebatch.sprites[0].uvMax[0] = 1.0f;
r->data.spritebatch.sprites[0].uvMax[1] = 1.0f;
}
void overworldSceneInit(void) {
consolePrint("Overworld scene initialized");
overworldGroundAdd(&OVERWORLD.ground);
overworldSceneConfigureShaderMaterial(
OVERWORLD.ground.entityId, COLOR_MAGENTA, &PLANE_MESH_SIMPLE
);
overworldPlayerAdd(&OVERWORLD.player);
overworldSceneConfigureSprite(OVERWORLD.player.entityId, COLOR_GREEN, NULL);
vec3 npcPos = { 3.0f, 0.5f, 3.0f };
overworldNpcAdd(&OVERWORLD.npc, npcPos);
overworldSceneConfigureSprite(OVERWORLD.npc.entityId, COLOR_BLUE, NULL);
OVERWORLD.cameraEntityId = entityManagerAdd();
entityAddComponent(OVERWORLD.cameraEntityId, COMPONENT_TYPE_POSITION);
entityAddComponent(OVERWORLD.cameraEntityId, COMPONENT_TYPE_CAMERA);
OVERWORLD.cameraOverworldCompId = entityAddComponent(
OVERWORLD.cameraEntityId, COMPONENT_TYPE_OVERWORLD_CAMERA
);
entityOverworldCameraSetTarget(
OVERWORLD.cameraEntityId, OVERWORLD.cameraOverworldCompId,
OVERWORLD.player.entityId, OVERWORLD.player.posCompId
);
entityoverworldcamera_t *camData = entityOverworldCameraGet(
OVERWORLD.cameraEntityId, OVERWORLD.cameraOverworldCompId
);
glm_vec3_zero(camData->targetOffset);
glm_vec3_copy((vec3){ 0.0f, 0.0f, 5.0f }, camData->eyeOffset);
camData->scale = 32.0f;
entityInteractableSetCallback(
OVERWORLD.npc.entityId, OVERWORLD.npc.interactableCompId,
overworldSceneNpcInteract, NULL
);
OVERWORLD.testTriggerId = entityManagerAdd();
OVERWORLD.testTriggerCompId = entityAddComponent(
OVERWORLD.testTriggerId, COMPONENT_TYPE_OVERWORLD_TRIGGER
);
entityOverworldTriggerSetBounds(
OVERWORLD.testTriggerId, OVERWORLD.testTriggerCompId,
(vec3){ -2.0f, -1.0f, -2.0f },
(vec3){ 2.0f, 1.0f, 2.0f }
);
entityoverworldtrigger_t *testTrigger = entityOverworldTriggerGet(
OVERWORLD.testTriggerId, OVERWORLD.testTriggerCompId
);
testTrigger->onEnter = overworldSceneTestTriggerEnter;
testTrigger->onExit = overworldSceneTestTriggerExit;
}
errorret_t overworldSceneUpdate(void) {
overworldPlayerUpdate(&OVERWORLD.player);
errorOk();
}
void overworldSceneDispose(void) {
OVERWORLD.cameraEntityId = ENTITY_ID_INVALID;
OVERWORLD.cameraOverworldCompId = COMPONENT_ID_INVALID;
OVERWORLD.ground.entityId = ENTITY_ID_INVALID;
OVERWORLD.ground.posCompId = COMPONENT_ID_INVALID;
OVERWORLD.ground.floorEntityId = ENTITY_ID_INVALID;
OVERWORLD.player.entityId = ENTITY_ID_INVALID;
OVERWORLD.player.posCompId = COMPONENT_ID_INVALID;
OVERWORLD.npc.entityId = ENTITY_ID_INVALID;
OVERWORLD.npc.posCompId = COMPONENT_ID_INVALID;
OVERWORLD.npc.overworldCompId = COMPONENT_ID_INVALID;
OVERWORLD.npc.triggerCompId = COMPONENT_ID_INVALID;
OVERWORLD.npc.interactableCompId = COMPONENT_ID_INVALID;
}
-72
View File
@@ -1,72 +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 "entity/entitybase.h"
#include "display/color.h"
#include "display/mesh/mesh.h"
#include "display/texture/texture.h"
#include "scene/overworld/overworldplayer.h"
#include "scene/overworld/overworldground.h"
#include "scene/overworld/overworldnpc.h"
typedef struct {
entityid_t cameraEntityId;
componentid_t cameraOverworldCompId;
overworldplayer_t player;
overworldground_t ground;
overworldnpc_t npc;
entityid_t testTriggerId;
componentid_t testTriggerCompId;
} overworldscene_t;
/**
* Configures a SHADER_MATERIAL renderable on an entity with the unlit shader,
* depth testing enabled, no blending, and a single mesh.
*
* @param entityId The entity to configure.
* @param color Unlit diffuse color.
* @param mesh Mesh to render.
*/
void overworldSceneConfigureShaderMaterial(
const entityid_t entityId,
const color_t color,
mesh_t *mesh
);
/**
* Configures a SPRITEBATCH renderable on an entity as a single 1x1 billboard
* sprite centered at the entity's origin.
*
* @param entityId The entity to configure.
* @param color Per-vertex sprite tint color.
* @param texture Texture to use, or NULL for untextured.
*/
void overworldSceneConfigureSprite(
const entityid_t entityId,
const color_t color,
texture_t *texture
);
/**
* Initializes the overworld scene, spawning all entities and configuring
* the camera, player, ground, and NPC.
*/
void overworldSceneInit(void);
/**
* Updates the overworld scene each frame.
*
* @return Error state.
*/
errorret_t overworldSceneUpdate(void);
/**
* Disposes the overworld scene, invalidating all entity and component IDs.
*/
void overworldSceneDispose(void);
+14 -52
View File
@@ -6,65 +6,41 @@
#include "scene.h" #include "scene.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "log/log.h"
#include "time/time.h" #include "time/time.h"
#include "display/screen/screen.h" #include "display/screen/screen.h"
#include "entity/entitymanager.h" #include "entity/entitymanager.h"
#include "display/shader/shaderunlit.h" #include "display/shader/shaderunlit.h"
#include "display/display.h" #include "display/display.h"
#include "console/console.h"
#include "util/string.h"
#include "ui/ui.h" #include "ui/ui.h"
#include "scene/scenerenderpipeline.h" #include "scene/scenerenderpipeline.h"
#include "entity/component.h" #include "entity/component.h"
#include "asset/asset.h"
scenefuncs_t SCENE_FUNCTIONS[SCENE_TYPE_COUNT] = { #include "asset/loader/assetloader.h"
{ 0 }, #include "script/module/modulebase.h"
#define X(structName, varName, varNameUpper, initFunc, updateFunc, disposeFunc) \ #include "console/console.h"
{ initFunc, updateFunc, disposeFunc }, #include "script/script.h"
#include "scene/scenelist.h" #include "scene_js.h"
#undef X
};
scene_t SCENE; scene_t SCENE;
errorret_t sceneInit(void) { errorret_t sceneInit(void) {
memoryZero(&SCENE, sizeof(scene_t)); memoryZero(&SCENE, sizeof(scene_t));
errorChain(scriptExecString(SCENE_JS));
errorOk(); errorOk();
} }
errorret_t sceneUpdate(void) { errorret_t sceneUpdate(void) {
// Handle scene change
if(SCENE.nextType != SCENE_TYPE_NULL) {
// Dispose current scene.
if(SCENE.type != SCENE_TYPE_NULL) {
if(SCENE_FUNCTIONS[SCENE.type].dispose) {
SCENE_FUNCTIONS[SCENE.type].dispose();
}
}
// Init new scene
SCENE.type = SCENE.nextType;
SCENE.nextType = SCENE_TYPE_NULL;
if(SCENE.type != SCENE_TYPE_NULL) {
if(SCENE_FUNCTIONS[SCENE.type].init) {
SCENE_FUNCTIONS[SCENE.type].init();
}
}
}
// Update scene
#ifdef DUSK_TIME_DYNAMIC #ifdef DUSK_TIME_DYNAMIC
if(TIME.dynamicUpdate) { if(TIME.dynamicUpdate) {
errorOk(); errorChain(scriptExecString("Scene.dynamicUpdate();"));
} else {
errorChain(scriptExecString("Scene.update();"));
} }
#else
errorChain(scriptExecString("Scene.update();"));
errorChain(scriptExecString("Scene.dynamicUpdate();"));
#endif #endif
if(SCENE.type != SCENE_TYPE_NULL && SCENE_FUNCTIONS[SCENE.type].update) {
errorChain(SCENE_FUNCTIONS[SCENE.type].update());
}
errorOk(); errorOk();
} }
@@ -103,21 +79,7 @@ errorret_t sceneRender(void) {
errorOk(); errorOk();
} }
void sceneSet(const scenetype_t type) {
assertTrue(
type > SCENE_TYPE_NULL && type < SCENE_TYPE_COUNT,
"Invalid scene type"
);
SCENE.nextType = type;
}
errorret_t sceneDispose(void) { errorret_t sceneDispose(void) {
if(SCENE.type != SCENE_TYPE_NULL) { errorChain(scriptExecString("Scene.dispose();"));
if(SCENE_FUNCTIONS[SCENE.type].dispose) {
SCENE_FUNCTIONS[SCENE.type].dispose();
}
}
SCENE.type = SCENE_TYPE_NULL;
SCENE.nextType = SCENE_TYPE_NULL;
errorOk(); errorOk();
} }
+11 -47
View File
@@ -6,75 +6,39 @@
*/ */
#pragma once #pragma once
#include "asset/assetfile.h" #include "error/error.h"
#include "scene/initial/initialscene.h"
#include "scene/test/testscene.h"
#include "scene/overworld/overworldscene.h"
#define SCENE_EVENT_UPDATE_MAX 16
typedef enum {
SCENE_TYPE_NULL,
#define X(structName, varName, varNameUpper, initFunc, updateFunc, disposeFunc) \
SCENE_TYPE_##varNameUpper,
#include "scene/scenelist.h"
#undef X
SCENE_TYPE_COUNT
} scenetype_t;
typedef union {
#define X(structName, varName, varNameUpper, initFunc, updateFunc, disposeFunc) \
structName varName;
#include "scene/scenelist.h"
#undef X
} scenedata_t;
typedef struct { typedef struct {
void (*init)(void); void *nothing;
errorret_t (*update)(void);
void (*dispose)(void);
} scenefuncs_t;
typedef struct {
scenedata_t data;
scenetype_t type;
scenetype_t nextType;
} scene_t; } scene_t;
extern scenefuncs_t SCENE_FUNCTIONS[SCENE_TYPE_COUNT];
extern scene_t SCENE; extern scene_t SCENE;
/** /**
* Initializes the scene manager. * Initialises the scene manager.
* *
* @return Any error state that happened. * @return An error if the init failed, or errorOk() if it succeeded.
*/ */
errorret_t sceneInit(void); errorret_t sceneInit(void);
/** /**
* Ticks the scene manager; may call the scene's update method. * Ticks the scene manager. Processes any pending scene transition, then
* calls scriptSceneUpdate on the active scene.
* *
* @return Any error state that happened. * @return An error if the update failed, or errorOk() if it succeeded.
*/ */
errorret_t sceneUpdate(void); errorret_t sceneUpdate(void);
/** /**
* Renders the scene. * Renders the current scene (entities, render pipeline, UI).
* *
* @return Any error state that happened. * @return An error if the render failed, or errorOk() if it succeeded.
*/ */
errorret_t sceneRender(void); errorret_t sceneRender(void);
/** /**
* Requests a scene change on the next safe opportunity. * Disposes the active scene immediately.
* *
* @param type The type of scene to change to. * @return An error if the dispose failed, or errorOk() if it succeeded.
*/
void sceneSet(const scenetype_t type);
/**
* Disposes of the current scene.
*
* @return Any error state that happened.
*/ */
errorret_t sceneDispose(void); errorret_t sceneDispose(void);
+40
View File
@@ -0,0 +1,40 @@
// Copyright (c) 2026 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var Scene = {
};
Scene.update = () => {
if(!Scene.current || !Scene.current.update) return;
Scene.current.update();
}
Scene.dynamicUpdate = () => {
if(!Scene.current || !Scene.current.dynamicUpdate) return;
Scene.current.dynamicUpdate();
}
Scene.set = (newScene) => {
// Current scene active?
if(Scene.current && Scene.current.dispose) {
Scene.current.dispose();
}
// Set new scene
Scene.current = newScene;
if(!newScene) return;
// Init
if(newScene.init) {
newScene.init();
}
};
Scene.dispose = () => {
if(Scene.current && Scene.current.dispose) {
Scene.current.dispose();
}
Scene.current = null;
}
-15
View File
@@ -1,15 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#ifndef X
#define X(structName, varName, varNameUpper, initFunc, updateFunc, disposeFunc) \
((void))
#endif
X(initialscene_t, initial, INITIAL, initialSceneInit, initialSceneUpdate, initialSceneDispose)
X(testscene_t, test, TEST, testSceneInit, testSceneUpdate, testSceneDispose)
X(overworldscene_t, overworld, OVERWORLD, overworldSceneInit, overworldSceneUpdate, overworldSceneDispose)

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