Compare commits
46 Commits
f841a35a53
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 5a08384ae1 | |||
| 45d8fda0e4 | |||
| a9e664492f | |||
| 3c8b6cb2cc | |||
| 2b3abbe13b | |||
| 241a52b94a | |||
| 82c300b077 | |||
| 0f8b629e20 | |||
| 36f6ac65f2 | |||
| a25871a849 | |||
| 57766a9104 | |||
| 3770ae1645 | |||
| d73edb403f | |||
| b14196ff0d | |||
| 88903fee94 | |||
| 1e8311fc04 | |||
| 2b78370cb8 | |||
| 8f78bba9e9 | |||
| 41a4be678e | |||
| 8b2b4b7c3d | |||
| 1f3a29f89d | |||
| c4c93097cd | |||
| eedb7769e6 | |||
| 98db62a4bc | |||
| df48c8e500 | |||
| db9cc0f4c6 | |||
| a79ee429b4 | |||
| 6acfca6d48 | |||
| 1cd6f4cb72 | |||
| 3271e8c7d6 | |||
| 0bcde064af | |||
| 957980b3c5 | |||
| 03eb328d81 | |||
| e1716a741f | |||
| e24707c847 | |||
| 7c4b8c307f | |||
| 109318aeaf | |||
| 1f2657cea0 | |||
| 382c435bac | |||
| 130fe4ca5d | |||
| 31ba3fe127 | |||
| f68b31158f | |||
| 653ca9a72d | |||
| ba7857f4df | |||
| 23e617ea21 | |||
| cdf5a5229c |
@@ -144,7 +144,7 @@ jobs:
|
|||||||
- name: Copy output files.
|
- name: Copy output files.
|
||||||
run: |
|
run: |
|
||||||
mkdir -p ./git-artifcats/Dusk/apps/Dusk
|
mkdir -p ./git-artifcats/Dusk/apps/Dusk
|
||||||
cp build-wii/Dusk.dol ./git-artifcats/Dusk/apps/Dusk/boot.dol
|
cp build-wii/boot.dol ./git-artifcats/Dusk/apps/Dusk/boot.dol
|
||||||
cp build-wii/dusk.dsk ./git-artifcats/Dusk/apps/Dusk/dusk.dsk
|
cp build-wii/dusk.dsk ./git-artifcats/Dusk/apps/Dusk/dusk.dsk
|
||||||
cp build-wii/meta.xml ./git-artifcats/Dusk/apps/Dusk/meta.xml
|
cp build-wii/meta.xml ./git-artifcats/Dusk/apps/Dusk/meta.xml
|
||||||
- name: Upload Wii binary
|
- name: Upload Wii binary
|
||||||
|
|||||||
+2
-1
@@ -105,4 +105,5 @@ yarn.lock
|
|||||||
/build2
|
/build2
|
||||||
/build*
|
/build*
|
||||||
/assets/test
|
/assets/test
|
||||||
/tools_old
|
/tools_old
|
||||||
|
/assets/test.png
|
||||||
@@ -76,6 +76,10 @@ else()
|
|||||||
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
if(NOT DEFINED DUSK_VERSION)
|
||||||
|
string(TIMESTAMP DUSK_VERSION "debug-%y%m%d%H%M%S")
|
||||||
|
endif()
|
||||||
|
|
||||||
# Definitions
|
# Definitions
|
||||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
|
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
@@ -84,6 +88,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
|
|||||||
DUSK_GAME_AUTHOR="${DUSK_GAME_AUTHOR}"
|
DUSK_GAME_AUTHOR="${DUSK_GAME_AUTHOR}"
|
||||||
DUSK_GAME_SHORT_DESCRIPTION="${DUSK_GAME_SHORT_DESCRIPTION}"
|
DUSK_GAME_SHORT_DESCRIPTION="${DUSK_GAME_SHORT_DESCRIPTION}"
|
||||||
DUSK_GAME_LONG_DESCRIPTION="${DUSK_GAME_LONG_DESCRIPTION}"
|
DUSK_GAME_LONG_DESCRIPTION="${DUSK_GAME_LONG_DESCRIPTION}"
|
||||||
|
DUSK_VERSION="${DUSK_VERSION}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Toolchains
|
# Toolchains
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
|
|
||||||
function MoveCubeCutscene(params) {
|
|
||||||
Cutscene.call(this);
|
|
||||||
this.cube = params.cube;
|
|
||||||
|
|
||||||
var SPEED = 3.0;
|
|
||||||
var DURATION = 2.0;
|
|
||||||
|
|
||||||
this.anim = new Animation([
|
|
||||||
[
|
|
||||||
{ time: 0.0, value: 0, easing: Easing.inOutQuad },
|
|
||||||
{ time: DURATION, value: -(SPEED * DURATION), easing: Easing.inOutQuad },
|
|
||||||
{ time: DURATION * 2, value: 0 }
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
this.anim.onComplete = function() {
|
|
||||||
Cutscene.finish();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
MoveCubeCutscene.prototype = Object.create(Cutscene.prototype);
|
|
||||||
MoveCubeCutscene.prototype.constructor = MoveCubeCutscene;
|
|
||||||
|
|
||||||
MoveCubeCutscene.prototype.update = function() {
|
|
||||||
this.anim.update(TIME.delta);
|
|
||||||
this.cube.position.position.x = this.anim.properties[0].value;
|
|
||||||
};
|
|
||||||
|
|
||||||
module = MoveCubeCutscene;
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
var OverworldEntity = include('entities/OverworldEntity.js');
|
|
||||||
|
|
||||||
function CubeEntity() {
|
|
||||||
OverworldEntity.call(this);
|
|
||||||
|
|
||||||
this.add(RENDERABLE);
|
|
||||||
|
|
||||||
this.cubeMesh = Mesh.createCube();
|
|
||||||
this.renderable.mesh = this.cubeMesh;
|
|
||||||
}
|
|
||||||
|
|
||||||
CubeEntity.prototype = Object.create(OverworldEntity.prototype);
|
|
||||||
CubeEntity.prototype.constructor = CubeEntity;
|
|
||||||
|
|
||||||
CubeEntity.prototype.update = function() {
|
|
||||||
OverworldEntity.prototype.update.call(this);
|
|
||||||
var speed = 5.0;
|
|
||||||
var move = Input.axis2D(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT, INPUT_ACTION_UP, INPUT_ACTION_DOWN);
|
|
||||||
this.position.position.x += move.x * speed * TIME.delta;
|
|
||||||
this.position.position.z += move.y * speed * TIME.delta;
|
|
||||||
this.renderable.color = Color.rainbow();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = CubeEntity;
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
function OverworldEntity() {
|
|
||||||
Entity.call(this);
|
|
||||||
|
|
||||||
this.add(POSITION);
|
|
||||||
}
|
|
||||||
|
|
||||||
OverworldEntity.prototype = Object.create(Entity.prototype);
|
|
||||||
OverworldEntity.prototype.constructor = OverworldEntity;
|
|
||||||
|
|
||||||
OverworldEntity.prototype.update = function() {
|
|
||||||
// var speed = 3.0;
|
|
||||||
// var move = Input.axis2D(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT, INPUT_ACTION_UP, INPUT_ACTION_DOWN);
|
|
||||||
// this.position.position.x += move.x * speed * TIME.delta;
|
|
||||||
// this.position.position.z += move.y * speed * TIME.delta;
|
|
||||||
}
|
|
||||||
|
|
||||||
OverworldEntity.prototype.dispose = function() {
|
|
||||||
Entity.prototype.dispose.call(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
module = OverworldEntity;
|
|
||||||
+24
-88
@@ -1,93 +1,29 @@
|
|||||||
Console.visible = true;
|
|
||||||
|
|
||||||
// Default input bindings.
|
|
||||||
if (typeof PSP !== 'undefined') {
|
|
||||||
Input.bind("up", INPUT_ACTION_UP);
|
|
||||||
Input.bind("down", INPUT_ACTION_DOWN);
|
|
||||||
Input.bind("left", INPUT_ACTION_LEFT);
|
|
||||||
Input.bind("right", INPUT_ACTION_RIGHT);
|
|
||||||
Input.bind("accept", INPUT_ACTION_ACCEPT);
|
|
||||||
Input.bind("cancel", INPUT_ACTION_CANCEL);
|
|
||||||
Input.bind("select", INPUT_ACTION_RAGEQUIT);
|
|
||||||
Input.bind("lstick_up", INPUT_ACTION_UP);
|
|
||||||
Input.bind("lstick_down", INPUT_ACTION_DOWN);
|
|
||||||
Input.bind("lstick_left", INPUT_ACTION_LEFT);
|
|
||||||
Input.bind("lstick_right", INPUT_ACTION_RIGHT);
|
|
||||||
Input.bind("triangle", INPUT_ACTION_CONSOLE);
|
|
||||||
|
|
||||||
} else if (typeof DOLPHIN !== 'undefined') {
|
const platformNames = {
|
||||||
Input.bind("up", INPUT_ACTION_UP);
|
[System.PLATFORM_LINUX]: 'Linux',
|
||||||
Input.bind("down", INPUT_ACTION_DOWN);
|
[System.PLATFORM_KNULLI]: 'Knulli',
|
||||||
Input.bind("left", INPUT_ACTION_LEFT);
|
[System.PLATFORM_PSP]: 'PSP',
|
||||||
Input.bind("right", INPUT_ACTION_RIGHT);
|
[System.PLATFORM_GAMECUBE]: 'GameCube',
|
||||||
Input.bind("b", INPUT_ACTION_CANCEL);
|
[System.PLATFORM_WII]: 'Wii',
|
||||||
Input.bind("a", INPUT_ACTION_ACCEPT);
|
};
|
||||||
Input.bind("z", INPUT_ACTION_CONSOLE);
|
|
||||||
Input.bind("lstick_up", INPUT_ACTION_UP);
|
|
||||||
Input.bind("lstick_down", INPUT_ACTION_DOWN);
|
|
||||||
Input.bind("lstick_left", INPUT_ACTION_LEFT);
|
|
||||||
Input.bind("lstick_right", INPUT_ACTION_RIGHT);
|
|
||||||
|
|
||||||
} else if (typeof LINUX !== 'undefined') {
|
Console.print('Platform: ' + (platformNames[System.platform] || 'Unknown'));
|
||||||
if (typeof INPUT_KEYBOARD !== 'undefined') {
|
|
||||||
Input.bind("w", INPUT_ACTION_UP);
|
|
||||||
Input.bind("s", INPUT_ACTION_DOWN);
|
|
||||||
Input.bind("a", INPUT_ACTION_LEFT);
|
|
||||||
Input.bind("d", INPUT_ACTION_RIGHT);
|
|
||||||
|
|
||||||
Input.bind("left", INPUT_ACTION_LEFT);
|
const test = require('test.js');
|
||||||
Input.bind("right", INPUT_ACTION_RIGHT);
|
Console.print(test.str());
|
||||||
Input.bind("up", INPUT_ACTION_UP);
|
test.increment();
|
||||||
Input.bind("down", INPUT_ACTION_DOWN);
|
Console.print(test.str());
|
||||||
|
test.decrement();
|
||||||
|
Console.print(test.str());
|
||||||
|
|
||||||
Input.bind("enter", INPUT_ACTION_ACCEPT);
|
// Scene.set('testscene.js');
|
||||||
Input.bind("e", INPUT_ACTION_ACCEPT);
|
// Console.print('Loading scene...');
|
||||||
|
// requireAsync('./testscene.js', function(scene) {
|
||||||
Input.bind("q", INPUT_ACTION_CANCEL);
|
// throw "test";
|
||||||
|
// Console.print('Initializing scene...');
|
||||||
Input.bind("escape", INPUT_ACTION_RAGEQUIT);
|
// var batch = scene.load();
|
||||||
Input.bind("`", INPUT_ACTION_CONSOLE);
|
// batch.lock();
|
||||||
}
|
// batch.requireLoaded();
|
||||||
|
// scene.init();
|
||||||
if (typeof INPUT_GAMEPAD !== 'undefined') {
|
// });
|
||||||
Input.bind("gamepad_up", INPUT_ACTION_UP);
|
|
||||||
Input.bind("gamepad_down", INPUT_ACTION_DOWN);
|
|
||||||
Input.bind("gamepad_left", INPUT_ACTION_LEFT);
|
|
||||||
Input.bind("gamepad_right", INPUT_ACTION_RIGHT);
|
|
||||||
|
|
||||||
Input.bind("gamepad_a", INPUT_ACTION_ACCEPT);
|
|
||||||
Input.bind("gamepad_b", INPUT_ACTION_CANCEL);
|
|
||||||
Input.bind("gamepad_back", INPUT_ACTION_RAGEQUIT);
|
|
||||||
|
|
||||||
Input.bind("gamepad_lstick_up", INPUT_ACTION_UP);
|
|
||||||
Input.bind("gamepad_lstick_down", INPUT_ACTION_DOWN);
|
|
||||||
Input.bind("gamepad_lstick_left", INPUT_ACTION_LEFT);
|
|
||||||
Input.bind("gamepad_lstick_right", INPUT_ACTION_RIGHT);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof INPUT_POINTER !== 'undefined') {
|
|
||||||
Input.bind("mouse_x", INPUT_ACTION_POINTERX);
|
|
||||||
Input.bind("mouse_y", INPUT_ACTION_POINTERY);
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
print("Unknown platform, no default input bindings set.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Scene.set('scenes/cube.js');
|
|
||||||
|
|
||||||
// Console.print("Testing save stuff;");
|
|
||||||
// Console.print("Save Count: " + Save.count);
|
|
||||||
// Console.print("Save 0 exists? " + Save.exists(0));
|
|
||||||
// try {
|
|
||||||
// Save.load(0);
|
|
||||||
// Console.print("Successfully loaded save 0.");
|
|
||||||
// } catch (e) {
|
|
||||||
// Console.print("Error loading save 0: " + e);
|
|
||||||
// Save.delete(0);
|
|
||||||
// }
|
|
||||||
// Console.print("Save 0 exists? " + Save.exists(0));
|
|
||||||
// Console.print("Writing...");
|
|
||||||
// Save.write(0);
|
|
||||||
// Console.print("Save 0 exists? " + Save.exists(0));
|
|
||||||
// Console.print("Save 0 data: " + Save.load(0));
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function TestChunkN100(x, y, z) {
|
|
||||||
MapChunk.call(this, x, y, z);
|
|
||||||
|
|
||||||
this.cube = new CubeEntity();
|
|
||||||
this.cube.position.position = new Vec3(-16, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestChunkN100.prototype = Object.create(MapChunk.prototype);
|
|
||||||
TestChunkN100.prototype.constructor = TestChunkN100;
|
|
||||||
|
|
||||||
TestChunkN100.prototype.dispose = function() {
|
|
||||||
this.cube.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestChunkN100;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function TestChunk000(x, y, z) {
|
|
||||||
MapChunk.call(this, x, y, z);
|
|
||||||
|
|
||||||
this.cube = new CubeEntity();
|
|
||||||
this.cube.position.position = new Vec3(0, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestChunk000.prototype = Object.create(MapChunk.prototype);
|
|
||||||
TestChunk000.prototype.constructor = TestChunk000;
|
|
||||||
|
|
||||||
TestChunk000.prototype.dispose = function() {
|
|
||||||
this.cube.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestChunk000;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function TestChunk001(x, y, z) {
|
|
||||||
MapChunk.call(this, x, y, z);
|
|
||||||
|
|
||||||
this.cube = new CubeEntity();
|
|
||||||
this.cube.position.position = new Vec3(0, 0, 16);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestChunk001.prototype = Object.create(MapChunk.prototype);
|
|
||||||
TestChunk001.prototype.constructor = TestChunk001;
|
|
||||||
|
|
||||||
TestChunk001.prototype.dispose = function() {
|
|
||||||
this.cube.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestChunk001;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function TestChunk010(x, y, z) {
|
|
||||||
MapChunk.call(this, x, y, z);
|
|
||||||
|
|
||||||
this.cube = new CubeEntity();
|
|
||||||
this.cube.position.position = new Vec3(0, 16, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestChunk010.prototype = Object.create(MapChunk.prototype);
|
|
||||||
TestChunk010.prototype.constructor = TestChunk010;
|
|
||||||
|
|
||||||
TestChunk010.prototype.dispose = function() {
|
|
||||||
this.cube.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestChunk010;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function TestChunk100(x, y, z) {
|
|
||||||
MapChunk.call(this, x, y, z);
|
|
||||||
|
|
||||||
this.cube = new CubeEntity();
|
|
||||||
this.cube.position.position = new Vec3(16, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestChunk100.prototype = Object.create(MapChunk.prototype);
|
|
||||||
TestChunk100.prototype.constructor = TestChunk100;
|
|
||||||
|
|
||||||
TestChunk100.prototype.dispose = function() {
|
|
||||||
this.cube.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestChunk100;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function TestChunk200(x, y, z) {
|
|
||||||
MapChunk.call(this, x, y, z);
|
|
||||||
|
|
||||||
this.cube = new CubeEntity();
|
|
||||||
this.cube.position.position = new Vec3(32, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestChunk200.prototype = Object.create(MapChunk.prototype);
|
|
||||||
TestChunk200.prototype.constructor = TestChunk200;
|
|
||||||
|
|
||||||
TestChunk200.prototype.dispose = function() {
|
|
||||||
this.cube.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestChunk200;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function TestChunk300(x, y, z) {
|
|
||||||
MapChunk.call(this, x, y, z);
|
|
||||||
|
|
||||||
this.cube = new CubeEntity();
|
|
||||||
this.cube.position.position = new Vec3(48, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestChunk300.prototype = Object.create(MapChunk.prototype);
|
|
||||||
TestChunk300.prototype.constructor = TestChunk300;
|
|
||||||
|
|
||||||
TestChunk300.prototype.dispose = function() {
|
|
||||||
this.cube.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestChunk300;
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
function TestMap() {
|
|
||||||
Map.call(this);
|
|
||||||
|
|
||||||
Map.setChunkSize(16, 16, 16);
|
|
||||||
Map.setPosition(0, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestMap.prototype = Object.create(Map.prototype);
|
|
||||||
TestMap.prototype.constructor = TestMap;
|
|
||||||
|
|
||||||
TestMap.prototype.update = function() {
|
|
||||||
};
|
|
||||||
|
|
||||||
TestMap.prototype.dispose = function() {
|
|
||||||
};
|
|
||||||
|
|
||||||
module = TestMap;
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
var CubeEntity = include('entities/CubeEntity.js');
|
|
||||||
|
|
||||||
function CubeScene() {
|
|
||||||
Map.load('test');
|
|
||||||
|
|
||||||
this.cam = new Entity();
|
|
||||||
this.cam.add(POSITION);
|
|
||||||
this.cam.add(CAMERA);
|
|
||||||
|
|
||||||
this.player = new CubeEntity();
|
|
||||||
this.player.position.position = new Vec3(0, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
CubeScene.prototype = Object.create(Scene.prototype);
|
|
||||||
CubeScene.prototype.constructor = CubeScene;
|
|
||||||
|
|
||||||
CubeScene.prototype.update = function() {
|
|
||||||
this.player.update();
|
|
||||||
|
|
||||||
var pos = this.player.position.position;
|
|
||||||
this.cam.position.position = new Vec3(pos.x, pos.y + 8, pos.z + 8);
|
|
||||||
this.cam.position.lookAt(pos);
|
|
||||||
|
|
||||||
Map.setPosition(Math.floor(pos.x), Math.floor(pos.y), Math.floor(pos.z));
|
|
||||||
};
|
|
||||||
|
|
||||||
CubeScene.prototype.dispose = function() {
|
|
||||||
this.cam.dispose();
|
|
||||||
this.player.dispose();
|
|
||||||
Map.dispose();
|
|
||||||
};
|
|
||||||
|
|
||||||
module = CubeScene;
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
Console.print('test included');
|
||||||
|
|
||||||
|
var x = 1 + 2;
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
str: function() {
|
||||||
|
return x.toString();
|
||||||
|
},
|
||||||
|
increment: function() {
|
||||||
|
x++;
|
||||||
|
},
|
||||||
|
decrement: function() {
|
||||||
|
x--;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
var scene = {
|
||||||
|
'test': 'teststring'
|
||||||
|
};
|
||||||
|
|
||||||
|
var assets = AssetBatch([
|
||||||
|
{ path: 'test.png', type: Asset.TYPE_TEXTURE, format: Texture.FORMAT_RGBA }
|
||||||
|
]);
|
||||||
|
|
||||||
|
var cam;
|
||||||
|
var camPos;
|
||||||
|
var testEntity;
|
||||||
|
var testPos;
|
||||||
|
var testRenderable;
|
||||||
|
var texEntry;
|
||||||
|
|
||||||
|
scene.init = function() {
|
||||||
|
assets.lock();
|
||||||
|
assets.onLoaded[0] = scene.loaded;
|
||||||
|
};
|
||||||
|
|
||||||
|
scene.loaded = function() {
|
||||||
|
texEntry = assets.entry(0);
|
||||||
|
|
||||||
|
// Camera at (3, 3, 3) looking at origin
|
||||||
|
cam = Entity.create();
|
||||||
|
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 with textured quad at origin
|
||||||
|
testEntity = Entity.create();
|
||||||
|
testPos = testEntity.add(Component.POSITION);
|
||||||
|
testRenderable = testEntity.add(Component.RENDERABLE);
|
||||||
|
|
||||||
|
testRenderable.texture = texEntry.texture;
|
||||||
|
testRenderable.sprites = [
|
||||||
|
[0, 0, 1, 1, 0, 1, 1, 0]
|
||||||
|
];
|
||||||
|
testPos.localPosition = new Vec3(0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
scene.dispose = function() {
|
||||||
|
Console.print('Scene Dispose');
|
||||||
|
Entity.dispose(cam);
|
||||||
|
Entity.dispose(testEntity);
|
||||||
|
assets.unlock();
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = scene;
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# Copyright (c) 2026 Dominic Masters
|
||||||
|
#
|
||||||
|
# This software is released under the MIT License.
|
||||||
|
# https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
|
# Turn things off we don't need
|
||||||
|
set(JERRY_CMDLINE OFF CACHE BOOL "" FORCE)
|
||||||
|
set(JERRY_EXT ON CACHE BOOL "" FORCE)
|
||||||
|
set(JERRY_DEBUGGER OFF CACHE BOOL "" FORCE)
|
||||||
|
set(JERRY_BUILTIN_DATE OFF CACHE BOOL "" FORCE)
|
||||||
|
set(ENABLE_LTO OFF CACHE BOOL "" FORCE)
|
||||||
|
|
||||||
|
# Fetch Jerry
|
||||||
|
include(FetchContent)
|
||||||
|
FetchContent_Declare(
|
||||||
|
jerryscript
|
||||||
|
GIT_REPOSITORY https://git.wish.moe/YourWishes/jerryscript
|
||||||
|
GIT_TAG float32-fix
|
||||||
|
)
|
||||||
|
FetchContent_MakeAvailable(jerryscript)
|
||||||
|
|
||||||
|
# Mark found
|
||||||
|
set(jerryscript_FOUND ON)
|
||||||
|
|
||||||
|
# Define targets
|
||||||
|
if(TARGET jerryscript-core)
|
||||||
|
set(JERRY_CORE_TARGET jerryscript-core)
|
||||||
|
elseif(TARGET jerry-core)
|
||||||
|
set(JERRY_CORE_TARGET jerry-core)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(TARGET jerryscript-ext)
|
||||||
|
set(JERRY_EXT_TARGET jerryscript-ext)
|
||||||
|
elseif(TARGET jerry-ext)
|
||||||
|
set(JERRY_EXT_TARGET jerry-ext)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(TARGET jerryscript-port-default)
|
||||||
|
set(JERRY_PORT_TARGET jerryscript-port-default)
|
||||||
|
elseif(TARGET jerry-port-default)
|
||||||
|
set(JERRY_PORT_TARGET jerry-port-default)
|
||||||
|
elseif(TARGET jerryscript-port)
|
||||||
|
set(JERRY_PORT_TARGET jerryscript-port)
|
||||||
|
elseif(TARGET jerry-port)
|
||||||
|
set(JERRY_PORT_TARGET jerry-port)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT JERRY_CORE_TARGET)
|
||||||
|
message(FATAL_ERROR "JerryScript core target not found")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT JERRY_EXT_TARGET)
|
||||||
|
message(FATAL_ERROR "JerryScript ext target not found")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(NOT JERRY_PORT_TARGET)
|
||||||
|
message(FATAL_ERROR "JerryScript port target not found")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
foreach(tgt IN ITEMS
|
||||||
|
${JERRY_CORE_TARGET}
|
||||||
|
${JERRY_EXT_TARGET}
|
||||||
|
${JERRY_PORT_TARGET}
|
||||||
|
)
|
||||||
|
if(TARGET ${tgt})
|
||||||
|
set_property(TARGET ${tgt} PROPERTY INTERPROCEDURAL_OPTIMIZATION OFF)
|
||||||
|
target_compile_definitions(${JERRY_CORE_TARGET} PRIVATE
|
||||||
|
JERRY_NUMBER_TYPE_FLOAT64=0
|
||||||
|
JERRY_BUILTIN_DATE=0
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
# Export include dirs through the targets
|
||||||
|
target_include_directories(${JERRY_CORE_TARGET} INTERFACE
|
||||||
|
${jerryscript_SOURCE_DIR}/jerry-core/include
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(${JERRY_EXT_TARGET} INTERFACE
|
||||||
|
${jerryscript_SOURCE_DIR}/jerry-ext/include
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(${JERRY_PORT_TARGET} INTERFACE
|
||||||
|
${jerryscript_SOURCE_DIR}/jerry-port/default/include
|
||||||
|
)
|
||||||
|
|
||||||
|
# Suppress JerryScript-only warning
|
||||||
|
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
|
||||||
|
target_compile_options(${JERRY_CORE_TARGET} PRIVATE
|
||||||
|
-Wno-error
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
add_library(jerryscript::core ALIAS ${JERRY_CORE_TARGET})
|
||||||
|
add_library(jerryscript::ext ALIAS ${JERRY_EXT_TARGET})
|
||||||
|
add_library(jerryscript::port ALIAS ${JERRY_PORT_TARGET})
|
||||||
@@ -34,6 +34,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|||||||
DUSK_OPENGL
|
DUSK_OPENGL
|
||||||
DUSK_OPENGL_ES
|
DUSK_OPENGL_ES
|
||||||
DUSK_LINUX
|
DUSK_LINUX
|
||||||
|
DUSK_KNULLI
|
||||||
DUSK_DISPLAY_SIZE_DYNAMIC
|
DUSK_DISPLAY_SIZE_DYNAMIC
|
||||||
DUSK_DISPLAY_WIDTH_DEFAULT=640
|
DUSK_DISPLAY_WIDTH_DEFAULT=640
|
||||||
DUSK_DISPLAY_HEIGHT_DEFAULT=480
|
DUSK_DISPLAY_HEIGHT_DEFAULT=480
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
|||||||
# CURL::libcurl
|
# CURL::libcurl
|
||||||
)
|
)
|
||||||
|
|
||||||
|
set(DUSK_BACKTRACE ON CACHE BOOL "Enable backtrace support for assert failures.")
|
||||||
|
|
||||||
# Define platform-specific macros.
|
# Define platform-specific macros.
|
||||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||||
DUSK_SDL2
|
DUSK_SDL2
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-dolphin /bin/bash -c "./scripts/build-gamecube.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-gamecube.sh"
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-dolphin /bin/bash -c "./scripts/build-gamecube-iso.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-gamecube-iso.sh"
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-knulli -f docker/knulli/Dockerfile .
|
docker build -t dusk-knulli -f docker/knulli/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-knulli /bin/bash -c "./scripts/build-knulli.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-knulli /bin/bash -c "./scripts/build-knulli.sh"
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-linux -f docker/linux/Dockerfile .
|
docker build -t dusk-linux -f docker/linux/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-linux /bin/bash -c "./scripts/build-linux.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-linux /bin/bash -c "./scripts/build-linux.sh"
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-psp -f docker/psp/Dockerfile .
|
docker build -t dusk-psp -f docker/psp/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-psp /bin/bash -c "./scripts/build-psp.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-psp /bin/bash -c "./scripts/build-psp.sh"
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-vita -f docker/vita/Dockerfile .
|
docker build -t dusk-vita -f docker/vita/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-vita /bin/bash -c "./scripts/build-vita.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-vita /bin/bash -c "./scripts/build-vita.sh"
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-dolphin /bin/bash -c "./scripts/build-wii.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-wii.sh"
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
docker build -t dusk-dolphin -f docker/dolphin/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-dolphin /bin/bash -c "./scripts/build-wii-iso.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-dolphin /bin/bash -c "./scripts/build-wii-iso.sh"
|
||||||
|
|||||||
@@ -7,4 +7,5 @@ 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"
|
||||||
cd build-wii
|
cd build-wii
|
||||||
make -j$(nproc) VERBOSE=1
|
make -j$(nproc) VERBOSE=1
|
||||||
|
mv Dusk.dol boot.dol
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
docker build -t dusk-linux -f docker/linux/Dockerfile .
|
docker build -t dusk-linux -f docker/linux/Dockerfile .
|
||||||
docker run --rm -v $(pwd):/workdir dusk-linux /bin/bash -c "./scripts/test-linux.sh"
|
docker run --rm -v "$(pwd):/workdir" dusk-linux /bin/bash -c "./scripts/test-linux.sh"
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
rm -rf build-tests
|
||||||
cmake -S . -B build-tests -DDUSK_BUILD_TESTS=ON -DDUSK_TARGET_SYSTEM=linux
|
cmake -S . -B build-tests -DDUSK_BUILD_TESTS=ON -DDUSK_TARGET_SYSTEM=linux
|
||||||
cmake --build build-tests -- -j$(nproc)
|
cmake --build build-tests -- -j$(nproc)
|
||||||
ctest --output-on-failure --test-dir build-tests
|
ctest --output-on-failure --test-dir build-tests
|
||||||
@@ -32,6 +32,22 @@ if(NOT yyjson_FOUND)
|
|||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
if(NOT jerryscript_FOUND)
|
||||||
|
find_package(jerryscript REQUIRED)
|
||||||
|
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||||
|
jerryscript::core
|
||||||
|
jerryscript::ext
|
||||||
|
jerryscript::port
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(DUSK_BACKTRACE)
|
||||||
|
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
|
||||||
|
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
||||||
|
DUSK_BACKTRACE
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
# Includes
|
# Includes
|
||||||
target_include_directories(${DUSK_LIBRARY_TARGET_NAME}
|
target_include_directories(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
@@ -62,6 +78,7 @@ add_subdirectory(input)
|
|||||||
add_subdirectory(locale)
|
add_subdirectory(locale)
|
||||||
add_subdirectory(physics)
|
add_subdirectory(physics)
|
||||||
add_subdirectory(scene)
|
add_subdirectory(scene)
|
||||||
|
add_subdirectory(script)
|
||||||
add_subdirectory(system)
|
add_subdirectory(system)
|
||||||
add_subdirectory(time)
|
add_subdirectory(time)
|
||||||
add_subdirectory(ui)
|
add_subdirectory(ui)
|
||||||
|
|||||||
@@ -7,5 +7,4 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
|||||||
PUBLIC
|
PUBLIC
|
||||||
easing.c
|
easing.c
|
||||||
animation.c
|
animation.c
|
||||||
animationproperty.c
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -8,86 +8,45 @@
|
|||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
#include "util/math.h"
|
#include "util/math.h"
|
||||||
|
|
||||||
void animationInit(animation_t *anim) {
|
void animationInit(
|
||||||
memoryZero(anim, sizeof(animation_t));
|
animation_t *anim,
|
||||||
eventInit(&anim->onStart);
|
keyframe_t *keyframes,
|
||||||
eventInit(&anim->onComplete);
|
uint16_t keyframeCount
|
||||||
|
) {
|
||||||
|
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||||
|
assertNotNull(keyframes, "Keyframes pointer cannot be null.");
|
||||||
|
assertTrue(keyframeCount > 0, "Keyframe count must be more than 0.");
|
||||||
|
|
||||||
|
anim->keyframes = keyframes;
|
||||||
|
anim->keyframeCount = keyframeCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
animationproperty_t *animationAddProperty(animation_t *anim, float_t *target) {
|
float_t animationGetValue(animation_t *anim, const float_t time) {
|
||||||
assertTrue(
|
assertNotNull(anim, "Animation pointer cannot be null.");
|
||||||
anim->propertyCount < ANIMATION_PROPERTY_COUNT_MAX,
|
assertNotNull(anim->keyframes, "Keyframes pointer cannot be null.");
|
||||||
"Property count exceeds ANIMATION_PROPERTY_COUNT_MAX"
|
assertTrue(anim->keyframeCount > 0, "Keyframe count invalid.");
|
||||||
);
|
assertTrue(time >= 0, "Time must be non-negative.");
|
||||||
animationproperty_t *prop = &anim->properties[anim->propertyCount++];
|
|
||||||
prop->keyframeCount = 0;
|
keyframe_t *start;
|
||||||
prop->target = target;
|
keyframe_t *end;
|
||||||
return prop;
|
keyframe_t *last = anim->keyframes + anim->keyframeCount - 1;
|
||||||
}
|
keyframe_t *current = anim->keyframes;
|
||||||
|
start = current;
|
||||||
|
|
||||||
void animationUpdate(animation_t *anim, float_t delta) {
|
do {
|
||||||
assertNotNull(anim, "Animation cannot be null");
|
if(current->time > time) {
|
||||||
|
end = current;
|
||||||
if(
|
break;
|
||||||
(anim->flags & ANIMATION_FLAG_FINISHED) &&
|
|
||||||
!(anim->flags & ANIMATION_FLAG_LOOP_ENABLED)
|
|
||||||
) return;
|
|
||||||
|
|
||||||
bool_t wasStarted = (anim->flags & ANIMATION_FLAG_STARTED) != 0;
|
|
||||||
anim->flags |= ANIMATION_FLAG_STARTED;
|
|
||||||
anim->time += delta;
|
|
||||||
|
|
||||||
float_t duration = animationGetDuration(anim);
|
|
||||||
bool_t justFinished = false;
|
|
||||||
if(anim->time >= duration) {
|
|
||||||
if(anim->flags & ANIMATION_FLAG_LOOP_ENABLED) {
|
|
||||||
anim->time = mathModFloat(anim->time, duration);
|
|
||||||
} else {
|
|
||||||
anim->time = duration;
|
|
||||||
if(!(anim->flags & ANIMATION_FLAG_FINISHED)) {
|
|
||||||
anim->flags |= ANIMATION_FLAG_FINISHED;
|
|
||||||
justFinished = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
start = current;
|
||||||
|
current++;
|
||||||
|
|
||||||
for(uint8_t i = 0; i < anim->propertyCount; i++) {
|
if(current > last) {
|
||||||
animationproperty_t *prop = &anim->properties[i];
|
end = start;
|
||||||
if(prop->target != NULL) {
|
break;
|
||||||
*prop->target = animationPropertyGetValue(prop, anim->time);
|
|
||||||
}
|
}
|
||||||
}
|
} while(true);
|
||||||
|
|
||||||
if(!wasStarted) eventInvoke(&anim->onStart, anim);
|
float_t t = (time - start->time) / (end->time - start->time);
|
||||||
if(justFinished) eventInvoke(&anim->onComplete, anim);
|
return mathLerp(start->value, end->value, easingApply(start->easing, t));
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void animationReset(animation_t *anim) {
|
|
||||||
anim->time = 0.0f;
|
|
||||||
anim->flags &= ~(ANIMATION_FLAG_FINISHED | ANIMATION_FLAG_STARTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool_t animationIsFinished(const animation_t *anim) {
|
|
||||||
return (anim->flags & ANIMATION_FLAG_FINISHED) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool_t animationIsStarted(const animation_t *anim) {
|
|
||||||
return (anim->flags & ANIMATION_FLAG_STARTED) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool_t animationIsLooping(const animation_t *anim) {
|
|
||||||
return (anim->flags & ANIMATION_FLAG_LOOP_ENABLED) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
float_t animationGetDuration(const animation_t *anim) {
|
|
||||||
float_t duration = 0.0f;
|
|
||||||
for(uint8_t i = 0; i < anim->propertyCount; i++) {
|
|
||||||
animationproperty_t *prop = &anim->properties[i];
|
|
||||||
if(prop->keyframeCount == 0) continue;
|
|
||||||
float_t lastKeyframeTime =
|
|
||||||
prop->keyframes[prop->keyframeCount - 1].time;
|
|
||||||
if(lastKeyframeTime > duration) duration = lastKeyframeTime;
|
|
||||||
}
|
|
||||||
return duration;
|
|
||||||
}
|
}
|
||||||
@@ -4,87 +4,31 @@
|
|||||||
// https://opensource.org/licenses/MIT
|
// https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "animationproperty.h"
|
#include "keyframe.h"
|
||||||
#include "event/event.h"
|
|
||||||
|
|
||||||
#define ANIMATION_PROPERTY_COUNT_MAX 8
|
|
||||||
|
|
||||||
#define ANIMATION_FLAG_FINISHED (1 << 0)
|
|
||||||
#define ANIMATION_FLAG_STARTED (1 << 1)
|
|
||||||
#define ANIMATION_FLAG_LOOP_ENABLED (1 << 2)
|
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
animationproperty_t properties[ANIMATION_PROPERTY_COUNT_MAX];
|
keyframe_t *keyframes;
|
||||||
uint8_t propertyCount;
|
uint16_t keyframeCount;
|
||||||
float_t time;
|
|
||||||
uint8_t flags;
|
|
||||||
event_t onStart;
|
|
||||||
event_t onComplete;
|
|
||||||
} animation_t;
|
} animation_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes an animation.
|
* Initializes an animation.
|
||||||
*
|
*
|
||||||
* @param anim The animation to initialize.
|
* @param anim The animation to initialize.
|
||||||
|
* @param keyframes The keyframes to use for the animation.
|
||||||
|
* @param keyframeCount The number of keyframes in the animation.
|
||||||
*/
|
*/
|
||||||
void animationInit(animation_t *anim);
|
void animationInit(
|
||||||
|
animation_t *anim,
|
||||||
|
keyframe_t *keyframes,
|
||||||
|
uint16_t keyframeCount
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a new animated property. The caller owns target and must keep it valid
|
* Gets the value of the animation at a given time.
|
||||||
* for the lifetime of the animation.
|
|
||||||
*
|
*
|
||||||
* @param anim The animation to add the property to.
|
* @param anim The animation to get the value from.
|
||||||
* @param target Pointer to the float to write interpolated values into.
|
* @param time The time at which to get the value, in seconds.
|
||||||
* @return A pointer to the new property.
|
* @return The value of the animation at the given time.
|
||||||
*/
|
*/
|
||||||
animationproperty_t *animationAddProperty(animation_t *anim, float_t *target);
|
float_t animationGetValue(animation_t *anim, const float_t time);
|
||||||
|
|
||||||
/**
|
|
||||||
* Advances the animation by delta seconds and writes interpolated values to
|
|
||||||
* each property's target pointer.
|
|
||||||
*
|
|
||||||
* @param anim The animation to update.
|
|
||||||
* @param delta The time to advance the animation by, in seconds.
|
|
||||||
*/
|
|
||||||
void animationUpdate(animation_t *anim, float_t delta);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resets the animation to the beginning, clearing Started and Finished flags.
|
|
||||||
*
|
|
||||||
* @param anim The animation to reset.
|
|
||||||
*/
|
|
||||||
void animationReset(animation_t *anim);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if the animation has finished (i.e. reached the end of its
|
|
||||||
* duration and is not looping).
|
|
||||||
*
|
|
||||||
* @param anim The animation to check.
|
|
||||||
* @return true if the animation has finished, false otherwise.
|
|
||||||
*/
|
|
||||||
bool_t animationIsFinished(const animation_t *anim);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if the animation has been started (i.e. animationUpdate has
|
|
||||||
* been called at least once).
|
|
||||||
*
|
|
||||||
* @param anim The animation to check.
|
|
||||||
* @return true if the animation has been started, false otherwise.
|
|
||||||
*/
|
|
||||||
bool_t animationIsStarted(const animation_t *anim);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if the animation is set to loop.
|
|
||||||
*
|
|
||||||
* @param anim The animation to check.
|
|
||||||
* @return true if the animation is set to loop, false otherwise.
|
|
||||||
*/
|
|
||||||
bool_t animationIsLooping(const animation_t *anim);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the total duration of the animation (based on the keyframes).
|
|
||||||
*
|
|
||||||
* @param anim The animation to get the duration of.
|
|
||||||
* @return The total duration of the animation, in seconds.
|
|
||||||
*/
|
|
||||||
float_t animationGetDuration(const animation_t *anim);
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "animationproperty.h"
|
|
||||||
#include "assert/assert.h"
|
|
||||||
|
|
||||||
void animationPropertyAddKeyframe(
|
|
||||||
animationproperty_t *prop,
|
|
||||||
const float_t time,
|
|
||||||
const float_t value,
|
|
||||||
const easingtype_t easing
|
|
||||||
) {
|
|
||||||
assertNotNull(prop, "Property cannot be null");
|
|
||||||
assertTrue(
|
|
||||||
prop->keyframeCount < ANIMATION_PROPERTY_KEYFRAME_COUNT_MAX,
|
|
||||||
"Too many keyframes added to property"
|
|
||||||
);
|
|
||||||
assertTrue(time >= 0.0f, "Keyframe time cannot be negative");
|
|
||||||
|
|
||||||
keyframe_t *frame = &prop->keyframes[prop->keyframeCount++];
|
|
||||||
frame->time = time;
|
|
||||||
frame->value = value;
|
|
||||||
frame->easing = easing;
|
|
||||||
}
|
|
||||||
|
|
||||||
float_t animationPropertyGetValue(
|
|
||||||
const animationproperty_t *prop,
|
|
||||||
const float_t time
|
|
||||||
) {
|
|
||||||
assertNotNull(prop, "Property cannot be null");
|
|
||||||
assertTrue(time >= 0.0f, "Time cannot be negative");
|
|
||||||
|
|
||||||
if(prop->keyframeCount == 0) return 0.0f;
|
|
||||||
|
|
||||||
uint8_t last = prop->keyframeCount - 1;
|
|
||||||
|
|
||||||
if(prop->keyframeCount == 1) return prop->keyframes[0].value;
|
|
||||||
if(time <= prop->keyframes[0].time) return prop->keyframes[0].value;
|
|
||||||
if(time >= prop->keyframes[last].time) return prop->keyframes[last].value;
|
|
||||||
|
|
||||||
for(uint8_t i = 0; i < last; i++) {
|
|
||||||
const keyframe_t *a = &prop->keyframes[i];
|
|
||||||
const keyframe_t *b = &prop->keyframes[i + 1];
|
|
||||||
if(time < a->time || time >= b->time) continue;
|
|
||||||
float_t t = (time - a->time) / (b->time - a->time);
|
|
||||||
t = easingApply(a->easing, t);
|
|
||||||
return a->value + (b->value - a->value) * t;
|
|
||||||
}
|
|
||||||
|
|
||||||
return prop->keyframes[last].value;
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2026 Dominic Masters
|
|
||||||
*
|
|
||||||
* This software is released under the MIT License.
|
|
||||||
* https://opensource.org/licenses/MIT
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "keyframe.h"
|
|
||||||
|
|
||||||
#define ANIMATION_PROPERTY_KEYFRAME_COUNT_MAX 16
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
keyframe_t keyframes[ANIMATION_PROPERTY_KEYFRAME_COUNT_MAX];
|
|
||||||
uint8_t keyframeCount;
|
|
||||||
float_t *target;
|
|
||||||
} animationproperty_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Appends a keyframe to a property. Keyframes must be added in ascending time
|
|
||||||
* order. Updates the animation's duration.
|
|
||||||
*
|
|
||||||
* @param property The property to add the keyframe to.
|
|
||||||
* @param time The time of the keyframe, in seconds.
|
|
||||||
* @param value The value of the keyframe.
|
|
||||||
* @param easing The easing type to use when interpolating to the next keyframe.
|
|
||||||
*/
|
|
||||||
void animationPropertyAddKeyframe(
|
|
||||||
animationproperty_t *property,
|
|
||||||
const float_t time,
|
|
||||||
const float_t value,
|
|
||||||
const easingtype_t easing
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the property's value at a given time.
|
|
||||||
*
|
|
||||||
* @param prop The property to get the value from.
|
|
||||||
* @param time The time at which to get the value, in seconds.
|
|
||||||
* @return The value of the property at the given time.
|
|
||||||
*/
|
|
||||||
float_t animationPropertyGetValue(
|
|
||||||
const animationproperty_t *prop,
|
|
||||||
const float_t time
|
|
||||||
);
|
|
||||||
@@ -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) {
|
||||||
|
|||||||
@@ -10,4 +10,4 @@ typedef struct {
|
|||||||
float_t time;
|
float_t time;
|
||||||
float_t value;
|
float_t value;
|
||||||
easingtype_t easing;
|
easingtype_t easing;
|
||||||
} keyframe_t;
|
} keyframe_t;
|
||||||
@@ -8,8 +8,19 @@
|
|||||||
#include "assert.h"
|
#include "assert.h"
|
||||||
#include "log/log.h"
|
#include "log/log.h"
|
||||||
#include "util/string.h"
|
#include "util/string.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,
|
||||||
@@ -25,6 +36,25 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
|
#ifdef DUSK_BACKTRACE
|
||||||
|
#include <execinfo.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
static void assertLogBacktrace(void) {
|
||||||
|
void *frames[64];
|
||||||
|
int count = backtrace(frames, 64);
|
||||||
|
char **symbols = backtrace_symbols(frames, count);
|
||||||
|
memoryTrack(symbols);
|
||||||
|
logError("Stack trace:\n");
|
||||||
|
if(symbols) {
|
||||||
|
for(int i = 0; i < count; i++) {
|
||||||
|
logError(" %s\n", symbols[i]);
|
||||||
|
}
|
||||||
|
memoryFree(symbols);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
void assertTrueImpl(
|
void assertTrueImpl(
|
||||||
const char *file,
|
const char *file,
|
||||||
const int32_t line,
|
const int32_t line,
|
||||||
@@ -33,11 +63,14 @@
|
|||||||
) {
|
) {
|
||||||
if(x != true) {
|
if(x != true) {
|
||||||
logError(
|
logError(
|
||||||
"Assertion Failed in %s:%i\n\n%s\n",
|
"Assertion Failed in %s:%i\n\n%s\n\n",
|
||||||
file,
|
file,
|
||||||
line,
|
line,
|
||||||
message
|
message
|
||||||
);
|
);
|
||||||
|
#ifdef DUSK_BACKTRACE
|
||||||
|
assertLogBacktrace();
|
||||||
|
#endif
|
||||||
abort();
|
abort();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -109,4 +142,29 @@
|
|||||||
) {
|
) {
|
||||||
assertTrueImpl(file, line, stringCompare(a, b) == 0, message);
|
assertTrueImpl(file, line, stringCompare(a, b) == 0, message);
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
asset.c
|
asset.c
|
||||||
|
assetbatch.c
|
||||||
assetfile.c
|
assetfile.c
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+399
-14
@@ -11,15 +11,23 @@
|
|||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "engine/engine.h"
|
#include "engine/engine.h"
|
||||||
#include "util/string.h"
|
#include "util/string.h"
|
||||||
|
#include "console/console.h"
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
asset_t ASSET;
|
asset_t ASSET;
|
||||||
|
|
||||||
errorret_t assetInit(void) {
|
errorret_t assetInit(void) {
|
||||||
memoryZero(&ASSET, sizeof(asset_t));
|
memoryZero(&ASSET, sizeof(asset_t));
|
||||||
|
|
||||||
|
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
|
||||||
|
threadMutexInit(&ASSET.loading[i].mutex);
|
||||||
|
}
|
||||||
|
|
||||||
// assetInitPlatform must either define ASSET.zip or throw an error.
|
// assetInitPlatform must either define ASSET.zip or throw an error.
|
||||||
errorChain(assetInitPlatform());
|
errorChain(assetInitPlatform());
|
||||||
assertNotNull(ASSET.zip, "Asset zip null without error.");
|
assertNotNull(ASSET.zip, "Asset zip null without error.");
|
||||||
|
threadInit(&ASSET.loadThread, assetUpdateAsync);
|
||||||
|
threadStart(&ASSET.loadThread);
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
@@ -32,31 +40,408 @@ bool_t assetFileExists(const char_t *filename) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetLoad(
|
assetentry_t * assetGetEntry(
|
||||||
const char_t *filename,
|
const char_t *name,
|
||||||
assetfileloader_t loader,
|
const assetloadertype_t type,
|
||||||
void *params,
|
assetloaderinput_t *input
|
||||||
void *output
|
|
||||||
) {
|
) {
|
||||||
assertStrLenMax(filename, ASSET_FILE_NAME_MAX, "Filename too long.");
|
// Is there an existing asset?
|
||||||
assertNotNull(output, "Output pointer cannot be NULL.");
|
assetentry_t *entry = ASSET.entries;
|
||||||
assertNotNull(loader, "Asset file loader cannot be NULL.");
|
do {
|
||||||
|
if(entry->type == ASSET_LOADER_TYPE_NULL) {
|
||||||
|
entry++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if(stringEquals(entry->name, name)) {
|
||||||
|
assertTrue(entry->type == type, "Asset entry type mismatch.");
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
entry++;
|
||||||
|
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||||
|
|
||||||
|
// We did not find one existing, Find first available slot.
|
||||||
|
entry = ASSET.entries;
|
||||||
|
do {
|
||||||
|
if(entry->type != ASSET_LOADER_TYPE_NULL) {
|
||||||
|
entry++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
assetfile_t file;
|
if(entry->state == ASSET_ENTRY_STATE_NOT_STARTED) {
|
||||||
errorChain(assetFileInit(&file, filename, params, output));
|
assetEntryInit(entry, name, type, input);
|
||||||
errorChain(loader(&file));
|
return entry;
|
||||||
errorChain(assetFileDispose(&file));
|
}
|
||||||
|
entry++;
|
||||||
|
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||||
|
|
||||||
|
assertUnreachable("No available asset entry slots.");
|
||||||
|
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) {
|
||||||
|
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->state == ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lock to prevent the reaper from collecting the entry mid-spin.
|
||||||
|
assetEntryLock(entry);
|
||||||
|
|
||||||
|
while(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
usleep(1000);
|
||||||
|
errorret_t ret = assetUpdate();
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
assetEntryUnlock(entry);
|
||||||
|
errorChain(ret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assetEntryUnlock(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(
|
||||||
|
const char_t *name,
|
||||||
|
const assetloadertype_t type,
|
||||||
|
assetloaderinput_t *input
|
||||||
|
) {
|
||||||
|
assetentry_t *entry = assetGetEntry(name, type, input);
|
||||||
|
assetEntryLock(entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetUnlock(const char_t *name) {
|
||||||
|
assertNotNull(name, "Name cannot be NULL.");
|
||||||
|
|
||||||
|
assetentry_t *entry = ASSET.entries;
|
||||||
|
do {
|
||||||
|
if(entry->type != ASSET_LOADER_TYPE_NULL && stringEquals(entry->name, name)) {
|
||||||
|
assetEntryUnlock(entry);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entry++;
|
||||||
|
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||||
|
|
||||||
|
assertUnreachable("Asset entry not found for unlock.");
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetUnlockEntry(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL.");
|
||||||
|
assetEntryUnlock(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetUpdate(void) {
|
||||||
|
assertIsMainThread("assetUpdate must be called from the main thread.");
|
||||||
|
|
||||||
|
// Determine how many available loading slots we have.
|
||||||
|
assetloading_t *availableLoading[ASSET_LOADING_COUNT_MAX];
|
||||||
|
uint8_t availableLoadingCount = 0;
|
||||||
|
assetloading_t *loading = ASSET.loading;
|
||||||
|
assetentry_t *entry;
|
||||||
|
|
||||||
|
|
||||||
|
do {
|
||||||
|
// We only care about NULL entry references. Nothing async touches this so
|
||||||
|
// it's fine to use raw here.
|
||||||
|
if(loading->entry != NULL) {
|
||||||
|
loading++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
availableLoading[availableLoadingCount++] = loading;
|
||||||
|
loading++;
|
||||||
|
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
|
||||||
|
|
||||||
|
|
||||||
|
// Now we can check for pending asset entries, we can't do anything if there
|
||||||
|
// is no available slots though.
|
||||||
|
if(availableLoadingCount > 0) {
|
||||||
|
entry = ASSET.entries;
|
||||||
|
do {
|
||||||
|
// Is this asset "ready to start loading" ?
|
||||||
|
if(entry->type == ASSET_LOADER_TYPE_NULL) {
|
||||||
|
entry++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// We only care about assets not started.
|
||||||
|
if(entry->state != ASSET_ENTRY_STATE_NOT_STARTED) {
|
||||||
|
entry++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pop a loading slot for this asset entry.
|
||||||
|
loading = availableLoading[--availableLoadingCount];
|
||||||
|
|
||||||
|
// Start loading this asset.
|
||||||
|
assetEntryStartLoading(entry, loading);
|
||||||
|
entry++;
|
||||||
|
|
||||||
|
// Did we run out of loading slots?
|
||||||
|
if(availableLoadingCount == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now walk over all the loading slots and see what needs to be done.
|
||||||
|
loading = ASSET.loading;
|
||||||
|
do {
|
||||||
|
// Is the loading slot in use? Entry can only be modified synchronously.
|
||||||
|
if(loading->entry == NULL) {
|
||||||
|
loading++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lock the loading slot. This will prevent any async modifications.
|
||||||
|
threadMutexLock(&loading->mutex);
|
||||||
|
|
||||||
|
// Check the state of the entry.
|
||||||
|
switch(loading->entry->state) {
|
||||||
|
// This thing is pending synchronous loading.
|
||||||
|
case ASSET_ENTRY_STATE_PENDING_SYNC:
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADING_SYNC;
|
||||||
|
// Unlock before calling loadSync. The sync loader may re-enter
|
||||||
|
// assetUpdate (e.g. a script loading another asset), and the async
|
||||||
|
// thread never touches LOADING_SYNC entries, so this is safe.
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
|
||||||
|
errorret_t ret = (
|
||||||
|
ASSET_LOADER_CALLBACKS[loading->type].loadSync(loading)
|
||||||
|
);
|
||||||
|
|
||||||
|
// After a sync load, these are the only valid states.
|
||||||
|
assertTrue(
|
||||||
|
loading->entry->state == ASSET_ENTRY_STATE_LOADED ||
|
||||||
|
loading->entry->state == ASSET_ENTRY_STATE_ERROR ||
|
||||||
|
loading->entry->state == ASSET_ENTRY_STATE_PENDING_SYNC ||
|
||||||
|
loading->entry->state == ASSET_ENTRY_STATE_PENDING_ASYNC,
|
||||||
|
"Loader did not set entry state to loaded or error on finished load."
|
||||||
|
);
|
||||||
|
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
errorCatch(errorPrint(ret));
|
||||||
|
assertTrue(
|
||||||
|
loading->entry->state == ASSET_ENTRY_STATE_ERROR,
|
||||||
|
"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++;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_ENTRY_STATE_LOADING_SYNC:
|
||||||
|
// A re-entrant assetUpdate call (e.g. from a script loading another
|
||||||
|
// asset) will see this entry mid-sync-load. Skip it.
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
loading++;
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// Done loading, we can just free it up.
|
||||||
|
case ASSET_ENTRY_STATE_LOADED:
|
||||||
|
loading->entry = NULL;
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
loading++;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_ENTRY_STATE_ERROR: {
|
||||||
|
assetentry_t *errEntry = loading->entry;
|
||||||
|
loading->entry = NULL;
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
eventInvoke(&errEntry->onError, errEntry);
|
||||||
|
errorThrow("Failed to load asset asynchronously.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
loading++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
|
||||||
|
|
||||||
|
|
||||||
|
// Reap unused entries.
|
||||||
|
entry = ASSET.entries;
|
||||||
|
do {
|
||||||
|
if(entry->state != ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
entry++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(entry->type == ASSET_LOADER_TYPE_NULL) {
|
||||||
|
entry++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(entry->refs.count > 0) {
|
||||||
|
entry++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
consolePrint("Reaping asset %s", entry->name);
|
||||||
|
errorChain(assetEntryDispose(entry));
|
||||||
|
entry++;
|
||||||
|
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetUpdateAsync(thread_t *thread) {
|
||||||
|
assertNotMainThread("assetUpdateAsync must not run on the main thread.");
|
||||||
|
|
||||||
|
while(!threadShouldStop(thread)) {
|
||||||
|
// Walk over each asset
|
||||||
|
assetloading_t *loading;
|
||||||
|
loading = ASSET.loading;
|
||||||
|
|
||||||
|
do {
|
||||||
|
threadMutexLock(&loading->mutex);
|
||||||
|
|
||||||
|
if(loading->entry == NULL) {
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
loading++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch(loading->entry->state) {
|
||||||
|
case ASSET_ENTRY_STATE_PENDING_ASYNC:
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADING_ASYNC;
|
||||||
|
assertNotNull(
|
||||||
|
ASSET_LOADER_CALLBACKS[loading->type].loadAsync,
|
||||||
|
"Loader does not support async loading."
|
||||||
|
);
|
||||||
|
errorret_t ret = (
|
||||||
|
ASSET_LOADER_CALLBACKS[loading->type].loadAsync(loading)
|
||||||
|
);
|
||||||
|
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
errorCatch(errorPrint(ret));
|
||||||
|
assertTrue(
|
||||||
|
loading->entry->state == ASSET_ENTRY_STATE_ERROR,
|
||||||
|
"Loader did not set entry state to error on failed load."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
loading++;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_ENTRY_STATE_LOADING_ASYNC:
|
||||||
|
assertUnreachable(
|
||||||
|
"Entry is in a pending async state still?"
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
threadMutexUnlock(&loading->mutex);
|
||||||
|
loading++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
|
||||||
|
|
||||||
|
if(threadShouldStop(thread)) break;
|
||||||
|
usleep(1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
errorret_t assetDispose(void) {
|
errorret_t assetDispose(void) {
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
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++) {
|
||||||
|
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.
|
||||||
if(ASSET.zip != NULL) {
|
if(ASSET.zip != NULL) {
|
||||||
if(zip_close(ASSET.zip) != 0) {
|
if(zip_close(ASSET.zip) != 0) {
|
||||||
errorThrow("Failed to close asset zip archive.");
|
errorThrow("Failed to close asset zip archive.");
|
||||||
}
|
}
|
||||||
ASSET.zip = NULL;
|
ASSET.zip = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
errorChain(assetDisposePlatform());
|
errorChain(assetDisposePlatform());
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
+101
-12
@@ -9,6 +9,9 @@
|
|||||||
#include "error/error.h"
|
#include "error/error.h"
|
||||||
#include "asset/assetplatform.h"
|
#include "asset/assetplatform.h"
|
||||||
#include "assetfile.h"
|
#include "assetfile.h"
|
||||||
|
#include "thread/thread.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
|
||||||
#ifndef assetInitPlatform
|
#ifndef assetInitPlatform
|
||||||
#error "Platform must define assetInitPlatform function."
|
#error "Platform must define assetInitPlatform function."
|
||||||
@@ -20,15 +23,27 @@
|
|||||||
#define ASSET_FILE_NAME "dusk.dsk"
|
#define ASSET_FILE_NAME "dusk.dsk"
|
||||||
#define ASSET_HEADER_SIZE 3
|
#define ASSET_HEADER_SIZE 3
|
||||||
|
|
||||||
|
#define ASSET_LOADING_COUNT_MAX 4
|
||||||
|
#define ASSET_ENTRY_COUNT_MAX 128
|
||||||
|
|
||||||
typedef struct asset_s {
|
typedef struct asset_s {
|
||||||
zip_t *zip;
|
zip_t *zip;
|
||||||
assetplatform_t platform;
|
assetplatform_t platform;
|
||||||
|
|
||||||
|
// Background loading thread.
|
||||||
|
thread_t loadThread;
|
||||||
|
|
||||||
|
// Assets that are mid loading.
|
||||||
|
assetloading_t loading[ASSET_LOADING_COUNT_MAX];
|
||||||
|
assetentry_t entries[ASSET_ENTRY_COUNT_MAX];
|
||||||
} asset_t;
|
} asset_t;
|
||||||
|
|
||||||
extern asset_t ASSET;
|
extern asset_t ASSET;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the asset system.
|
* Initializes the asset system.
|
||||||
|
*
|
||||||
|
* @return An error code if the asset system could not be initialized properly.
|
||||||
*/
|
*/
|
||||||
errorret_t assetInit(void);
|
errorret_t assetInit(void);
|
||||||
|
|
||||||
@@ -41,21 +56,95 @@ errorret_t assetInit(void);
|
|||||||
bool_t assetFileExists(const char_t *filename);
|
bool_t assetFileExists(const char_t *filename);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads an asset by its filename,
|
* Gets, or creates, a new asset entry. Internal — prefer assetLock.
|
||||||
*
|
*
|
||||||
* @param filename The filename of the asset to retrieve.
|
* @param name Filename of the asset.
|
||||||
* @param loader Loader to use for loading the asset file.
|
* @param type Type of the asset.
|
||||||
* @param params Parameters to pass to the loader.
|
* @param input Loader-specific parameters.
|
||||||
* @param output The output pointer to store the loaded asset data.
|
|
||||||
* @return An error code if the asset could not be loaded.
|
|
||||||
*/
|
*/
|
||||||
errorret_t assetLoad(
|
assetentry_t * assetGetEntry(
|
||||||
const char_t *filename,
|
const char_t *name,
|
||||||
assetfileloader_t loader,
|
const assetloadertype_t type,
|
||||||
void *params,
|
assetloaderinput_t *input
|
||||||
void *output
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* the next assetUpdate. Call assetUnlock when done to allow the entry to be
|
||||||
|
* reclaimed.
|
||||||
|
*
|
||||||
|
* @param name Filename of the asset.
|
||||||
|
* @param type Type of the asset.
|
||||||
|
* @param input Loader-specific parameters.
|
||||||
|
* @return The locked asset entry.
|
||||||
|
*/
|
||||||
|
assetentry_t * assetLock(
|
||||||
|
const char_t *name,
|
||||||
|
const assetloadertype_t type,
|
||||||
|
assetloaderinput_t *input
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases a lock on an asset entry by name. When all locks are released the
|
||||||
|
* entry will be reclaimed at the start of the next assetUpdate.
|
||||||
|
*
|
||||||
|
* @param name Filename of the asset to unlock.
|
||||||
|
*/
|
||||||
|
void assetUnlock(const char_t *name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases a lock on an asset entry by pointer. When all locks are released
|
||||||
|
* the entry will be reclaimed at the start of the next assetUpdate.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to unlock.
|
||||||
|
*/
|
||||||
|
void assetUnlockEntry(assetentry_t *entry);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requires an asset entry to be loaded. This will block until the asset entry
|
||||||
|
* is fully loaded.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to require.
|
||||||
|
* @return An error code if the asset entry could not be loaded properly.
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
*
|
||||||
|
* @return An error code if the asset system could not be updated properly.
|
||||||
|
*/
|
||||||
|
errorret_t assetUpdate(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the background asset loading thread. The thread runs assetUpdate
|
||||||
|
* in a loop with a short sleep until stopped.
|
||||||
|
*
|
||||||
|
* @param thread The thread runner.
|
||||||
|
*/
|
||||||
|
void assetUpdateAsync(thread_t *thread);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disposes/cleans up the asset system.
|
* Disposes/cleans up the asset system.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetbatch.h"
|
||||||
|
#include "asset.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
/* ---- Per-entry event trampolines ----------------------------------------- */
|
||||||
|
|
||||||
|
static 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- Public API ---------------------------------------------------------- */
|
||||||
|
|
||||||
|
void assetBatchInit(
|
||||||
|
assetbatch_t *batch,
|
||||||
|
const uint16_t count,
|
||||||
|
const assetbatchdesc_t *descs
|
||||||
|
) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
assertNotNull(descs, "Descs cannot be NULL.");
|
||||||
|
assertTrue(count > 0, "Count must be greater than 0.");
|
||||||
|
assertTrue(count <= ASSET_BATCH_COUNT_MAX, "Count exceeds ASSET_BATCH_COUNT_MAX.");
|
||||||
|
|
||||||
|
memoryZero(batch, sizeof(assetbatch_t));
|
||||||
|
batch->count = count;
|
||||||
|
|
||||||
|
eventInit(
|
||||||
|
&batch->onLoaded,
|
||||||
|
batch->onLoadedCallbacks, batch->onLoadedUsers, ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&batch->onEntryLoaded,
|
||||||
|
batch->onEntryLoadedCallbacks, batch->onEntryLoadedUsers, ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&batch->onError,
|
||||||
|
batch->onErrorCallbacks, batch->onErrorUsers, ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
eventInit(
|
||||||
|
&batch->onEntryError,
|
||||||
|
batch->onEntryErrorCallbacks, batch->onEntryErrorUsers, ASSET_BATCH_EVENT_MAX
|
||||||
|
);
|
||||||
|
|
||||||
|
for(uint16_t i = 0; i < count; i++) {
|
||||||
|
batch->inputs[i] = descs[i].input;
|
||||||
|
batch->entries[i] = assetLock(descs[i].path, descs[i].type, &batch->inputs[i]);
|
||||||
|
|
||||||
|
if(batch->entries[i]->state == ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
/* Already loaded (cached) — count it now, no subscription needed. */
|
||||||
|
batch->loadedCount++;
|
||||||
|
} else if(batch->entries[i]->state == ASSET_ENTRY_STATE_ERROR) {
|
||||||
|
batch->errorCount++;
|
||||||
|
} else {
|
||||||
|
eventSubscribe(
|
||||||
|
&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb, batch
|
||||||
|
);
|
||||||
|
eventSubscribe(
|
||||||
|
&batch->entries[i]->onError, assetBatchEntryOnErrorCb, batch
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchLock(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
assetEntryLock(batch->entries[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchUnlock(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
assetEntryUnlock(batch->entries[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t assetBatchIsLoaded(const assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
if(batch->entries[i]->state != ASSET_ENTRY_STATE_LOADED) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool_t assetBatchHasError(const assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
if(batch->entries[i]->state == ASSET_ENTRY_STATE_ERROR) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetBatchRequireLoaded(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
|
||||||
|
bool_t allDone;
|
||||||
|
do {
|
||||||
|
allDone = true;
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
const assetentrystate_t state = batch->entries[i]->state;
|
||||||
|
if(state == ASSET_ENTRY_STATE_ERROR) {
|
||||||
|
errorThrow("Asset '%s' failed to load.", batch->entries[i]->name);
|
||||||
|
}
|
||||||
|
if(state != ASSET_ENTRY_STATE_LOADED) {
|
||||||
|
allDone = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!allDone) {
|
||||||
|
usleep(1000);
|
||||||
|
errorChain(assetUpdate());
|
||||||
|
}
|
||||||
|
} while(!allDone);
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetBatchDispose(assetbatch_t *batch) {
|
||||||
|
assertNotNull(batch, "Batch cannot be NULL.");
|
||||||
|
for(uint16_t i = 0; i < batch->count; i++) {
|
||||||
|
if(batch->entries[i]) {
|
||||||
|
/* Unsubscribe while we still hold a lock so the entry is guaranteed live. */
|
||||||
|
eventUnsubscribe(&batch->entries[i]->onLoaded, assetBatchEntryOnLoadedCb);
|
||||||
|
eventUnsubscribe(&batch->entries[i]->onError, assetBatchEntryOnErrorCb);
|
||||||
|
assetUnlockEntry(batch->entries[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
memoryZero(batch, sizeof(assetbatch_t));
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
#include "asset/loader/assetloader.h"
|
||||||
|
#include "event/event.h"
|
||||||
|
|
||||||
|
#define ASSET_BATCH_COUNT_MAX 64
|
||||||
|
#define ASSET_BATCH_EVENT_MAX 4
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
const char_t *path;
|
||||||
|
assetloadertype_t type;
|
||||||
|
assetloaderinput_t input;
|
||||||
|
} assetbatchdesc_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetentry_t *entries[ASSET_BATCH_COUNT_MAX];
|
||||||
|
assetloaderinput_t inputs[ASSET_BATCH_COUNT_MAX];
|
||||||
|
uint16_t count;
|
||||||
|
uint16_t loadedCount;
|
||||||
|
uint16_t errorCount;
|
||||||
|
|
||||||
|
/** Fires once when every entry has loaded successfully. 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 finishes loading. params = assetentry_t * */
|
||||||
|
event_t onEntryLoaded;
|
||||||
|
eventcallback_t onEntryLoadedCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||||
|
void *onEntryLoadedUsers[ASSET_BATCH_EVENT_MAX];
|
||||||
|
|
||||||
|
/** Fires once when all entries have finished (any with errors). params = assetbatch_t * */
|
||||||
|
event_t onError;
|
||||||
|
eventcallback_t onErrorCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||||
|
void *onErrorUsers[ASSET_BATCH_EVENT_MAX];
|
||||||
|
|
||||||
|
/** Fires each time a single entry errors. params = assetentry_t * */
|
||||||
|
event_t onEntryError;
|
||||||
|
eventcallback_t onEntryErrorCallbacks[ASSET_BATCH_EVENT_MAX];
|
||||||
|
void *onEntryErrorUsers[ASSET_BATCH_EVENT_MAX];
|
||||||
|
} assetbatch_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialises the batch from an array of descriptors. Each entry is locked
|
||||||
|
* and queued for loading immediately.
|
||||||
|
*
|
||||||
|
* @param batch Batch to initialise.
|
||||||
|
* @param descs Array of entry descriptors (need not outlive this call).
|
||||||
|
* @param count Number of descriptors (must be <= ASSET_BATCH_COUNT_MAX).
|
||||||
|
*/
|
||||||
|
void assetBatchInit(
|
||||||
|
assetbatch_t *batch,
|
||||||
|
uint16_t count,
|
||||||
|
const assetbatchdesc_t *descs
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Acquires one additional lock on every entry in the batch.
|
||||||
|
*
|
||||||
|
* @param batch Batch to lock.
|
||||||
|
*/
|
||||||
|
void assetBatchLock(assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases one lock from every entry in the batch. When an entry's lock
|
||||||
|
* count reaches zero it will be reaped on the next assetUpdate.
|
||||||
|
*
|
||||||
|
* @param batch Batch to unlock.
|
||||||
|
*/
|
||||||
|
void assetBatchUnlock(assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if every entry in the batch has finished loading.
|
||||||
|
*
|
||||||
|
* @param batch Batch to query.
|
||||||
|
*/
|
||||||
|
bool_t assetBatchIsLoaded(const assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if any entry in the batch is in an error state.
|
||||||
|
*
|
||||||
|
* @param batch Batch to query.
|
||||||
|
*/
|
||||||
|
bool_t assetBatchHasError(const assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocks until every entry is loaded. Returns an error if any entry fails.
|
||||||
|
*
|
||||||
|
* @param batch Batch to wait on.
|
||||||
|
*/
|
||||||
|
errorret_t assetBatchRequireLoaded(assetbatch_t *batch);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases the batch's lock on every entry and clears the batch. After this
|
||||||
|
* call the batch struct may be reused with assetBatchInit.
|
||||||
|
*
|
||||||
|
* @param batch Batch to dispose.
|
||||||
|
*/
|
||||||
|
void assetBatchDispose(assetbatch_t *batch);
|
||||||
@@ -117,6 +117,48 @@ 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,6 +15,7 @@ typedef struct assetfile_s assetfile_t;
|
|||||||
|
|
||||||
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
|
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
|
||||||
|
|
||||||
|
// Describes a file not yet loaded.
|
||||||
typedef struct assetfile_s {
|
typedef struct assetfile_s {
|
||||||
char_t filename[ASSET_FILE_NAME_MAX];
|
char_t filename[ASSET_FILE_NAME_MAX];
|
||||||
void *params;
|
void *params;
|
||||||
@@ -85,12 +86,27 @@ errorret_t assetFileClose(assetfile_t *file);
|
|||||||
/**
|
/**
|
||||||
* Disposes the asset file structure, closing any open handles and zeroing
|
* Disposes the asset file structure, closing any open handles and zeroing
|
||||||
* out the structure.
|
* out the structure.
|
||||||
*
|
*
|
||||||
* @param file The asset file to dispose.
|
* @param file The asset file to dispose.
|
||||||
* @return An error code if the file could not be disposed properly.
|
* @return An error code if the file could not be disposed properly.
|
||||||
*/
|
*/
|
||||||
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;
|
||||||
|
|||||||
@@ -4,8 +4,15 @@
|
|||||||
# https://opensource.org/licenses/MIT
|
# https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
# Sources
|
# Sources
|
||||||
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
|
PUBLIC
|
||||||
|
assetentry.c
|
||||||
|
assetloader.c
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Subdirs
|
# Subdirs
|
||||||
add_subdirectory(display)
|
add_subdirectory(display)
|
||||||
add_subdirectory(locale)
|
add_subdirectory(locale)
|
||||||
add_subdirectory(json)
|
add_subdirectory(json)
|
||||||
|
add_subdirectory(script)
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetentry.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "util/string.h"
|
||||||
|
|
||||||
|
void assetEntryInit(
|
||||||
|
assetentry_t *entry,
|
||||||
|
const char_t *name,
|
||||||
|
const assetloadertype_t type,
|
||||||
|
assetloaderinput_t *input
|
||||||
|
) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL");
|
||||||
|
assertStrLenMin(name, 1, "Name cannot be empty");
|
||||||
|
assertStrLenMax(name, ASSET_FILE_NAME_MAX - 1, "Name too long");
|
||||||
|
assertTrue(type != ASSET_LOADER_TYPE_NULL, "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));
|
||||||
|
stringCopy(entry->name, name, ASSET_FILE_NAME_MAX);
|
||||||
|
entry->type = type;
|
||||||
|
entry->state = ASSET_ENTRY_STATE_NOT_STARTED;
|
||||||
|
if(input) {
|
||||||
|
entry->inputData = *input;
|
||||||
|
} else {
|
||||||
|
memoryZero(&entry->inputData, sizeof(assetloaderinput_t));
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL");
|
||||||
|
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||||
|
|
||||||
|
refLock(&entry->refs);
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetEntryUnlock(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL");
|
||||||
|
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||||
|
|
||||||
|
refUnlock(&entry->refs);
|
||||||
|
}
|
||||||
|
|
||||||
|
void assetEntryStartLoading(
|
||||||
|
assetentry_t *entry,
|
||||||
|
assetloading_t *loading
|
||||||
|
) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL");
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "Invalid loader type.");
|
||||||
|
assertTrue(
|
||||||
|
entry->state == ASSET_ENTRY_STATE_NOT_STARTED,
|
||||||
|
"Can only start loading from NOT_STARTED state."
|
||||||
|
);
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
|
memoryZero(&loading->loading, sizeof(assetloaderloading_t));
|
||||||
|
loading->type = entry->type;
|
||||||
|
loading->entry = entry;
|
||||||
|
// At this point the asset manager will manage this thing's loading
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetEntryDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL");
|
||||||
|
assertTrue(entry->type != ASSET_LOADER_TYPE_NULL, "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));
|
||||||
|
memoryZero(entry, sizeof(assetentry_t));
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "event/event.h"
|
||||||
|
#include "util/ref.h"
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_ENTRY_STATE_NOT_STARTED,
|
||||||
|
ASSET_ENTRY_STATE_PENDING_ASYNC,
|
||||||
|
ASSET_ENTRY_STATE_LOADING_ASYNC,
|
||||||
|
ASSET_ENTRY_STATE_PENDING_SYNC,
|
||||||
|
ASSET_ENTRY_STATE_LOADING_SYNC,
|
||||||
|
ASSET_ENTRY_STATE_LOADED,
|
||||||
|
ASSET_ENTRY_STATE_ERROR
|
||||||
|
} assetentrystate_t;
|
||||||
|
|
||||||
|
/** Maximum number of subscribers for each per-entry event. */
|
||||||
|
#define ASSET_ENTRY_EVENT_MAX 2
|
||||||
|
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
struct assetentry_s {
|
||||||
|
char_t name[ASSET_FILE_NAME_MAX];
|
||||||
|
assetloadertype_t type;
|
||||||
|
assetloaderoutput_t data;
|
||||||
|
assetentrystate_t state;
|
||||||
|
ref_t refs;
|
||||||
|
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
|
||||||
|
* the asset.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to initialize.
|
||||||
|
* @param name The name of the asset, used as a key for loading and caching.
|
||||||
|
* @param type The type of asset this entry represents.
|
||||||
|
* @param input Data that will be passed to the loader about how it should load.
|
||||||
|
*/
|
||||||
|
void assetEntryInit(
|
||||||
|
assetentry_t *entry,
|
||||||
|
const char_t *name,
|
||||||
|
const assetloadertype_t type,
|
||||||
|
assetloaderinput_t *input
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Locks an asset entry, preventing it from being freed until it is unlocked.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to lock.
|
||||||
|
*/
|
||||||
|
void assetEntryLock(assetentry_t *entry);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unlocks an asset entry, allowing it to be freed if there are no more locks.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to unlock.
|
||||||
|
*/
|
||||||
|
void assetEntryUnlock(assetentry_t *entry);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts loading the given asset entry using an assetloading slot. This will
|
||||||
|
* be called by the asset manager when it deems it's a good time to begin the
|
||||||
|
* loading of this asset entry.
|
||||||
|
*
|
||||||
|
* Currently we return the error but in future this will not be returned.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to start loading.
|
||||||
|
* @param loading The assetloading slot to use for loading this asset entry.
|
||||||
|
* @return Any error that occurs during loading.
|
||||||
|
*/
|
||||||
|
void assetEntryStartLoading(assetentry_t *entry, assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes an asset entry, freeing any resources it holds.
|
||||||
|
* Fires the onUnloaded event before releasing asset data.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to dispose.
|
||||||
|
* @return Any error that occurs during disposal.
|
||||||
|
*/
|
||||||
|
errorret_t assetEntryDispose(assetentry_t *entry);
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetloader.h"
|
||||||
|
|
||||||
|
assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
|
||||||
|
[ASSET_LOADER_TYPE_NULL] = { 0 },
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_MESH] = {
|
||||||
|
.loadSync = assetMeshLoaderSync,
|
||||||
|
.loadAsync = assetMeshLoaderAsync,
|
||||||
|
.dispose = assetMeshDispose
|
||||||
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_TEXTURE] = {
|
||||||
|
.loadSync = assetTextureLoaderSync,
|
||||||
|
.loadAsync = assetTextureLoaderAsync,
|
||||||
|
.dispose = assetTextureDispose
|
||||||
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_TILESET] = {
|
||||||
|
.loadSync = assetTilesetLoaderSync,
|
||||||
|
.loadAsync = assetTilesetLoaderAsync,
|
||||||
|
.dispose = assetTilesetDispose
|
||||||
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_LOCALE] = {
|
||||||
|
.loadSync = assetLocaleLoaderSync,
|
||||||
|
.loadAsync = assetLocaleLoaderAsync,
|
||||||
|
.dispose = assetLocaleDispose
|
||||||
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_JSON] = {
|
||||||
|
.loadSync = assetJsonLoaderSync,
|
||||||
|
.loadAsync = assetJsonLoaderAsync,
|
||||||
|
.dispose = assetJsonDispose
|
||||||
|
},
|
||||||
|
|
||||||
|
[ASSET_LOADER_TYPE_SCRIPT] = {
|
||||||
|
.loadSync = assetScriptLoaderSync,
|
||||||
|
.loadAsync = assetScriptLoaderAsync,
|
||||||
|
.dispose = assetScriptDispose
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "asset/loader/display/assetmeshloader.h"
|
||||||
|
#include "asset/loader/display/assettextureloader.h"
|
||||||
|
#include "asset/loader/display/assettilesetloader.h"
|
||||||
|
#include "asset/loader/locale/assetlocaleloader.h"
|
||||||
|
#include "asset/loader/json/assetjsonloader.h"
|
||||||
|
#include "asset/loader/script/assetscriptloader.h"
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_LOADER_TYPE_NULL,
|
||||||
|
|
||||||
|
ASSET_LOADER_TYPE_MESH,
|
||||||
|
ASSET_LOADER_TYPE_TEXTURE,
|
||||||
|
ASSET_LOADER_TYPE_TILESET,
|
||||||
|
ASSET_LOADER_TYPE_LOCALE,
|
||||||
|
ASSET_LOADER_TYPE_JSON,
|
||||||
|
ASSET_LOADER_TYPE_SCRIPT,
|
||||||
|
|
||||||
|
ASSET_LOADER_TYPE_COUNT
|
||||||
|
} assetloadertype_t;
|
||||||
|
|
||||||
|
typedef union {
|
||||||
|
assetmeshloaderinput_t mesh;
|
||||||
|
assettextureloaderinput_t texture;
|
||||||
|
assettilesetloaderinput_t tileset;
|
||||||
|
assetlocaleloaderinput_t locale;
|
||||||
|
assetjsonloaderinput_t json;
|
||||||
|
assetscriptloaderinput_t script;
|
||||||
|
} assetloaderinput_t;
|
||||||
|
|
||||||
|
typedef union {
|
||||||
|
assetmeshloaderloading_t mesh;
|
||||||
|
assettextureloaderloading_t texture;
|
||||||
|
assettilesetloaderloading_t tileset;
|
||||||
|
assetlocaleloaderloading_t locale;
|
||||||
|
assetjsonloaderloading_t json;
|
||||||
|
assetscriptloaderloading_t script;
|
||||||
|
} assetloaderloading_t;
|
||||||
|
|
||||||
|
typedef union {
|
||||||
|
assetmeshoutput_t mesh;
|
||||||
|
assettextureoutput_t texture;
|
||||||
|
assettilesetoutput_t tileset;
|
||||||
|
assetlocaleoutput_t locale;
|
||||||
|
assetjsonoutput_t json;
|
||||||
|
assetscriptoutput_t script;
|
||||||
|
} assetloaderoutput_t;
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
typedef errorret_t (assetloadersynccallback_t)(assetloading_t *loading);
|
||||||
|
typedef errorret_t (assetloaderasynccallback_t)(assetloading_t *loading);
|
||||||
|
typedef errorret_t (assetloaderdisposecallback_t)(assetentry_t *entry);
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetloadersynccallback_t *loadSync;
|
||||||
|
assetloaderasynccallback_t *loadAsync;
|
||||||
|
assetloaderdisposecallback_t *dispose;
|
||||||
|
} assetloadercallbacks_t;
|
||||||
|
|
||||||
|
extern assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shorthand method to both chain an error (against the loader state) and to
|
||||||
|
* set the asset entry state to error.
|
||||||
|
*
|
||||||
|
* @param loading The asset loading slot.
|
||||||
|
* @param ret The error return value to check and chain if it's an error.
|
||||||
|
*/
|
||||||
|
#define assetLoaderErrorChain(loading, _expr) {\
|
||||||
|
errorret_t _alec = (_expr); \
|
||||||
|
if(errorIsNotOk(_alec)) { \
|
||||||
|
(loading)->entry->state = ASSET_ENTRY_STATE_ERROR; \
|
||||||
|
errorChain(_alec); \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shorthand method to both throw an error (against the loader state) and to
|
||||||
|
* set the asset entry state to error.
|
||||||
|
*
|
||||||
|
* @param loading The asset loading slot.
|
||||||
|
* @param ... Format string and arguments for the error message.
|
||||||
|
*/
|
||||||
|
#define assetLoaderErrorThrow(loading, ...) {\
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_ERROR; \
|
||||||
|
errorThrow(__VA_ARGS__); \
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "assetloader.h"
|
||||||
|
#include "asset/assetfile.h"
|
||||||
|
#include "thread/threadmutex.h"
|
||||||
|
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
typedef struct assetloading_s {
|
||||||
|
threadmutex_t mutex;
|
||||||
|
assetloadertype_t type;
|
||||||
|
assetentry_t *entry;
|
||||||
|
assetloaderloading_t loading;
|
||||||
|
} assetloading_t;
|
||||||
|
|
||||||
|
typedef errorret_t (assetloadingcallback_t)(assetloading_t *loading);
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetloadingcallback_t *loadSync;
|
||||||
|
} assetloadingcallbacks_t;
|
||||||
@@ -1,182 +1,174 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2026 Dominic Masters
|
* Copyright (c) 2026 Dominic Masters
|
||||||
*
|
*
|
||||||
* This software is released under the MIT License.
|
* This software is released under the MIT License.
|
||||||
* https://opensource.org/licenses/MIT
|
* https://opensource.org/licenses/MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "asset/loader/display/assetmeshloader.h"
|
#include "assetmeshloader.h"
|
||||||
#include "asset/asset.h"
|
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "util/endian.h"
|
#include "util/endian.h"
|
||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
errorret_t assetMeshLoader(assetfile_t *file) {
|
errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
|
||||||
assertNotNull(file, "Asset file cannot be null");
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
|
||||||
assetmeshoutput_t *output = (assetmeshoutput_t *)file->output;
|
|
||||||
assertNotNull(output, "Output cannot be null");
|
|
||||||
assertNotNull(output->outMesh, "Output mesh cannot be null");
|
|
||||||
assertNotNull(output->outVertices, "Output vertices cannot be null");
|
|
||||||
|
|
||||||
// STL file loading
|
if(loading->loading.mesh.state != ASSET_MESH_LOADING_STATE_READ_FILE) {
|
||||||
errorChain(assetFileOpen(file));
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
// Skip the 80 byte header
|
assetmeshoutput_t *out = &loading->entry->data.mesh;
|
||||||
errorChain(assetFileRead(file, NULL, 80));
|
assetfile_t *file = &loading->loading.mesh.file;
|
||||||
if(file->lastRead != 80) errorThrow("Failed to skip STL header");
|
assetmeshinputaxis_t axis = loading->entry->inputData.mesh;
|
||||||
|
|
||||||
|
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL));
|
||||||
|
assetLoaderErrorChain(loading, assetFileOpen(file));
|
||||||
|
|
||||||
|
// Skip the 80-byte STL header.
|
||||||
|
assetLoaderErrorChain(loading, assetFileRead(file, NULL, 80));
|
||||||
|
if(file->lastRead != 80) {
|
||||||
|
assetLoaderErrorThrow(loading, "Failed to skip STL header.");
|
||||||
|
}
|
||||||
|
|
||||||
uint32_t triangleCount;
|
uint32_t triangleCount;
|
||||||
errorChain(assetFileRead(file, &triangleCount, sizeof(uint32_t)));
|
assetLoaderErrorChain(loading, assetFileRead(file, &triangleCount, sizeof(uint32_t)));
|
||||||
if(file->lastRead != sizeof(uint32_t)) errorThrow("Failed read tri count");
|
if(file->lastRead != sizeof(uint32_t)) {
|
||||||
// normalize
|
assetLoaderErrorThrow(loading, "Failed to read tri count");
|
||||||
|
}
|
||||||
triangleCount = endianLittleToHost32(triangleCount);
|
triangleCount = endianLittleToHost32(triangleCount);
|
||||||
|
|
||||||
// Allocate mesh and vertex data
|
|
||||||
errorret_t ret;
|
|
||||||
meshvertex_t *verts = memoryAllocate(
|
|
||||||
sizeof(meshvertex_t) * triangleCount * 3
|
|
||||||
);
|
|
||||||
*output->outVertices = verts;
|
|
||||||
|
|
||||||
// Read triangle data
|
out->vertices = memoryAllocate(sizeof(meshvertex_t) * triangleCount * 3);
|
||||||
|
meshvertex_t *verts = out->vertices;
|
||||||
|
|
||||||
|
errorret_t ret;
|
||||||
for(uint32_t i = 0; i < triangleCount; i++) {
|
for(uint32_t i = 0; i < triangleCount; i++) {
|
||||||
assetmeshstltriangle_t triData;
|
assetmeshstltriangle_t triData;
|
||||||
ret = assetFileRead(file, &triData, sizeof(triData));
|
ret = assetFileRead(file, &triData, sizeof(triData));
|
||||||
if(ret.code != ERROR_OK) {
|
if(errorIsNotOk(ret)) {
|
||||||
memoryFree(verts);
|
memoryFree(verts);
|
||||||
errorChain(ret);
|
out->vertices = NULL;
|
||||||
|
assetLoaderErrorChain(loading, ret);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(file->lastRead != sizeof(triData)) {
|
if(file->lastRead != sizeof(triData)) {
|
||||||
memoryFree(verts);
|
memoryFree(verts);
|
||||||
errorThrow("Failed to read triangle data");
|
out->vertices = NULL;
|
||||||
|
assetLoaderErrorThrow(loading, "Failed to read triangle data");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip normals, we don't use them
|
|
||||||
|
|
||||||
// Fix endianess of of data
|
|
||||||
for(uint8_t j = 0; j < 3; j++) {
|
for(uint8_t j = 0; j < 3; j++) {
|
||||||
#if MESH_ENABLE_COLOR
|
#if MESH_ENABLE_COLOR
|
||||||
verts[i * 3 + j].color.r = (uint8_t)(endianLittleToHostFloat(
|
verts[i * 3 + j].color.r = (
|
||||||
triData.normal[0]
|
(uint8_t)(endianLittleToHostFloat(triData.normal[0]) * 255.0f)
|
||||||
) * 255.0f);
|
);
|
||||||
verts[i * 3 + j].color.g = (uint8_t)(endianLittleToHostFloat(
|
verts[i * 3 + j].color.g = (
|
||||||
triData.normal[1]
|
(uint8_t)(endianLittleToHostFloat(triData.normal[1]) * 255.0f)
|
||||||
) * 255.0f);
|
);
|
||||||
verts[i * 3 + j].color.b = (uint8_t)(endianLittleToHostFloat(
|
verts[i * 3 + j].color.b = (
|
||||||
triData.normal[2]
|
(uint8_t)(endianLittleToHostFloat(triData.normal[2]) * 255.0f)
|
||||||
) * 255.0f);
|
);
|
||||||
verts[i * 3 + j].color.a = 0xFF;
|
verts[i * 3 + j].color.a = 0xFF;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
verts[i * 3 + j].uv[0] = 0.0f; // No UV data in STL, just set to 0
|
verts[i * 3 + j].uv[0] = 0.0f;
|
||||||
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(
|
verts[i * 3 + j].pos[k] = endianLittleToHostFloat(triData.positions[j][k]);
|
||||||
triData.positions[j][k]
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch(output->inputAxis) {
|
switch(axis) {
|
||||||
case MESH_INPUT_AXIS_Z_UP:
|
case MESH_INPUT_AXIS_Z_UP: {
|
||||||
// Convert Z-Up to Y-Up
|
float_t temp = verts[i * 3 + j].pos[1];
|
||||||
{
|
verts[i * 3 + j].pos[1] = verts[i * 3 + j].pos[2];
|
||||||
float_t temp = verts[i * 3 + j].pos[1];
|
verts[i * 3 + j].pos[2] = temp;
|
||||||
verts[i * 3 + j].pos[1] = verts[i * 3 + j].pos[2];
|
|
||||||
verts[i * 3 + j].pos[2] = temp;
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
case MESH_INPUT_AXIS_X_UP:
|
case MESH_INPUT_AXIS_X_UP: {
|
||||||
// Convert X-Up to Y-Up
|
float_t temp = verts[i * 3 + j].pos[0];
|
||||||
{
|
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
||||||
float_t temp = verts[i * 3 + j].pos[0];
|
verts[i * 3 + j].pos[1] = temp;
|
||||||
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
|
||||||
verts[i * 3 + j].pos[1] = temp;
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
case MESH_INPUT_AXIS_Y_DOWN:
|
case MESH_INPUT_AXIS_Y_DOWN:
|
||||||
// Invert Y axis
|
|
||||||
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[1];
|
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[1];
|
||||||
break;
|
break;
|
||||||
|
case MESH_INPUT_AXIS_Z_DOWN: {
|
||||||
case MESH_INPUT_AXIS_Z_DOWN:
|
float_t temp = verts[i * 3 + j].pos[1];
|
||||||
// Convert Z-Up to Y-Up and invert Y axis
|
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[2];
|
||||||
{
|
verts[i * 3 + j].pos[2] = temp;
|
||||||
float_t temp = verts[i * 3 + j].pos[1];
|
|
||||||
verts[i * 3 + j].pos[1] = -verts[i * 3 + j].pos[2];
|
|
||||||
verts[i * 3 + j].pos[2] = temp;
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
case MESH_INPUT_AXIS_X_DOWN:
|
case MESH_INPUT_AXIS_X_DOWN: {
|
||||||
// Convert X-Up to Y-Up and invert Y axis
|
float_t temp = verts[i * 3 + j].pos[0];
|
||||||
{
|
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
||||||
float_t temp = verts[i * 3 + j].pos[0];
|
verts[i * 3 + j].pos[1] = -temp;
|
||||||
verts[i * 3 + j].pos[0] = verts[i * 3 + j].pos[1];
|
|
||||||
verts[i * 3 + j].pos[1] = -temp;
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
case MESH_INPUT_AXIS_Y_UP:
|
case MESH_INPUT_AXIS_Y_UP:
|
||||||
default:
|
default:
|
||||||
// No covnersion possible / Needed
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finally, init mesh
|
|
||||||
ret = meshInit(
|
|
||||||
output->outMesh,
|
|
||||||
MESH_PRIMITIVE_TYPE_TRIANGLES,
|
|
||||||
triangleCount * 3,
|
|
||||||
verts
|
|
||||||
);
|
|
||||||
if(ret.code != ERROR_OK) {
|
|
||||||
memoryFree(verts);
|
|
||||||
errorChain(ret);
|
|
||||||
}
|
|
||||||
|
|
||||||
ret = assetFileClose(file);
|
ret = assetFileClose(file);
|
||||||
if(ret.code != ERROR_OK) {
|
if(errorIsNotOk(ret)) {
|
||||||
errorCatch(errorPrint(meshDispose(output->outMesh)));
|
|
||||||
memoryFree(verts);
|
memoryFree(verts);
|
||||||
errorChain(ret);
|
out->vertices = NULL;
|
||||||
|
assetLoaderErrorChain(loading, ret);
|
||||||
}
|
}
|
||||||
|
assetFileDispose(file);
|
||||||
|
|
||||||
|
loading->loading.mesh.triangleCount = triangleCount;
|
||||||
|
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_CREATE_MESH;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetMeshLoadToOutput(
|
errorret_t assetMeshLoaderSync(assetloading_t *loading) {
|
||||||
const char_t *path,
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
assetmeshoutput_t *output
|
assertTrue(loading->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
|
||||||
) {
|
|
||||||
assertNotNull(path, "Path cannot be null");
|
switch(loading->loading.mesh.state) {
|
||||||
assertNotNull(output, "Output cannot be null");
|
case ASSET_MESH_LOADING_STATE_INITIAL:
|
||||||
assertNotNull(output->outMesh, "Output mesh cannot be null");
|
loading->loading.mesh.state = ASSET_MESH_LOADING_STATE_READ_FILE;
|
||||||
assertNotNull(output->outVertices, "Output vertices cannot be null");
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
return assetLoad(path, &assetMeshLoader, NULL, output);
|
break;
|
||||||
|
|
||||||
|
case ASSET_MESH_LOADING_STATE_CREATE_MESH:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
assetmeshoutput_t *out = &loading->entry->data.mesh;
|
||||||
|
assertNotNull(out->vertices, "Mesh vertices should have been loaded by now.");
|
||||||
|
|
||||||
|
errorret_t ret = meshInit(
|
||||||
|
&out->mesh,
|
||||||
|
MESH_PRIMITIVE_TYPE_TRIANGLES,
|
||||||
|
loading->loading.mesh.triangleCount * 3,
|
||||||
|
out->vertices
|
||||||
|
);
|
||||||
|
if(errorIsNotOk(ret)) {
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||||
|
memoryFree(out->vertices);
|
||||||
|
out->vertices = NULL;
|
||||||
|
assetLoaderErrorChain(loading, ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetMeshLoad(
|
errorret_t assetMeshDispose(assetentry_t *entry) {
|
||||||
const char_t *path,
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
mesh_t *outMesh,
|
assertTrue(entry->type == ASSET_LOADER_TYPE_MESH, "Invalid type.");
|
||||||
meshvertex_t **outVertices,
|
errorChain(meshDispose(&entry->data.mesh.mesh));
|
||||||
const assetmeshinputaxis_t inputAxis
|
memoryFree(entry->data.mesh.vertices);
|
||||||
) {
|
errorOk();
|
||||||
assertNotNull(path, "Path cannot be null");
|
}
|
||||||
assertNotNull(outMesh, "Output mesh cannot be null");
|
|
||||||
assertNotNull(outVertices, "Output vertices cannot be null");
|
|
||||||
|
|
||||||
assetmeshoutput_t output = {
|
|
||||||
outMesh,
|
|
||||||
outVertices,
|
|
||||||
inputAxis
|
|
||||||
};
|
|
||||||
return assetMeshLoadToOutput(path, &output);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,17 +1,20 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2026 Dominic Masters
|
* Copyright (c) 2026 Dominic Masters
|
||||||
*
|
*
|
||||||
* This software is released under the MIT License.
|
* This software is released under the MIT License.
|
||||||
* https://opensource.org/licenses/MIT
|
* https://opensource.org/licenses/MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/asset.h"
|
#include "asset/assetfile.h"
|
||||||
#include "display/mesh/mesh.h"
|
#include "display/mesh/mesh.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
MESH_INPUT_AXIS_Y_UP,// Default
|
MESH_INPUT_AXIS_Y_UP,
|
||||||
MESH_INPUT_AXIS_Z_UP,
|
MESH_INPUT_AXIS_Z_UP,
|
||||||
MESH_INPUT_AXIS_X_UP,
|
MESH_INPUT_AXIS_X_UP,
|
||||||
|
|
||||||
@@ -20,10 +23,24 @@ typedef enum {
|
|||||||
MESH_INPUT_AXIS_X_DOWN,
|
MESH_INPUT_AXIS_X_DOWN,
|
||||||
} assetmeshinputaxis_t;
|
} assetmeshinputaxis_t;
|
||||||
|
|
||||||
|
typedef assetmeshinputaxis_t assetmeshloaderinput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_MESH_LOADING_STATE_INITIAL,
|
||||||
|
ASSET_MESH_LOADING_STATE_READ_FILE,
|
||||||
|
ASSET_MESH_LOADING_STATE_CREATE_MESH,
|
||||||
|
ASSET_MESH_LOADING_STATE_DONE
|
||||||
|
} assetmeshloadingstate_t;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
mesh_t *outMesh;
|
assetfile_t file;
|
||||||
meshvertex_t **outVertices;
|
assetmeshloadingstate_t state;
|
||||||
assetmeshinputaxis_t inputAxis;
|
uint32_t triangleCount;
|
||||||
|
} assetmeshloaderloading_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
mesh_t mesh;
|
||||||
|
meshvertex_t *vertices;
|
||||||
} assetmeshoutput_t;
|
} assetmeshoutput_t;
|
||||||
|
|
||||||
#pragma pack(push, 1)
|
#pragma pack(push, 1)
|
||||||
@@ -36,26 +53,6 @@ typedef struct {
|
|||||||
|
|
||||||
assertStructSize(assetmeshstltriangle_t, 50);
|
assertStructSize(assetmeshstltriangle_t, 50);
|
||||||
|
|
||||||
/**
|
errorret_t assetMeshLoaderAsync(assetloading_t *loading);
|
||||||
* Loader for mesh assets.
|
errorret_t assetMeshLoaderSync(assetloading_t *loading);
|
||||||
*
|
errorret_t assetMeshDispose(assetentry_t *entry);
|
||||||
* @param file Asset file to load the mesh from.
|
|
||||||
* @return Any error that occurs during loading.
|
|
||||||
*/
|
|
||||||
errorret_t assetMeshLoader(assetfile_t *file);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handler for mesh assets.
|
|
||||||
*
|
|
||||||
* @param file Asset file to load the mesh from.
|
|
||||||
* @param outMesh Output mesh to load the data into.
|
|
||||||
* @param outVertices Output pointer to the vertex data, used for cleanup.
|
|
||||||
* @param inputAxis The axis orientation of the input mesh data.
|
|
||||||
* @return Any error that occurs during loading.
|
|
||||||
*/
|
|
||||||
errorret_t assetMeshLoad(
|
|
||||||
const char_t *path,
|
|
||||||
mesh_t *outMesh,
|
|
||||||
meshvertex_t **outVertices,
|
|
||||||
const assetmeshinputaxis_t inputAxis
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -11,6 +11,8 @@
|
|||||||
#include "stb_image.h"
|
#include "stb_image.h"
|
||||||
#include "log/log.h"
|
#include "log/log.h"
|
||||||
#include "util/endian.h"
|
#include "util/endian.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
stbi_io_callbacks ASSET_TEXTURE_STB_CALLBACKS = {
|
stbi_io_callbacks ASSET_TEXTURE_STB_CALLBACKS = {
|
||||||
.read = assetTextureReader,
|
.read = assetTextureReader,
|
||||||
@@ -25,7 +27,7 @@ int assetTextureReader(void *user, char *data, int size) {
|
|||||||
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
|
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
|
||||||
|
|
||||||
errorret_t ret = assetFileRead(file, data, (size_t)size);
|
errorret_t ret = assetFileRead(file, data, (size_t)size);
|
||||||
if(ret.code != ERROR_OK) {
|
if(errorIsNotOk(ret)) {
|
||||||
errorCatch(errorPrint(ret));
|
errorCatch(errorPrint(ret));
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
@@ -38,7 +40,7 @@ void assetTextureSkipper(void *user, int n) {
|
|||||||
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
|
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
|
||||||
|
|
||||||
errorret_t ret = assetFileRead(file, NULL, (size_t)n);
|
errorret_t ret = assetFileRead(file, NULL, (size_t)n);
|
||||||
if(ret.code != ERROR_OK) {
|
if(errorIsNotOk(ret)) {
|
||||||
errorCatch(errorPrint(ret));
|
errorCatch(errorPrint(ret));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,66 +52,118 @@ int assetTextureEOF(void *user) {
|
|||||||
return file->position >= file->size;
|
return file->position >= file->size;
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetTextureLoader(assetfile_t *file) {
|
errorret_t assetTextureLoaderAsync(assetloading_t *loading) {
|
||||||
assertNotNull(file, "Asset file cannot be NULL.");
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
assertNotNull(file->params, "Asset file parameters cannot be NULL.");
|
assertNotMainThread("Should be called from an async thread.");
|
||||||
assertNotNull(file->output, "Asset file output cannot be NULL.");
|
|
||||||
|
|
||||||
assettextureloaderparams_t *p = (assettextureloaderparams_t*)file->params;
|
// Only care about loading pixels.
|
||||||
assertNotNull(p, "Asset texture loader parameters cannot be NULL.");
|
if(loading->loading.texture.state != ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS){
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init the file
|
||||||
|
assertNull(
|
||||||
|
loading->loading.texture.data, "Pixels already defined?"
|
||||||
|
);
|
||||||
|
|
||||||
|
assetfile_t *file = &loading->loading.texture.file;
|
||||||
|
assetLoaderErrorChain(loading, assetFileInit(
|
||||||
|
file,
|
||||||
|
loading->entry->name,
|
||||||
|
NULL,
|
||||||
|
&loading->entry->data.texture
|
||||||
|
));
|
||||||
|
assetLoaderErrorChain(loading, assetFileOpen(file));
|
||||||
|
|
||||||
|
// Determine channels
|
||||||
int channelsDesired;
|
int channelsDesired;
|
||||||
switch(p->format) {
|
switch(loading->entry->inputData.texture) {
|
||||||
case TEXTURE_FORMAT_RGBA:
|
case TEXTURE_FORMAT_RGBA:
|
||||||
channelsDesired = 4;
|
channelsDesired = 4;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
errorThrow("Bad texture format.");
|
assetLoaderErrorThrow(loading, "Bad texture format.");
|
||||||
}
|
}
|
||||||
|
|
||||||
int width, height, channels;
|
// Load image pixels.
|
||||||
errorChain(assetFileOpen(file));
|
loading->loading.texture.data = stbi_load_from_callbacks(
|
||||||
uint8_t *data = stbi_load_from_callbacks(
|
|
||||||
&ASSET_TEXTURE_STB_CALLBACKS,
|
&ASSET_TEXTURE_STB_CALLBACKS,
|
||||||
file,
|
file,
|
||||||
&width,
|
&loading->loading.texture.width,
|
||||||
&height,
|
&loading->loading.texture.height,
|
||||||
&channels,
|
&loading->loading.texture.channels,
|
||||||
channelsDesired
|
channelsDesired
|
||||||
);
|
);
|
||||||
errorChain(assetFileClose(file));
|
|
||||||
|
|
||||||
if(data == NULL) {
|
// Close out the file.
|
||||||
|
assetLoaderErrorChain(loading, assetFileClose(file));
|
||||||
|
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||||
|
|
||||||
|
// Ensure we loaded correctly.
|
||||||
|
if(loading->loading.texture.data == NULL) {
|
||||||
const char_t *errorStr = stbi_failure_reason();
|
const char_t *errorStr = stbi_failure_reason();
|
||||||
errorThrow("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
|
||||||
if(!isHostLittleEndian()) {
|
if(!isHostLittleEndian()) {
|
||||||
stbi__vertical_flip(data, width, height, channelsDesired);
|
stbi__vertical_flip(
|
||||||
|
loading->loading.texture.data,
|
||||||
|
loading->loading.texture.width,
|
||||||
|
loading->loading.texture.height,
|
||||||
|
loading->loading.texture.channels
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
errorChain(textureInit(
|
loading->loading.texture.state = ASSET_TEXTURE_LOADING_STATE_CREATE_TEXTURE;
|
||||||
(texture_t*)file->output,
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
(int32_t)width, (int32_t)height,
|
|
||||||
p->format,
|
|
||||||
(texturedata_t){
|
|
||||||
.rgbaColors = (color_t*)data
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
stbi_image_free(data);
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetTextureLoad(
|
errorret_t assetTextureLoaderSync(assetloading_t *loading) {
|
||||||
const char_t *path,
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
texture_t *out,
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
const textureformat_t format
|
|
||||||
) {
|
switch(loading->loading.texture.state) {
|
||||||
assettextureloaderparams_t params = {
|
case ASSET_TEXTURE_LOADING_STATE_INITIAL:
|
||||||
.format = format
|
loading->loading.texture.state = ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS;
|
||||||
};
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
return assetLoad(path, assetTextureLoader, ¶ms, out);
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_TEXTURE_LOADING_STATE_CREATE_TEXTURE:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the texture.
|
||||||
|
assertNotNull(
|
||||||
|
loading->loading.texture.data, "Pixels should have been loaded by now."
|
||||||
|
);
|
||||||
|
|
||||||
|
assetLoaderErrorChain(loading, textureInit(
|
||||||
|
(texture_t*)&loading->entry->data.texture,
|
||||||
|
loading->loading.texture.width,
|
||||||
|
loading->loading.texture.height,
|
||||||
|
loading->entry->inputData.texture,
|
||||||
|
(texturedata_t){
|
||||||
|
.rgbaColors = (color_t*)loading->loading.texture.data
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
// Free the pixels.
|
||||||
|
stbi_image_free(loading->loading.texture.data);
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetTextureDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
return textureDispose(&entry->data.texture);
|
||||||
}
|
}
|
||||||
@@ -6,12 +6,29 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/asset.h"
|
#include "asset/assetfile.h"
|
||||||
#include "display/texture/texture.h"
|
#include "display/texture/texture.h"
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
typedef textureformat_t assettextureloaderinput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_TEXTURE_LOADING_STATE_INITIAL,
|
||||||
|
ASSET_TEXTURE_LOADING_STATE_LOAD_PIXELS,
|
||||||
|
ASSET_TEXTURE_LOADING_STATE_CREATE_TEXTURE,
|
||||||
|
ASSET_TEXTURE_LOADING_STATE_DONE
|
||||||
|
} assettextureloadingstate_t;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
textureformat_t format;
|
assetfile_t file;
|
||||||
} assettextureloaderparams_t;
|
assettextureloadingstate_t state;
|
||||||
|
|
||||||
|
int channels, width, height;
|
||||||
|
uint8_t *data;
|
||||||
|
} assettextureloaderloading_t;
|
||||||
|
|
||||||
|
typedef texture_t assettextureoutput_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* STB image read callback for asset files.
|
* STB image read callback for asset files.
|
||||||
@@ -23,28 +40,42 @@ typedef struct {
|
|||||||
*/
|
*/
|
||||||
int assetTextureReader(void *user, char *data, int size);
|
int assetTextureReader(void *user, char *data, int size);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STB image skip callback for asset files.
|
||||||
|
*
|
||||||
|
* @param user User data passed to the callback, should be an assetfile_t*.
|
||||||
|
* @param n Number of bytes to skip in the file.
|
||||||
|
*/
|
||||||
void assetTextureSkipper(void *user, int n);
|
void assetTextureSkipper(void *user, int n);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STB image EOF callback for asset files.
|
||||||
|
*
|
||||||
|
* @param user User data passed to the callback, should be an assetfile_t*.
|
||||||
|
* @return Non-zero if end of file has been reached, zero otherwise.
|
||||||
|
*/
|
||||||
int assetTextureEOF(void *user);
|
int assetTextureEOF(void *user);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handler for texture assets.
|
* Synchronous loader for texture assets.
|
||||||
*
|
*
|
||||||
* @param file Asset file to load the texture from.
|
* @param loading Loading information for the asset being loaded.
|
||||||
* @return Any error that occurs during loading.
|
* @return Error code indicating success or failure of the load operation.
|
||||||
*/
|
*/
|
||||||
errorret_t assetTextureLoader(assetfile_t *file);
|
errorret_t assetTextureLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads a texture from the specified path.
|
* Synchronous loader for texture assets.
|
||||||
*
|
*
|
||||||
* @param path Path to the texture asset.
|
* @param loading Loading information for the asset being loaded.
|
||||||
* @param out Output texture to load into.
|
* @return Error code indicating success or failure of the load operation.
|
||||||
* @param format Format of the texture to load.
|
|
||||||
* @return Any error that occurs during loading.
|
|
||||||
*/
|
*/
|
||||||
errorret_t assetTextureLoad(
|
errorret_t assetTextureLoaderSync(assetloading_t *loading);
|
||||||
const char_t *path,
|
|
||||||
texture_t *out,
|
/**
|
||||||
const textureformat_t format
|
* Disposer for texture assets.
|
||||||
);
|
*
|
||||||
|
* @param entry Asset entry containing the texture to dispose.
|
||||||
|
* @return Error code indicating success or failure of the dispose operation.
|
||||||
|
*/
|
||||||
|
errorret_t assetTextureDispose(assetentry_t *entry);
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2026 Dominic Masters
|
* Copyright (c) 2026 Dominic Masters
|
||||||
*
|
*
|
||||||
* This software is released under the MIT License.
|
* This software is released under the MIT License.
|
||||||
* https://opensource.org/licenses/MIT
|
* https://opensource.org/licenses/MIT
|
||||||
*/
|
*/
|
||||||
@@ -9,72 +9,111 @@
|
|||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
#include "util/endian.h"
|
#include "util/endian.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
errorret_t assetTilesetLoader(assetfile_t *file) {
|
errorret_t assetTilesetLoaderAsync(assetloading_t *loading) {
|
||||||
assertNotNull(file, "Asset file pointer for tileset loader is null.");
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertNotMainThread("Should be called from an async thread.");
|
||||||
|
|
||||||
tileset_t *out = (tileset_t *)file->output;
|
if(loading->loading.tileset.state != ASSET_TILESET_LOADING_STATE_READ_FILE) {
|
||||||
assertNotNull(out, "Output pointer for tileset loader is null.");
|
errorOk();
|
||||||
|
|
||||||
uint8_t *entire = memoryAllocate(file->size);
|
|
||||||
errorChain(assetFileOpen(file));
|
|
||||||
errorChain(assetFileRead(file, entire, file->size));
|
|
||||||
errorChain(assetFileClose(file));
|
|
||||||
assertTrue(file->lastRead == file->size, "Failed to read entire file.");
|
|
||||||
|
|
||||||
|
|
||||||
if(
|
|
||||||
entire[0] != 'D' ||
|
|
||||||
entire[1] != 'T' ||
|
|
||||||
entire[2] != 'F'
|
|
||||||
) {
|
|
||||||
errorThrow("Invalid tileset header");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if(entire[3] != 0x00) {
|
assertNull(loading->loading.tileset.data, "Data already defined?");
|
||||||
errorThrow("Unsupported tileset version");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fix endianness
|
assetfile_t *file = &loading->loading.tileset.file;
|
||||||
|
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL));
|
||||||
|
|
||||||
out->tileWidth = endianLittleToHost16(*(uint16_t *)(entire + 4));
|
uint8_t *data = memoryAllocate(file->size);
|
||||||
out->tileHeight = endianLittleToHost16(*(uint16_t *)(entire + 6));
|
assetLoaderErrorChain(loading, assetFileOpen(file));
|
||||||
out->columns = endianLittleToHost16(*(uint16_t *)(entire + 8));
|
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size));
|
||||||
out->rows = endianLittleToHost16(*(uint16_t *)(entire + 10));
|
assetLoaderErrorChain(loading, assetFileClose(file));
|
||||||
// out->right = endianLittleToHost16(*(uint16_t *)(entire + 12));
|
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||||
// out->bottom = endianLittleToHost16(*(uint16_t *)(entire + 14));
|
assertTrue(file->lastRead == file->size, "Failed to read entire tileset file.");
|
||||||
|
|
||||||
if(out->tileWidth == 0) {
|
|
||||||
errorThrow("Tile width cannot be 0");
|
|
||||||
}
|
|
||||||
if(out->tileHeight == 0) {
|
|
||||||
errorThrow("Tile height cannot be 0");
|
|
||||||
}
|
|
||||||
if(out->columns == 0) {
|
|
||||||
errorThrow("Column count cannot be 0");
|
|
||||||
}
|
|
||||||
if(out->rows == 0) {
|
|
||||||
errorThrow("Row count cannot be 0");
|
|
||||||
}
|
|
||||||
|
|
||||||
out->uv[0] = endianLittleToHostFloat(*(float *)(entire + 16));
|
|
||||||
out->uv[1] = endianLittleToHostFloat(*(float *)(entire + 20));
|
|
||||||
|
|
||||||
if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) {
|
|
||||||
errorThrow("Invalid v0 value in tileset");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Setup tileset
|
|
||||||
out->tileCount = out->columns * out->rows;
|
|
||||||
|
|
||||||
memoryFree(entire);
|
|
||||||
|
|
||||||
|
loading->loading.tileset.data = data;
|
||||||
|
loading->loading.tileset.state = ASSET_TILESET_LOADING_STATE_PARSE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetTilesetLoad(
|
errorret_t assetTilesetLoaderSync(assetloading_t *loading) {
|
||||||
const char_t *path,
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
tileset_t *out
|
assertTrue(loading->type == ASSET_LOADER_TYPE_TILESET, "Invalid type.");
|
||||||
) {
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
return assetLoad(path, assetTilesetLoader, NULL, out);
|
|
||||||
}
|
switch(loading->loading.tileset.state) {
|
||||||
|
case ASSET_TILESET_LOADING_STATE_INITIAL:
|
||||||
|
loading->loading.tileset.state = ASSET_TILESET_LOADING_STATE_READ_FILE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_TILESET_LOADING_STATE_PARSE:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t *data = loading->loading.tileset.data;
|
||||||
|
assertNotNull(data, "Tileset data should have been loaded by now.");
|
||||||
|
|
||||||
|
tileset_t *out = &loading->entry->data.tileset;
|
||||||
|
|
||||||
|
if(data[0] != 'D' || data[1] != 'T' || data[2] != 'F') {
|
||||||
|
memoryFree(data);
|
||||||
|
assetLoaderErrorThrow(loading, "Invalid tileset header");
|
||||||
|
}
|
||||||
|
|
||||||
|
if(data[3] != 0x00) {
|
||||||
|
memoryFree(data);
|
||||||
|
assetLoaderErrorThrow(loading, "Unsupported tileset version");
|
||||||
|
}
|
||||||
|
|
||||||
|
out->tileWidth = endianLittleToHost16(*(uint16_t *)(data + 4));
|
||||||
|
out->tileHeight = endianLittleToHost16(*(uint16_t *)(data + 6));
|
||||||
|
out->columns = endianLittleToHost16(*(uint16_t *)(data + 8));
|
||||||
|
out->rows = endianLittleToHost16(*(uint16_t *)(data + 10));
|
||||||
|
|
||||||
|
if(out->tileWidth == 0) {
|
||||||
|
memoryFree(data);
|
||||||
|
assetLoaderErrorThrow(loading, "Tile width cannot be 0");
|
||||||
|
}
|
||||||
|
if(out->tileHeight == 0) {
|
||||||
|
memoryFree(data);
|
||||||
|
assetLoaderErrorThrow(loading, "Tile height cannot be 0");
|
||||||
|
}
|
||||||
|
if(out->columns == 0) {
|
||||||
|
memoryFree(data);
|
||||||
|
assetLoaderErrorThrow(loading, "Column count cannot be 0");
|
||||||
|
}
|
||||||
|
if(out->rows == 0) {
|
||||||
|
memoryFree(data);
|
||||||
|
assetLoaderErrorThrow(loading, "Row count cannot be 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
out->uv[0] = endianLittleToHostFloat(*(float *)(data + 16));
|
||||||
|
out->uv[1] = endianLittleToHostFloat(*(float *)(data + 20));
|
||||||
|
|
||||||
|
if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) {
|
||||||
|
memoryFree(data);
|
||||||
|
assetLoaderErrorThrow(loading, "Invalid v0 value in tileset");
|
||||||
|
}
|
||||||
|
|
||||||
|
out->tileCount = out->columns * out->rows;
|
||||||
|
memoryFree(data);
|
||||||
|
loading->loading.tileset.data = NULL;
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetTilesetDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Entry cannot be NULL");
|
||||||
|
assertTrue(entry->type == ASSET_LOADER_TYPE_TILESET, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,30 +1,60 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2026 Dominic Masters
|
* Copyright (c) 2026 Dominic Masters
|
||||||
*
|
*
|
||||||
* This software is released under the MIT License.
|
* This software is released under the MIT License.
|
||||||
* https://opensource.org/licenses/MIT
|
* https://opensource.org/licenses/MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/asset.h"
|
#include "asset/assetfile.h"
|
||||||
#include "display/texture/tileset.h"
|
#include "display/texture/tileset.h"
|
||||||
|
|
||||||
/**
|
typedef struct assetloading_s assetloading_t;
|
||||||
* Handler for tileset assets.
|
typedef struct assetentry_s assetentry_t;
|
||||||
*
|
|
||||||
* @param file Asset file to load the tileset from.
|
typedef struct {
|
||||||
* @return Any error that occurs during loading.
|
void *nothing;
|
||||||
*/
|
} assettilesetloaderinput_t;
|
||||||
errorret_t assetTilesetLoader(assetfile_t *file);
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_TILESET_LOADING_STATE_INITIAL,
|
||||||
|
ASSET_TILESET_LOADING_STATE_READ_FILE,
|
||||||
|
ASSET_TILESET_LOADING_STATE_PARSE,
|
||||||
|
ASSET_TILESET_LOADING_STATE_DONE
|
||||||
|
} assettilesetloadingstate_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetfile_t file;
|
||||||
|
assettilesetloadingstate_t state;
|
||||||
|
|
||||||
|
uint8_t *data;
|
||||||
|
} assettilesetloaderloading_t;
|
||||||
|
|
||||||
|
typedef tileset_t assettilesetoutput_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads a tileset from the specified path.
|
* Asynchronous loader for tileset assets. Reads the raw DTF file bytes into
|
||||||
*
|
* the loading buffer so the sync phase can parse without blocking the main
|
||||||
* @param path Path to the tileset asset.
|
* thread on I/O.
|
||||||
* @param out Output tileset to load into.
|
*
|
||||||
* @return Any error that occurs during loading.
|
* @param loading Loading information for the asset being loaded.
|
||||||
|
* @return Error code indicating success or failure of the load operation.
|
||||||
*/
|
*/
|
||||||
errorret_t assetTilesetLoad(
|
errorret_t assetTilesetLoaderAsync(assetloading_t *loading);
|
||||||
const char_t *path,
|
|
||||||
tileset_t *out
|
/**
|
||||||
);
|
* Synchronous loader for tileset assets. Parses the DTF binary previously
|
||||||
|
* read by the async phase and populates the output tileset_t.
|
||||||
|
*
|
||||||
|
* @param loading Loading information for the asset being loaded.
|
||||||
|
* @return Error code indicating success or failure of the load operation.
|
||||||
|
*/
|
||||||
|
errorret_t assetTilesetLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposer for tileset assets.
|
||||||
|
*
|
||||||
|
* @param entry Asset entry containing the tileset to dispose.
|
||||||
|
* @return Error code indicating success or failure of the dispose operation.
|
||||||
|
*/
|
||||||
|
errorret_t assetTilesetDispose(assetentry_t *entry);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2026 Dominic Masters
|
* Copyright (c) 2026 Dominic Masters
|
||||||
*
|
*
|
||||||
* This software is released under the MIT License.
|
* This software is released under the MIT License.
|
||||||
* https://opensource.org/licenses/MIT
|
* https://opensource.org/licenses/MIT
|
||||||
*/
|
*/
|
||||||
@@ -8,46 +8,86 @@
|
|||||||
#include "assetjsonloader.h"
|
#include "assetjsonloader.h"
|
||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
|
||||||
errorret_t assetJsonLoadFileToDoc(assetfile_t *file, yyjson_doc **outDoc) {
|
errorret_t assetJsonLoaderAsync(assetloading_t *loading) {
|
||||||
assertNotNull(file, "Asset file pointer for JSON loader is null.");
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
assertNotNull(outDoc, "Output pointer for JSON loader is null.");
|
assertNotMainThread("Async loader should not be on main thread.");
|
||||||
|
|
||||||
if(file->size > ASSET_JSON_FILE_SIZE_MAX) {
|
if(loading->loading.json.state != ASSET_JSON_LOADING_STATE_READ_FILE) {
|
||||||
errorThrow("JSON exceeds maximum allowed size");
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create buffer
|
assertNull(loading->loading.json.buffer, "Buffer already defined?");
|
||||||
uint8_t *buffer = memoryAllocate(file->size);
|
|
||||||
|
|
||||||
errorChain(assetFileOpen(file));
|
assetfile_t *file = &loading->loading.json.file;
|
||||||
|
assetLoaderErrorChain(loading, assetFileInit(file, loading->entry->name, NULL, NULL));
|
||||||
|
|
||||||
// Read entire file
|
if(file->size > ASSET_JSON_FILE_SIZE_MAX) {
|
||||||
errorChain(assetFileRead(file, buffer, file->size));
|
assetLoaderErrorThrow(loading, "JSON exceeds maximum allowed size");
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t fileSize = (size_t)file->size;
|
||||||
|
uint8_t *buffer = memoryAllocate(fileSize);
|
||||||
|
assetLoaderErrorChain(loading, assetFileOpen(file));
|
||||||
|
assetLoaderErrorChain(loading, assetFileRead(file, buffer, fileSize));
|
||||||
assertTrue(file->lastRead == file->size, "Failed to read entire JSON file.");
|
assertTrue(file->lastRead == file->size, "Failed to read entire JSON file.");
|
||||||
|
assetLoaderErrorChain(loading, assetFileClose(file));
|
||||||
|
assetLoaderErrorChain(loading, assetFileDispose(file));
|
||||||
|
|
||||||
errorChain(assetFileClose(file));
|
loading->loading.json.buffer = buffer;
|
||||||
|
loading->loading.json.size = fileSize;
|
||||||
*outDoc = yyjson_read(
|
loading->loading.json.state = ASSET_JSON_LOADING_STATE_PARSE;
|
||||||
buffer,
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
file->size,
|
|
||||||
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
|
|
||||||
);
|
|
||||||
memoryFree(buffer);
|
|
||||||
|
|
||||||
if(!*outDoc) errorThrow("Failed to parse JSON");
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetJsonLoader(assetfile_t *file) {
|
errorret_t assetJsonLoaderSync(assetloading_t *loading) {
|
||||||
yyjson_doc **outDoc = (yyjson_doc **)file->output;
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
assertNotNull(outDoc, "Output pointer for JSON loader is null.");
|
assertTrue(loading->type == ASSET_LOADER_TYPE_JSON, "Invalid type.");
|
||||||
return assetJsonLoadFileToDoc(file, outDoc);
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
switch(loading->loading.json.state) {
|
||||||
|
case ASSET_JSON_LOADING_STATE_INITIAL:
|
||||||
|
loading->loading.json.state = ASSET_JSON_LOADING_STATE_READ_FILE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_JSON_LOADING_STATE_PARSE:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t *buffer = loading->loading.json.buffer;
|
||||||
|
assertNotNull(buffer, "JSON buffer should have been loaded by now.");
|
||||||
|
|
||||||
|
loading->entry->data.json = yyjson_read(
|
||||||
|
(char *)buffer,
|
||||||
|
loading->loading.json.size,
|
||||||
|
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
|
||||||
|
);
|
||||||
|
memoryFree(buffer);
|
||||||
|
loading->loading.json.buffer = NULL;
|
||||||
|
|
||||||
|
if(!loading->entry->data.json) {
|
||||||
|
assetLoaderErrorThrow(loading, "Failed to parse JSON");
|
||||||
|
}
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetJsonLoad(
|
errorret_t assetJsonDispose(assetentry_t *entry) {
|
||||||
const char_t *path,
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
yyjson_doc **outDoc
|
assertTrue(entry->type == ASSET_LOADER_TYPE_JSON, "Invalid type.");
|
||||||
) {
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
return assetLoad(path, assetJsonLoader, NULL, outDoc);
|
|
||||||
}
|
yyjson_doc_free(entry->data.json);
|
||||||
|
entry->data.json = NULL;
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,45 +1,37 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2026 Dominic Masters
|
* Copyright (c) 2026 Dominic Masters
|
||||||
*
|
*
|
||||||
* This software is released under the MIT License.
|
* This software is released under the MIT License.
|
||||||
* https://opensource.org/licenses/MIT
|
* https://opensource.org/licenses/MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/asset.h"
|
#include "asset/assetfile.h"
|
||||||
#include "yyjson.h"
|
#include "yyjson.h"
|
||||||
|
|
||||||
#define ASSET_JSON_FILE_SIZE_MAX 1024*256
|
#define ASSET_JSON_FILE_SIZE_MAX 1024*256
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
typedef struct { void *nothing; } assetjsonloaderinput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_JSON_LOADING_STATE_INITIAL,
|
||||||
|
ASSET_JSON_LOADING_STATE_READ_FILE,
|
||||||
|
ASSET_JSON_LOADING_STATE_PARSE,
|
||||||
|
ASSET_JSON_LOADING_STATE_DONE
|
||||||
|
} assetjsonloadingstate_t;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
void *nothing;
|
assetfile_t file;
|
||||||
} assetjsonloaderparams_t;
|
assetjsonloadingstate_t state;
|
||||||
|
uint8_t *buffer;
|
||||||
|
size_t size;
|
||||||
|
} assetjsonloaderloading_t;
|
||||||
|
|
||||||
/**
|
typedef yyjson_doc * assetjsonoutput_t;
|
||||||
* Loads a JSON document from the specified asset file.
|
|
||||||
*
|
|
||||||
* @param file Asset file to load the JSON document from.
|
|
||||||
* @param outDoc Pointer to store the loaded JSON document.
|
|
||||||
* @return Any error that occurs during loading.
|
|
||||||
*/
|
|
||||||
errorret_t assetJsonLoadFileToDoc(assetfile_t *file, yyjson_doc **outDoc);
|
|
||||||
|
|
||||||
/**
|
errorret_t assetJsonLoaderAsync(assetloading_t *loading);
|
||||||
* Handler for locale assets.
|
errorret_t assetJsonLoaderSync(assetloading_t *loading);
|
||||||
*
|
errorret_t assetJsonDispose(assetentry_t *entry);
|
||||||
* @param file Asset file to load the locale from.
|
|
||||||
* @return Any error that occurs during loading.
|
|
||||||
*/
|
|
||||||
errorret_t assetJsonLoader(assetfile_t *file);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Loads a locale from the specified path.
|
|
||||||
*
|
|
||||||
* @param path Path to the locale asset.
|
|
||||||
* @param outDoc Pointer to store the loaded JSON document.
|
|
||||||
* @return Any error that occurs during loading.
|
|
||||||
*/
|
|
||||||
errorret_t assetJsonLoad(
|
|
||||||
const char_t *path,
|
|
||||||
yyjson_doc **outDoc
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -11,38 +11,65 @@
|
|||||||
#include "util/string.h"
|
#include "util/string.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
|
|
||||||
errorret_t assetLocaleFileInit(
|
#include "asset/loader/assetloading.h"
|
||||||
assetlocalefile_t *localeFile,
|
#include "asset/loader/assetentry.h"
|
||||||
const char_t *path
|
|
||||||
) {
|
errorret_t assetLocaleLoaderAsync(assetloading_t *loading) {
|
||||||
assertNotNull(localeFile, "Locale file cannot be NULL.");
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
assertNotNull(path, "Locale file path cannot be NULL.");
|
assertNotMainThread("Async loader should not be on main thread.");
|
||||||
|
|
||||||
|
if(loading->loading.locale.state != ASSET_LOCALE_LOADER_STATE_LOAD_HEADER) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
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, assetFileOpen(&localeFile->file));
|
||||||
|
|
||||||
// Init the asset file.
|
|
||||||
errorChain(assetFileInit(&localeFile->file, path, NULL, NULL));
|
|
||||||
|
|
||||||
// Open the file handle
|
|
||||||
errorChain(assetFileOpen(&localeFile->file));
|
|
||||||
|
|
||||||
// Get the blank key, this is basically the header info for po files
|
|
||||||
char_t buffer[1024];
|
char_t buffer[1024];
|
||||||
errorChain(assetLocaleGetString(localeFile, "", 0, buffer, sizeof(buffer)));
|
assetLoaderErrorChain(loading, assetLocaleGetString(localeFile, "", 0, buffer, sizeof(buffer)));
|
||||||
errorChain(assetLocaleParseHeader(localeFile, buffer, sizeof(buffer)));
|
assetLoaderErrorChain(loading, assetLocaleParseHeader(localeFile, buffer, sizeof(buffer)));
|
||||||
|
|
||||||
|
loading->loading.locale.state = ASSET_LOCALE_LOADER_STATE_DONE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t assetLocaleFileDispose(assetlocalefile_t *localeFile) {
|
errorret_t assetLocaleLoaderSync(assetloading_t *loading) {
|
||||||
assertNotNull(localeFile, "Locale file cannot be NULL.");
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertTrue(loading->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
switch(loading->loading.locale.state) {
|
||||||
|
case ASSET_LOCALE_LOADER_STATE_INITIAL:
|
||||||
|
loading->loading.locale.state = ASSET_LOCALE_LOADER_STATE_LOAD_HEADER;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_LOCALE_LOADER_STATE_DONE:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetLocaleDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
|
assertTrue(entry->type == ASSET_LOADER_TYPE_LOCALE, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
assetlocalefile_t *localeFile = &entry->data.locale;
|
||||||
errorChain(assetFileClose(&localeFile->file));
|
errorChain(assetFileClose(&localeFile->file));
|
||||||
errorChain(assetFileDispose(&localeFile->file));
|
return assetFileDispose(&localeFile->file);
|
||||||
|
|
||||||
errorOk();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// These functions probably need some cleaning;
|
||||||
errorret_t assetLocaleParseHeader(
|
errorret_t assetLocaleParseHeader(
|
||||||
assetlocalefile_t *localeFile,
|
assetlocalefile_t *localeFile,
|
||||||
char_t *headerBuffer,
|
char_t *headerBuffer,
|
||||||
@@ -307,16 +334,24 @@ errorret_t assetLocaleLineSkipBlanks(
|
|||||||
while(!reader->eof) {
|
while(!reader->eof) {
|
||||||
// Skip blank lines
|
// Skip blank lines
|
||||||
if(lineBuffer[0] == '\0') {
|
if(lineBuffer[0] == '\0') {
|
||||||
errorChain(assetFileLineReaderNext(reader));
|
errorret_t r = assetFileLineReaderNext(reader);
|
||||||
|
if(errorIsNotOk(r)) {
|
||||||
|
errorCatch(r);
|
||||||
|
break;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip comment lines
|
// Skip comment lines
|
||||||
if(lineBuffer[0] == '#') {
|
if(lineBuffer[0] == '#') {
|
||||||
errorChain(assetFileLineReaderNext(reader));
|
errorret_t r = assetFileLineReaderNext(reader);
|
||||||
|
if(errorIsNotOk(r)) {
|
||||||
|
errorCatch(r);
|
||||||
|
break;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Is line only spaces?
|
// Is line only spaces?
|
||||||
size_t lineLength = strlen((char_t *)lineBuffer);
|
size_t lineLength = strlen((char_t *)lineBuffer);
|
||||||
size_t i;
|
size_t i;
|
||||||
@@ -329,7 +364,11 @@ errorret_t assetLocaleLineSkipBlanks(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(onlySpaces) {
|
if(onlySpaces) {
|
||||||
errorChain(assetFileLineReaderNext(reader));
|
errorret_t r = assetFileLineReaderNext(reader);
|
||||||
|
if(errorIsNotOk(r)) {
|
||||||
|
errorCatch(r);
|
||||||
|
break;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -365,10 +404,18 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
|
|
||||||
// Now start buffering lines out
|
// Now start buffering lines out
|
||||||
while(!reader->eof) {
|
while(!reader->eof) {
|
||||||
errorChain(assetFileLineReaderNext(reader));
|
errorret_t r = assetFileLineReaderNext(reader);
|
||||||
|
if(errorIsNotOk(r)) {
|
||||||
|
errorCatch(r);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// Skip blank lines
|
// Skip blank lines
|
||||||
errorChain(assetLocaleLineSkipBlanks(reader, lineBuffer));
|
r = assetLocaleLineSkipBlanks(reader, lineBuffer);
|
||||||
|
if(errorIsNotOk(r)) {
|
||||||
|
errorCatch(r);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// Skip starting spaces
|
// Skip starting spaces
|
||||||
char_t *ptr = (char_t *)lineBuffer;
|
char_t *ptr = (char_t *)lineBuffer;
|
||||||
@@ -593,7 +640,7 @@ errorret_t assetLocaleGetStringWithVA(
|
|||||||
tempBuffer,
|
tempBuffer,
|
||||||
bufferSize
|
bufferSize
|
||||||
);
|
);
|
||||||
if(ret.code != ERROR_OK) {
|
if(errorIsNotOk(ret)) {
|
||||||
memoryFree(tempBuffer);
|
memoryFree(tempBuffer);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
@@ -641,7 +688,7 @@ errorret_t assetLocaleGetStringWithArgs(
|
|||||||
format,
|
format,
|
||||||
bufferSize
|
bufferSize
|
||||||
);
|
);
|
||||||
if(ret.code != ERROR_OK) {
|
if(errorIsNotOk(ret)) {
|
||||||
memoryFree(format);
|
memoryFree(format);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,40 @@
|
|||||||
/**
|
/**
|
||||||
* Copyright (c) 2026 Dominic Masters
|
* Copyright (c) 2026 Dominic Masters
|
||||||
*
|
*
|
||||||
* This software is released under the MIT License.
|
* This software is released under the MIT License.
|
||||||
* https://opensource.org/licenses/MIT
|
* https://opensource.org/licenses/MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/asset.h"
|
#include "asset/assetfile.h"
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
/** Input passed to the locale loader — currently unused. */
|
||||||
|
typedef struct { void *nothing; } assetlocaleloaderinput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_LOCALE_LOADER_STATE_INITIAL,
|
||||||
|
ASSET_LOCALE_LOADER_STATE_LOAD_HEADER,
|
||||||
|
ASSET_LOCALE_LOADER_STATE_DONE
|
||||||
|
} assetlocaleloaderstate_t;
|
||||||
|
|
||||||
|
/** Per-slot scratch data used while the locale file is loading. */
|
||||||
|
typedef struct {
|
||||||
|
assetlocaleloaderstate_t state;
|
||||||
|
} assetlocaleloaderloading_t;
|
||||||
|
|
||||||
|
/** Maximum number of distinct plural forms a locale file may declare. */
|
||||||
#define ASSET_LOCALE_FILE_PLURAL_FORM_COUNT 6
|
#define ASSET_LOCALE_FILE_PLURAL_FORM_COUNT 6
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Comparison operator used in a plural-form expression.
|
||||||
|
*
|
||||||
|
* Each condition in the plural-form header is evaluated as
|
||||||
|
* `n <op> value`
|
||||||
|
* where `n` is the runtime plural count.
|
||||||
|
*/
|
||||||
typedef enum {
|
typedef enum {
|
||||||
ASSET_LOCALE_PLURAL_OP_EQUAL,
|
ASSET_LOCALE_PLURAL_OP_EQUAL,
|
||||||
ASSET_LOCALE_PLURAL_OP_NOT_EQUAL,
|
ASSET_LOCALE_PLURAL_OP_NOT_EQUAL,
|
||||||
@@ -19,13 +44,24 @@ typedef enum {
|
|||||||
ASSET_LOCALE_PLURAL_OP_GREATER_EQUAL
|
ASSET_LOCALE_PLURAL_OP_GREATER_EQUAL
|
||||||
} assetlocalepluraloperation_t;
|
} assetlocalepluraloperation_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discriminator tag for a locale string argument.
|
||||||
|
* @see assetlocalearg_t
|
||||||
|
*/
|
||||||
typedef enum {
|
typedef enum {
|
||||||
ASSET_LOCALE_ARG_STRING,
|
ASSET_LOCALE_ARG_STRING,
|
||||||
ASSET_LOCALE_ARG_INT,
|
ASSET_LOCALE_ARG_INT,
|
||||||
ASSET_LOCALE_ARG_FLOAT
|
ASSET_LOCALE_ARG_FLOAT
|
||||||
} assetlocaleargtype_t;
|
} assetlocaleargtype_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single typed argument for locale string substitution.
|
||||||
|
*
|
||||||
|
* Used with @ref assetLocaleGetStringWithArgs to fill `%s`, `%d`, or `%f`
|
||||||
|
* placeholders inside a translated string.
|
||||||
|
*/
|
||||||
typedef struct {
|
typedef struct {
|
||||||
|
/** Which union member is active. */
|
||||||
assetlocaleargtype_t type;
|
assetlocaleargtype_t type;
|
||||||
union {
|
union {
|
||||||
const char_t *stringValue;
|
const char_t *stringValue;
|
||||||
@@ -34,35 +70,81 @@ typedef struct {
|
|||||||
};
|
};
|
||||||
} assetlocalearg_t;
|
} assetlocalearg_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runtime state for an open locale file.
|
||||||
|
*
|
||||||
|
* Loaded once by @ref assetLocaleLoaderSync and kept alive for the lifetime
|
||||||
|
* of the asset entry. The plural-form fields are populated from the PO header
|
||||||
|
* by @ref assetLocaleParseHeader.
|
||||||
|
*
|
||||||
|
* Plural evaluation works as a linear scan over `pluralStateCount - 1`
|
||||||
|
* conditions; if none match, `pluralDefaultIndex` is returned.
|
||||||
|
*/
|
||||||
typedef struct {
|
typedef struct {
|
||||||
|
/** Underlying file handle used to rewind and re-read the PO data. */
|
||||||
assetfile_t file;
|
assetfile_t file;
|
||||||
|
|
||||||
|
/** Comparison operator for each conditional plural clause. */
|
||||||
assetlocalepluraloperation_t pluralOps[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
assetlocalepluraloperation_t pluralOps[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
||||||
|
|
||||||
|
/** Right-hand value for each conditional plural clause. */
|
||||||
int32_t pluralValues[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
int32_t pluralValues[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
||||||
|
|
||||||
|
/** Form index returned when the corresponding condition is true. */
|
||||||
int32_t pluralIndices[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
int32_t pluralIndices[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
|
||||||
|
|
||||||
|
/** Total number of plural forms declared by `nplurals=`. */
|
||||||
uint8_t pluralStateCount;
|
uint8_t pluralStateCount;
|
||||||
|
|
||||||
|
/** Form index used when no conditional clause matches. */
|
||||||
uint8_t pluralDefaultIndex;
|
uint8_t pluralDefaultIndex;
|
||||||
} assetlocalefile_t;
|
} assetlocalefile_t;
|
||||||
|
|
||||||
/**
|
/** Convenience alias — the loaded output type of a locale asset entry. */
|
||||||
* Initialize a locale asset file.
|
typedef assetlocalefile_t assetlocaleoutput_t;
|
||||||
*
|
|
||||||
* @param localeFile The locale file to initialize.
|
|
||||||
* @param path The path to the locale file.
|
|
||||||
* @return An error code if a failure occurs.
|
|
||||||
*/
|
|
||||||
errorret_t assetLocaleFileInit(
|
|
||||||
assetlocalefile_t *localeFile,
|
|
||||||
const char_t *path
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dispose of a locale asset file.
|
* Asynchronous loader callback. Opens the locale file, reads the PO header,
|
||||||
*
|
* and parses plural-form rules. All I/O happens here so the main thread is
|
||||||
* @param localeFile The locale file to dispose of.
|
* not blocked. Sets entry state to `ASSET_ENTRY_STATE_PENDING_SYNC` on
|
||||||
* @return An error code if a failure occurs.
|
* success or `ASSET_ENTRY_STATE_ERROR` on failure.
|
||||||
|
*
|
||||||
|
* @param loading The loading slot for this asset entry.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
*/
|
*/
|
||||||
errorret_t assetLocaleFileDispose(assetlocalefile_t *localeFile);
|
errorret_t assetLocaleLoaderAsync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronous loader callback. Confirms the async phase completed and marks
|
||||||
|
* the entry as `ASSET_ENTRY_STATE_LOADED`.
|
||||||
|
*
|
||||||
|
* @param loading The loading slot for this asset entry.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
|
errorret_t assetLocaleLoaderSync(assetloading_t *loading);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispose callback. Closes the open file handle and zeros the locale data.
|
||||||
|
*
|
||||||
|
* @param entry The asset entry to dispose.
|
||||||
|
* @return OK on success, error otherwise.
|
||||||
|
*/
|
||||||
|
errorret_t assetLocaleDispose(assetentry_t *entry);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses the `Plural-Forms:` line from a PO header string and populates the
|
||||||
|
* plural-form fields of `localeFile`. If no `Plural-Forms:` key is present
|
||||||
|
* the function returns OK without modifying the struct.
|
||||||
|
*
|
||||||
|
* Supports the `nplurals=N; plural=(<expr>);` syntax where `<expr>` is a
|
||||||
|
* chain of `n <op> value ? index : ...` ternary conditions ending with a
|
||||||
|
* fallback index.
|
||||||
|
*
|
||||||
|
* @param localeFile Struct whose plural fields will be filled in.
|
||||||
|
* @param headerBuffer The raw PO header string (msgstr of msgid "").
|
||||||
|
* @param headerBufferSize Size of `headerBuffer` in bytes.
|
||||||
|
* @return OK on success, error if the plural expression is malformed.
|
||||||
|
*/
|
||||||
errorret_t assetLocaleParseHeader(
|
errorret_t assetLocaleParseHeader(
|
||||||
assetlocalefile_t *localeFile,
|
assetlocalefile_t *localeFile,
|
||||||
char_t *headerBuffer,
|
char_t *headerBuffer,
|
||||||
@@ -70,11 +152,29 @@ errorret_t assetLocaleParseHeader(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Skips blank lines and comment lines in the line reader.
|
* Evaluates which plural form index to use for a given count.
|
||||||
*
|
*
|
||||||
* @param reader Line reader to read from.
|
* Walks the conditions stored in `file` in order; returns the index for the
|
||||||
* @param lineBuffer Buffer to use for reading lines.
|
* first condition that matches `pluralCount`. Falls back to
|
||||||
* @return Any error that occurs during skipping.
|
* `file->pluralDefaultIndex` if none match.
|
||||||
|
*
|
||||||
|
* @param file Locale file with parsed plural rules.
|
||||||
|
* @param pluralCount The runtime count (e.g. number of items).
|
||||||
|
* @return Zero-based plural form index.
|
||||||
|
*/
|
||||||
|
uint8_t assetLocaleEvaluatePlural(
|
||||||
|
assetlocalefile_t *file,
|
||||||
|
const int32_t pluralCount
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Advances the line reader past blank lines, comment lines (starting with
|
||||||
|
* `#`), and lines containing only spaces. Stops at the first content line or
|
||||||
|
* end of file.
|
||||||
|
*
|
||||||
|
* @param reader Line reader positioned at the current line.
|
||||||
|
* @param lineBuffer Output buffer that the reader writes each line into.
|
||||||
|
* @return OK on success, error if reading fails.
|
||||||
*/
|
*/
|
||||||
errorret_t assetLocaleLineSkipBlanks(
|
errorret_t assetLocaleLineSkipBlanks(
|
||||||
assetfilelinereader_t *reader,
|
assetfilelinereader_t *reader,
|
||||||
@@ -82,16 +182,19 @@ errorret_t assetLocaleLineSkipBlanks(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unbuffers a potentially multi-line quoted string from the line reader.
|
* Reads a PO quoted string value from the current line and any immediately
|
||||||
*
|
* following continuation lines that begin with `"`.
|
||||||
* This will read lines until it finds a line that starts with a quote, then
|
*
|
||||||
* read until the closing quote.
|
* Handles standard C escape sequences (`\n`, `\t`, `\\`, `\"`).
|
||||||
*
|
*
|
||||||
* @param reader Line reader to read from.
|
* @param reader Line reader positioned at the line containing the opening
|
||||||
* @param lineBuffer Buffer to use for reading lines.
|
* quote (e.g. `msgstr "..."`).
|
||||||
* @param stringBuffer Buffer to write the unbuffered string to.
|
* @param lineBuffer Buffer the reader fills on each @ref assetFileLineReaderNext
|
||||||
* @param stringBufferSize Size of the string buffer.
|
* call; also used to detect continuation lines.
|
||||||
* @return Any error that occurs during unbuffering.
|
* @param stringBuffer Destination for the unescaped string content.
|
||||||
|
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
||||||
|
* @return OK on success, error if a quote or escape sequence is malformed or
|
||||||
|
* the buffer would overflow.
|
||||||
*/
|
*/
|
||||||
errorret_t assetLocaleLineUnbuffer(
|
errorret_t assetLocaleLineUnbuffer(
|
||||||
assetfilelinereader_t *reader,
|
assetfilelinereader_t *reader,
|
||||||
@@ -101,14 +204,19 @@ errorret_t assetLocaleLineUnbuffer(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test function for locale asset loading.
|
* Looks up a translated string by message ID from the open locale file.
|
||||||
*
|
*
|
||||||
* @param file Asset file to test loading from.
|
* Rewinds the file and scans from the beginning on every call. For plural
|
||||||
* @param messageId The message ID to retrieve.
|
* entries (`msgid_plural`) the `pluralCount` is evaluated against the loaded
|
||||||
* @param pluralCount Count for formulating the plural variant.
|
* plural rules to select the correct `msgstr[N]` form.
|
||||||
* @param stringBuffer Buffer to write the retrieved string to.
|
*
|
||||||
* @param stringBufferSize Size of the string buffer.
|
* @param file Locale file to search. Must be open.
|
||||||
* @return Any error that occurs during testing.
|
* @param messageId PO message ID to find (`""` retrieves the header entry).
|
||||||
|
* @param pluralCount Count used to select the plural form (ignored for
|
||||||
|
* singular entries).
|
||||||
|
* @param stringBuffer Buffer to receive the translated string.
|
||||||
|
* @param stringBufferSize Capacity of `stringBuffer` in bytes.
|
||||||
|
* @return OK on success, error if the message ID is not found or I/O fails.
|
||||||
*/
|
*/
|
||||||
errorret_t assetLocaleGetString(
|
errorret_t assetLocaleGetString(
|
||||||
assetlocalefile_t *file,
|
assetlocalefile_t *file,
|
||||||
@@ -119,15 +227,21 @@ errorret_t assetLocaleGetString(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test function for locale asset loading with a variable argument list.
|
* Looks up a translated string and formats it with a `printf`-style variadic
|
||||||
*
|
* argument list.
|
||||||
* @param file Asset file to test loading from.
|
*
|
||||||
* @param messageId The message ID to retrieve.
|
* Retrieves the raw format string via @ref assetLocaleGetString then applies
|
||||||
* @param pluralCount Count for formulating the plural variant.
|
* `vsnprintf` with the provided arguments.
|
||||||
* @param buffer Buffer to write the retrieved string to.
|
*
|
||||||
* @param bufferSize Size of the buffer.
|
* @param file Locale file to search. Must be open.
|
||||||
* @param ... Additional arguments for formatting the string.
|
* @param messageId PO message ID to find.
|
||||||
* @return Any error that occurs during testing.
|
* @param pluralCount Count used to select the plural form.
|
||||||
|
* @param buffer Buffer to receive the formatted string.
|
||||||
|
* @param bufferSize Capacity of `buffer` in bytes.
|
||||||
|
* @param ... Format arguments matching the specifiers in the translated
|
||||||
|
* string.
|
||||||
|
* @return OK on success, error if the message is not found or formatting
|
||||||
|
* fails.
|
||||||
*/
|
*/
|
||||||
errorret_t assetLocaleGetStringWithVA(
|
errorret_t assetLocaleGetStringWithVA(
|
||||||
assetlocalefile_t *file,
|
assetlocalefile_t *file,
|
||||||
@@ -139,16 +253,22 @@ errorret_t assetLocaleGetStringWithVA(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test function for locale asset loading with a list of arguments.
|
* Looks up a translated string and substitutes typed arguments into its
|
||||||
*
|
* `%s`, `%d`, and `%f` placeholders.
|
||||||
* @param file Asset file to test loading from.
|
*
|
||||||
* @param messageId The message ID to retrieve.
|
* Unlike @ref assetLocaleGetStringWithVA this variant accepts an explicit
|
||||||
* @param pluralCount Count for formulating the plural variant.
|
* array of @ref assetlocalearg_t values, which is safer to use from
|
||||||
* @param buffer Buffer to write the retrieved string to.
|
* generated or scripted call sites.
|
||||||
* @param bufferSize Size of the buffer.
|
*
|
||||||
* @param args List of arguments for formatting the string.
|
* @param file Locale file to search. Must be open.
|
||||||
* @param argCount Number of arguments in the list.
|
* @param messageId PO message ID to find.
|
||||||
* @return Any error that occurs during testing.
|
* @param pluralCount Count used to select the plural form.
|
||||||
|
* @param buffer Buffer to receive the formatted string.
|
||||||
|
* @param bufferSize Capacity of `buffer` in bytes.
|
||||||
|
* @param args Array of typed arguments; may be NULL when `argCount` is 0.
|
||||||
|
* @param argCount Number of elements in `args`.
|
||||||
|
* @return OK on success, error if the message is not found, an argument type
|
||||||
|
* mismatches the specifier, or the buffer would overflow.
|
||||||
*/
|
*/
|
||||||
errorret_t assetLocaleGetStringWithArgs(
|
errorret_t assetLocaleGetStringWithArgs(
|
||||||
assetlocalefile_t *file,
|
assetlocalefile_t *file,
|
||||||
@@ -158,4 +278,4 @@ errorret_t assetLocaleGetStringWithArgs(
|
|||||||
const size_t bufferSize,
|
const size_t bufferSize,
|
||||||
const assetlocalearg_t *args,
|
const assetlocalearg_t *args,
|
||||||
const size_t argCount
|
const size_t argCount
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
# Copyright (c) 2026 Dominic Masters
|
# Copyright (c) 2026 Dominic Masters
|
||||||
#
|
#
|
||||||
# This software is released under the MIT License.
|
# This software is released under the MIT License.
|
||||||
# https://opensource.org/licenses/MIT
|
# https://opensource.org/licenses/MIT
|
||||||
|
|
||||||
# Sources
|
|
||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
initialscene.c
|
assetscriptloader.c
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "assetscriptloader.h"
|
||||||
|
#include "asset/loader/assetloading.h"
|
||||||
|
#include "asset/loader/assetentry.h"
|
||||||
|
#include "asset/loader/assetloader.h"
|
||||||
|
#include "script/module/require/modulerequire.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
#include <jerryscript.h>
|
||||||
|
|
||||||
|
errorret_t assetScriptLoaderAsync(assetloading_t *loading) {
|
||||||
|
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) {
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNull(loading->loading.script.buffer, "Buffer already defined?");
|
||||||
|
|
||||||
|
assetfile_t *file = &loading->loading.script.file;
|
||||||
|
assetLoaderErrorChain(
|
||||||
|
loading, assetFileInit(file, loading->entry->name, NULL, NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
uint8_t *buffer = NULL;
|
||||||
|
size_t size = 0;
|
||||||
|
assetLoaderErrorChain(loading, assetFileReadEntire(file, &buffer, &size));
|
||||||
|
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.size = size;
|
||||||
|
loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_EXEC;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetScriptLoaderSync(assetloading_t *loading) {
|
||||||
|
assertNotNull(loading, "Loading cannot be NULL");
|
||||||
|
assertTrue(loading->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
switch(loading->loading.script.state) {
|
||||||
|
case ASSET_SCRIPT_LOADING_STATE_INITIAL:
|
||||||
|
loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_READ_FILE;
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
|
||||||
|
errorOk();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ASSET_SCRIPT_LOADING_STATE_EXEC:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get read buffer
|
||||||
|
uint8_t *buffer = loading->loading.script.buffer;
|
||||||
|
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(
|
||||||
|
buffer,
|
||||||
|
loading->loading.script.size,
|
||||||
|
JERRY_PARSE_NO_OPTS
|
||||||
|
);
|
||||||
|
|
||||||
|
// Free the read buffer
|
||||||
|
memoryFree(buffer);
|
||||||
|
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)) {
|
||||||
|
jerry_value_free(module);
|
||||||
|
|
||||||
|
loading->entry->data.script.exports = jerry_undefined();
|
||||||
|
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
|
||||||
|
|
||||||
|
// Get error string
|
||||||
|
char_t buf[256];
|
||||||
|
moduleBaseExceptionMessage(result, buf, sizeof(buf));
|
||||||
|
jerry_value_free(result);
|
||||||
|
assetLoaderErrorThrow(
|
||||||
|
loading,
|
||||||
|
"Script execution failed: %s: %s", loading->entry->name, buf
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t assetScriptDispose(assetentry_t *entry) {
|
||||||
|
assertNotNull(entry, "Asset entry cannot be NULL");
|
||||||
|
assertTrue(entry->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
|
||||||
|
assertIsMainThread("Must be called from the main thread.");
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "asset/assetfile.h"
|
||||||
|
#include "script/scriptmodule.h"
|
||||||
|
|
||||||
|
#define ASSET_SCRIPT_CHUNK_SIZE 1024
|
||||||
|
|
||||||
|
typedef struct assetloading_s assetloading_t;
|
||||||
|
typedef struct assetentry_s assetentry_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
void *nothing;
|
||||||
|
} assetscriptloaderinput_t;
|
||||||
|
|
||||||
|
typedef scriptmodule_t assetscriptoutput_t;
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ASSET_SCRIPT_LOADING_STATE_INITIAL,
|
||||||
|
ASSET_SCRIPT_LOADING_STATE_READ_FILE,
|
||||||
|
ASSET_SCRIPT_LOADING_STATE_EXEC,
|
||||||
|
ASSET_SCRIPT_LOADING_STATE_DONE
|
||||||
|
} assetscriptloadingstate_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
assetfile_t file;
|
||||||
|
assetscriptloadingstate_t state;
|
||||||
|
uint8_t *buffer;
|
||||||
|
size_t size;
|
||||||
|
} 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);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
@@ -67,7 +67,7 @@ errorret_t consoleDraw(void) {
|
|||||||
|
|
||||||
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
|
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
|
||||||
errorChain(textDraw(
|
errorChain(textDraw(
|
||||||
0, FONT_DEFAULT.tileset.tileHeight * i,
|
0, FONT_DEFAULT.tileset->tileHeight * i,
|
||||||
CONSOLE.line[i],
|
CONSOLE.line[i],
|
||||||
COLOR_WHITE,
|
COLOR_WHITE,
|
||||||
&FONT_DEFAULT
|
&FONT_DEFAULT
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
#include "util/string.h"
|
#include "util/string.h"
|
||||||
#include "asset/asset.h"
|
#include "asset/asset.h"
|
||||||
#include "display/shader/shaderunlit.h"
|
#include "display/shader/shaderlist.h"
|
||||||
#include "time/time.h"
|
#include "time/time.h"
|
||||||
|
|
||||||
display_t DISPLAY = { 0 };
|
display_t DISPLAY = { 0 };
|
||||||
@@ -53,31 +53,8 @@ errorret_t displayInit(void) {
|
|||||||
errorChain(screenInit());
|
errorChain(screenInit());
|
||||||
|
|
||||||
// Setup initial shader with default values
|
// Setup initial shader with default values
|
||||||
mat4 view, proj, model;
|
|
||||||
glm_lookat(
|
|
||||||
(vec3){ 0.0f, 0.0f, 1.0f },
|
|
||||||
(vec3){ 0.0f, 0.0f, 0.0f },
|
|
||||||
(vec3){ 0.0f, 1.0f, 0.0f },
|
|
||||||
view
|
|
||||||
);
|
|
||||||
|
|
||||||
glm_perspective(
|
errorChain(shaderListInit());
|
||||||
glm_rad(45.0f),
|
|
||||||
SCREEN.aspect,
|
|
||||||
0.1f,
|
|
||||||
100.0f,
|
|
||||||
proj
|
|
||||||
);
|
|
||||||
|
|
||||||
glm_mat4_identity(model);
|
|
||||||
|
|
||||||
errorChain(shaderInit(&SHADER_UNLIT, &SHADER_UNLIT_DEFINITION));
|
|
||||||
errorChain(shaderBind(&SHADER_UNLIT));
|
|
||||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj));
|
|
||||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, view));
|
|
||||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, model));
|
|
||||||
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, NULL));
|
|
||||||
errorChain(shaderSetColor(&SHADER_UNLIT, SHADER_UNLIT_COLOR, COLOR_WHITE));
|
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
@@ -119,7 +96,7 @@ errorret_t displaySetState(displaystate_t state) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
errorret_t displayDispose(void) {
|
errorret_t displayDispose(void) {
|
||||||
errorChain(shaderDispose(&SHADER_UNLIT));
|
errorChain(shaderListDispose());
|
||||||
errorChain(spriteBatchDispose());
|
errorChain(spriteBatchDispose());
|
||||||
screenDispose();
|
screenDispose();
|
||||||
errorChain(textDispose());
|
errorChain(textDispose());
|
||||||
|
|||||||
@@ -7,5 +7,6 @@
|
|||||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||||
PUBLIC
|
PUBLIC
|
||||||
shader.c
|
shader.c
|
||||||
|
shaderlist.c
|
||||||
shaderunlit.c
|
shaderunlit.c
|
||||||
)
|
)
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
#include "shader.h"
|
#include "shader.h"
|
||||||
#include "shadermaterial.h"
|
#include "shadermaterial.h"
|
||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
|
#include "log/log.h"
|
||||||
|
|
||||||
shader_t *bound = NULL;
|
shader_t *bound = NULL;
|
||||||
|
|
||||||
@@ -57,6 +58,7 @@ errorret_t shaderSetColor(
|
|||||||
) {
|
) {
|
||||||
assertNotNull(shader, "Shader cannot be null");
|
assertNotNull(shader, "Shader cannot be null");
|
||||||
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
||||||
|
assertTrue(bound == shader, "Shader must be bound.");
|
||||||
errorChain(shaderSetColorPlatform(shader, name, color));
|
errorChain(shaderSetColorPlatform(shader, name, color));
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "shaderlist.h"
|
||||||
|
#include "display/screen/screen.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
|
||||||
|
shaderlistdef_t SHADER_LIST_DEFS[SHADER_LIST_SHADER_COUNT] = {
|
||||||
|
[SHADER_LIST_SHADER_UNLIT] = {
|
||||||
|
.shader = &SHADER_UNLIT,
|
||||||
|
.definition = &SHADER_UNLIT_DEFINITION
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
errorret_t shaderListInit() {
|
||||||
|
mat4 view, proj, model;
|
||||||
|
glm_lookat(
|
||||||
|
(vec3){ 0.0f, 0.0f, 1.0f },
|
||||||
|
(vec3){ 0.0f, 0.0f, 0.0f },
|
||||||
|
(vec3){ 0.0f, 1.0f, 0.0f },
|
||||||
|
view
|
||||||
|
);
|
||||||
|
|
||||||
|
glm_perspective(
|
||||||
|
glm_rad(45.0f),
|
||||||
|
SCREEN.aspect,
|
||||||
|
0.1f,
|
||||||
|
100.0f,
|
||||||
|
proj
|
||||||
|
);
|
||||||
|
|
||||||
|
glm_mat4_identity(model);
|
||||||
|
|
||||||
|
for(shaderlistshader_t i = 0; i < SHADER_LIST_SHADER_COUNT; i++) {
|
||||||
|
if(i == SHADER_LIST_SHADER_NULL) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNotNull(
|
||||||
|
SHADER_LIST_DEFS[i].shader, "Shader cannot be null"
|
||||||
|
);
|
||||||
|
assertNotNull(
|
||||||
|
SHADER_LIST_DEFS[i].definition, "Shader definition cannot be null"
|
||||||
|
);
|
||||||
|
|
||||||
|
errorChain(shaderInit(
|
||||||
|
SHADER_LIST_DEFS[i].shader, SHADER_LIST_DEFS[i].definition
|
||||||
|
));
|
||||||
|
errorChain(shaderBind(SHADER_LIST_DEFS[i].shader));
|
||||||
|
errorChain(shaderSetMatrix(
|
||||||
|
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_PROJECTION, proj
|
||||||
|
));
|
||||||
|
errorChain(shaderSetMatrix(
|
||||||
|
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_VIEW, view
|
||||||
|
));
|
||||||
|
errorChain(shaderSetMatrix(
|
||||||
|
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_MODEL, model
|
||||||
|
));
|
||||||
|
errorChain(shaderSetTexture(
|
||||||
|
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_TEXTURE, NULL
|
||||||
|
));
|
||||||
|
errorChain(shaderSetColor(
|
||||||
|
SHADER_LIST_DEFS[i].shader, SHADER_UNLIT_COLOR, COLOR_WHITE
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
|
errorret_t shaderListDispose(void) {
|
||||||
|
for(shaderlistshader_t i = 0; i < SHADER_LIST_SHADER_COUNT; i++) {
|
||||||
|
if(i == SHADER_LIST_SHADER_NULL) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNotNull(
|
||||||
|
SHADER_LIST_DEFS[i].shader, "Shader cannot be null"
|
||||||
|
);
|
||||||
|
|
||||||
|
errorChain(shaderDispose(SHADER_LIST_DEFS[i].shader));
|
||||||
|
}
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (c) 2026 Dominic Masters
|
||||||
|
*
|
||||||
|
* This software is released under the MIT License.
|
||||||
|
* https://opensource.org/licenses/MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include "display/shader/shader.h"
|
||||||
|
#include "display/shader/shaderunlit.h"
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
SHADER_LIST_SHADER_NULL,
|
||||||
|
|
||||||
|
SHADER_LIST_SHADER_UNLIT,
|
||||||
|
|
||||||
|
SHADER_LIST_SHADER_COUNT
|
||||||
|
} shaderlistshader_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
shader_t *shader;
|
||||||
|
shaderdefinition_t *definition;
|
||||||
|
} shaderlistdef_t;
|
||||||
|
|
||||||
|
extern shaderlistdef_t SHADER_LIST_DEFS[SHADER_LIST_SHADER_COUNT];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes all default shaders and uploads the initial view, projection,
|
||||||
|
* and model matrices to each.
|
||||||
|
*
|
||||||
|
* @return Error state.
|
||||||
|
*/
|
||||||
|
errorret_t shaderListInit();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes all default shaders.
|
||||||
|
*
|
||||||
|
* @return Error state.
|
||||||
|
*/
|
||||||
|
errorret_t shaderListDispose(void);
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "display/shader/shaderunlit.h"
|
#include "display/shader/shaderlist.h"
|
||||||
|
|
||||||
typedef union shadermaterial_u {
|
typedef union shadermaterial_u {
|
||||||
shaderunlitmaterial_t unlit;
|
shaderunlitmaterial_t unlit;
|
||||||
|
|||||||
@@ -9,14 +9,13 @@
|
|||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
#include "util/math.h"
|
#include "util/math.h"
|
||||||
#include "display/shader/shaderunlit.h"
|
#include "display/shader/shadermaterial.h"
|
||||||
|
|
||||||
meshvertex_t SPRITEBATCH_VERTICES[SPRITEBATCH_VERTEX_COUNT];
|
meshvertex_t SPRITEBATCH_VERTICES[SPRITEBATCH_VERTEX_COUNT];
|
||||||
spritebatch_t SPRITEBATCH;
|
spritebatch_t SPRITEBATCH;
|
||||||
|
|
||||||
errorret_t spriteBatchInit() {
|
errorret_t spriteBatchInit() {
|
||||||
memoryZero(&SPRITEBATCH, sizeof(spritebatch_t));
|
memoryZero(&SPRITEBATCH, sizeof(spritebatch_t));
|
||||||
|
|
||||||
errorChain(meshInit(
|
errorChain(meshInit(
|
||||||
&SPRITEBATCH.mesh,
|
&SPRITEBATCH.mesh,
|
||||||
QUAD_PRIMITIVE_TYPE,
|
QUAD_PRIMITIVE_TYPE,
|
||||||
@@ -28,137 +27,100 @@ errorret_t spriteBatchInit() {
|
|||||||
|
|
||||||
errorret_t spriteBatchBuffer(
|
errorret_t spriteBatchBuffer(
|
||||||
const spritebatchsprite_t *sprites,
|
const spritebatchsprite_t *sprites,
|
||||||
const uint32_t count
|
const uint32_t count,
|
||||||
|
shader_t *shader,
|
||||||
|
const shadermaterial_t material
|
||||||
) {
|
) {
|
||||||
for(uint32_t i = 0; i < count; i++) {
|
assertNotNull(sprites, "Sprites cannot be null");
|
||||||
const spritebatchsprite_t *s = &sprites[i];
|
assertTrue(count > 0, "Count must be greater than zero");
|
||||||
|
assertNotNull(shader, "Shader cannot be null");
|
||||||
|
|
||||||
// if(s->texture != SPRITEBATCH.currentTexture) {
|
// Did the shader or material data change?
|
||||||
// errorChain(spriteBatchFlush());
|
if(shader != SPRITEBATCH.shader) {
|
||||||
// }
|
errorChain(spriteBatchFlush());
|
||||||
|
SPRITEBATCH.shader = shader;
|
||||||
|
SPRITEBATCH.material = material;
|
||||||
|
} else if(memoryCompare(
|
||||||
|
&material, &SPRITEBATCH.material, sizeof(shadermaterial_t)
|
||||||
|
) != 0) {
|
||||||
|
// Did the material data change?
|
||||||
|
errorChain(spriteBatchFlush());
|
||||||
|
SPRITEBATCH.shader = shader;
|
||||||
|
SPRITEBATCH.material = material;
|
||||||
|
}
|
||||||
|
|
||||||
if(SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX_PER_FLUSH) {
|
// Buffer the vertices.
|
||||||
errorChain(spriteBatchFlush());
|
for(uint32_t i = 0; i < count; i++ ){
|
||||||
}
|
spritebatchsprite_t sprite = sprites[i];
|
||||||
|
|
||||||
meshvertex_t *v = &SPRITEBATCH_VERTICES[
|
meshvertex_t *v = &SPRITEBATCH_VERTICES[
|
||||||
(SPRITEBATCH.spriteCount + (SPRITEBATCH.spriteFlush *
|
(SPRITEBATCH.spriteCount + (SPRITEBATCH.spriteFlush *
|
||||||
SPRITEBATCH_SPRITES_MAX_PER_FLUSH)) * QUAD_VERTEX_COUNT
|
SPRITEBATCH_SPRITES_MAX_PER_FLUSH)) * QUAD_VERTEX_COUNT
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Buffer the quad
|
||||||
|
v[0].pos[0] = sprite.min[0];
|
||||||
|
v[0].pos[1] = sprite.min[1];
|
||||||
|
v[0].pos[2] = sprite.min[2];
|
||||||
|
|
||||||
v[0].pos[0] = s->min[0]; v[0].pos[1] = s->min[1]; v[0].pos[2] = s->min[2];
|
v[0].uv[0] = sprite.uvMin[0];
|
||||||
v[0].uv[0] = s->uvMin[0]; v[0].uv[1] = s->uvMin[1];
|
v[0].uv[1] = sprite.uvMin[1];
|
||||||
|
|
||||||
v[1].pos[0] = s->max[0]; v[1].pos[1] = s->min[1]; v[1].pos[2] = s->min[2];
|
|
||||||
v[1].uv[0] = s->uvMax[0]; v[1].uv[1] = s->uvMin[1];
|
|
||||||
|
|
||||||
v[2].pos[0] = s->max[0]; v[2].pos[1] = s->max[1]; v[2].pos[2] = s->min[2];
|
v[1].pos[0] = sprite.max[0];
|
||||||
v[2].uv[0] = s->uvMax[0]; v[2].uv[1] = s->uvMax[1];
|
v[1].pos[1] = sprite.min[1];
|
||||||
|
v[1].pos[2] = sprite.min[2];
|
||||||
|
|
||||||
v[3].pos[0] = s->min[0]; v[3].pos[1] = s->min[1]; v[3].pos[2] = s->min[2];
|
v[1].uv[0] = sprite.uvMax[0];
|
||||||
v[3].uv[0] = s->uvMin[0]; v[3].uv[1] = s->uvMin[1];
|
v[1].uv[1] = sprite.uvMin[1];
|
||||||
|
|
||||||
v[4].pos[0] = s->max[0]; v[4].pos[1] = s->max[1]; v[4].pos[2] = s->min[2];
|
|
||||||
v[4].uv[0] = s->uvMax[0]; v[4].uv[1] = s->uvMax[1];
|
|
||||||
|
|
||||||
v[5].pos[0] = s->min[0]; v[5].pos[1] = s->max[1]; v[5].pos[2] = s->min[2];
|
v[2].pos[0] = sprite.max[0];
|
||||||
v[5].uv[0] = s->uvMin[0]; v[5].uv[1] = s->uvMax[1];
|
v[2].pos[1] = sprite.max[1];
|
||||||
|
v[2].pos[2] = sprite.max[2];
|
||||||
|
|
||||||
#if MESH_ENABLE_COLOR
|
v[2].uv[0] = sprite.uvMax[0];
|
||||||
for(uint8_t vi = 0; vi < QUAD_VERTEX_COUNT; vi++) {
|
v[2].uv[1] = sprite.uvMax[1];
|
||||||
v[vi].color = s->color;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
|
v[3].pos[0] = sprite.min[0];
|
||||||
|
v[3].pos[1] = sprite.min[1];
|
||||||
|
v[3].pos[2] = sprite.min[2];
|
||||||
|
|
||||||
|
v[3].uv[0] = sprite.uvMin[0];
|
||||||
|
v[3].uv[1] = sprite.uvMin[1];
|
||||||
|
|
||||||
|
|
||||||
|
v[4].pos[0] = sprite.max[0];
|
||||||
|
v[4].pos[1] = sprite.max[1];
|
||||||
|
v[4].pos[2] = sprite.max[2];
|
||||||
|
|
||||||
|
v[4].uv[0] = sprite.uvMax[0];
|
||||||
|
v[4].uv[1] = sprite.uvMax[1];
|
||||||
|
|
||||||
|
|
||||||
|
v[5].pos[0] = sprite.min[0];
|
||||||
|
v[5].pos[1] = sprite.max[1];
|
||||||
|
v[5].pos[2] = sprite.max[2];
|
||||||
|
|
||||||
|
v[5].uv[0] = sprite.uvMin[0];
|
||||||
|
v[5].uv[1] = sprite.uvMax[1];
|
||||||
|
|
||||||
|
// Do we need to flush?
|
||||||
SPRITEBATCH.spriteCount++;
|
SPRITEBATCH.spriteCount++;
|
||||||
|
if(SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX_PER_FLUSH) {
|
||||||
|
errorChain(spriteBatchFlush());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t spriteBatchBufferSprite(const spritebatchsprite_t *sprite) {
|
|
||||||
return spriteBatchBuffer(sprite, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t spriteBatchPushv(
|
|
||||||
const float_t *minX,
|
|
||||||
const float_t *minY,
|
|
||||||
const float_t *maxX,
|
|
||||||
const float_t *maxY,
|
|
||||||
const float_t *z,
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
const color_t *color,
|
|
||||||
#endif
|
|
||||||
const float_t *u0,
|
|
||||||
const float_t *v0,
|
|
||||||
const float_t *u1,
|
|
||||||
const float_t *v1,
|
|
||||||
const size_t count
|
|
||||||
) {
|
|
||||||
for(size_t i = 0; i < count; i++) {
|
|
||||||
spritebatchsprite_t sprite;
|
|
||||||
sprite.min[0] = minX[i]; sprite.min[1] = minY[i]; sprite.min[2] = z[i];
|
|
||||||
sprite.max[0] = maxX[i]; sprite.max[1] = maxY[i]; sprite.max[2] = z[i];
|
|
||||||
sprite.uvMin[0] = u0[i]; sprite.uvMin[1] = v0[i];
|
|
||||||
sprite.uvMax[0] = u1[i]; sprite.uvMax[1] = v1[i];
|
|
||||||
sprite.texture = SPRITEBATCH.currentTexture;
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
sprite.color = color[i];
|
|
||||||
#endif
|
|
||||||
errorChain(spriteBatchBuffer(&sprite, 1));
|
|
||||||
}
|
|
||||||
errorOk();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t spriteBatchPush(
|
|
||||||
const float_t minX,
|
|
||||||
const float_t minY,
|
|
||||||
const float_t maxX,
|
|
||||||
const float_t maxY,
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
const color_t color,
|
|
||||||
#endif
|
|
||||||
const float_t u0,
|
|
||||||
const float_t v0,
|
|
||||||
const float_t u1,
|
|
||||||
const float_t v1
|
|
||||||
) {
|
|
||||||
spritebatchsprite_t sprite;
|
|
||||||
sprite.min[0] = minX; sprite.min[1] = minY; sprite.min[2] = 0;
|
|
||||||
sprite.max[0] = maxX; sprite.max[1] = maxY; sprite.max[2] = 0;
|
|
||||||
sprite.uvMin[0] = u0; sprite.uvMin[1] = v0;
|
|
||||||
sprite.uvMax[0] = u1; sprite.uvMax[1] = v1;
|
|
||||||
sprite.texture = SPRITEBATCH.currentTexture;
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
sprite.color = color;
|
|
||||||
#endif
|
|
||||||
return spriteBatchBuffer(&sprite, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
errorret_t spriteBatchPushZ(
|
|
||||||
const vec3 min,
|
|
||||||
const vec3 max,
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
const color_t color,
|
|
||||||
#endif
|
|
||||||
const vec2 uvMin,
|
|
||||||
const vec2 uvMax
|
|
||||||
) {
|
|
||||||
spritebatchsprite_t sprite;
|
|
||||||
sprite.min[0] = min[0]; sprite.min[1] = min[1]; sprite.min[2] = min[2];
|
|
||||||
sprite.max[0] = max[0]; sprite.max[1] = max[1]; sprite.max[2] = max[2];
|
|
||||||
sprite.uvMin[0] = uvMin[0]; sprite.uvMin[1] = uvMin[1];
|
|
||||||
sprite.uvMax[0] = uvMax[0]; sprite.uvMax[1] = uvMax[1];
|
|
||||||
sprite.texture = SPRITEBATCH.currentTexture;
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
sprite.color = color;
|
|
||||||
#endif
|
|
||||||
return spriteBatchBuffer(&sprite, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
void spriteBatchClear() {
|
void spriteBatchClear() {
|
||||||
SPRITEBATCH.spriteCount = 0;
|
SPRITEBATCH.spriteCount = 0;
|
||||||
SPRITEBATCH.spriteFlush = 0;
|
SPRITEBATCH.spriteFlush = 0;
|
||||||
SPRITEBATCH.currentTexture = NULL;
|
SPRITEBATCH.shader = NULL;
|
||||||
|
memoryZero(&SPRITEBATCH.material, sizeof(shadermaterial_t));
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t spriteBatchFlush() {
|
errorret_t spriteBatchFlush() {
|
||||||
@@ -171,6 +133,9 @@ errorret_t spriteBatchFlush() {
|
|||||||
SPRITEBATCH.spriteFlush * SPRITEBATCH_SPRITES_MAX_PER_FLUSH *
|
SPRITEBATCH.spriteFlush * SPRITEBATCH_SPRITES_MAX_PER_FLUSH *
|
||||||
QUAD_VERTEX_COUNT
|
QUAD_VERTEX_COUNT
|
||||||
);
|
);
|
||||||
|
|
||||||
|
errorChain(shaderBind(SPRITEBATCH.shader));
|
||||||
|
errorChain(shaderSetMaterial(SPRITEBATCH.shader, &SPRITEBATCH.material));
|
||||||
errorChain(meshFlush(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
errorChain(meshFlush(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
||||||
errorChain(meshDraw(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
errorChain(meshDraw(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
||||||
|
|
||||||
@@ -186,4 +151,4 @@ errorret_t spriteBatchFlush() {
|
|||||||
errorret_t spriteBatchDispose() {
|
errorret_t spriteBatchDispose() {
|
||||||
errorChain(meshDispose(&SPRITEBATCH.mesh));
|
errorChain(meshDispose(&SPRITEBATCH.mesh));
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "display/mesh/quad.h"
|
#include "display/mesh/quad.h"
|
||||||
#include "display/texture/texture.h"
|
#include "display/texture/texture.h"
|
||||||
|
#include "display/shader/shadermaterial.h"
|
||||||
|
|
||||||
#define SPRITEBATCH_SPRITES_MAX 512
|
#define SPRITEBATCH_SPRITES_MAX 512
|
||||||
#define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT)
|
#define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT)
|
||||||
@@ -21,146 +22,66 @@ typedef struct {
|
|||||||
vec3 max;
|
vec3 max;
|
||||||
vec2 uvMin;
|
vec2 uvMin;
|
||||||
vec2 uvMax;
|
vec2 uvMax;
|
||||||
texture_t *texture;
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
color_t color;
|
|
||||||
#endif
|
|
||||||
} spritebatchsprite_t;
|
} spritebatchsprite_t;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
mesh_t mesh;
|
mesh_t mesh;
|
||||||
int32_t spriteCount;
|
int32_t spriteCount;
|
||||||
int32_t spriteFlush;
|
int32_t spriteFlush;
|
||||||
texture_t *currentTexture;
|
|
||||||
|
shader_t *shader;
|
||||||
|
shadermaterial_t material;
|
||||||
} spritebatch_t;
|
} spritebatch_t;
|
||||||
|
|
||||||
// Have to define these seperately because of alignment in certain platforms.
|
// Have to define these separately because of alignment on certain platforms.
|
||||||
extern meshvertex_t SPRITEBATCH_VERTICES[SPRITEBATCH_VERTEX_COUNT];
|
extern meshvertex_t SPRITEBATCH_VERTICES[SPRITEBATCH_VERTEX_COUNT];
|
||||||
extern spritebatch_t SPRITEBATCH;
|
extern spritebatch_t SPRITEBATCH;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes a sprite batch.
|
* Initializes the global sprite batch and its internal mesh buffer.
|
||||||
*
|
*
|
||||||
* @return An error code indicating success or failure.
|
* @return Error state.
|
||||||
*/
|
*/
|
||||||
errorret_t spriteBatchInit();
|
errorret_t spriteBatchInit();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Buffers an array of sprites. Flushes automatically when the texture changes
|
* Lowest-level buffer function. Writes sprites into the internal vertex buffer.
|
||||||
* or the per-flush limit is reached.
|
* Flushes automatically when the per-flush capacity is reached. Does not
|
||||||
|
* modify material state — call spriteBatchSetState or use a high-level push
|
||||||
|
* function before buffering.
|
||||||
*
|
*
|
||||||
* @param sprites Pointer to the sprite array.
|
* @param sprites Pointer to the sprite array.
|
||||||
* @param count Number of sprites to buffer.
|
* @param count Number of sprites to buffer.
|
||||||
* @return An error code indicating success or failure.
|
* @param shader Shader to use when flushing.
|
||||||
|
* @param material Material information passed to the shader when flushing.
|
||||||
|
* @return Error state.
|
||||||
*/
|
*/
|
||||||
errorret_t spriteBatchBuffer(
|
errorret_t spriteBatchBuffer(
|
||||||
const spritebatchsprite_t *sprites,
|
const spritebatchsprite_t *sprites,
|
||||||
const uint32_t count
|
const uint32_t count,
|
||||||
|
shader_t *shader,
|
||||||
|
const shadermaterial_t material
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convenience wrapper — buffers a single sprite.
|
* Resets sprite and flush counters and clears the current material state.
|
||||||
*
|
* Calling spriteBatchFlush after this renders nothing.
|
||||||
* @param sprite The sprite to buffer.
|
|
||||||
* @return An error code indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t spriteBatchBufferSprite(const spritebatchsprite_t *sprite);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pushes multiple sprites to the batch using parallel arrays of values.
|
|
||||||
*
|
|
||||||
* @param minX Array of minimum x coordinates.
|
|
||||||
* @param minY Array of minimum y coordinates.
|
|
||||||
* @param maxX Array of maximum x coordinates.
|
|
||||||
* @param maxY Array of maximum y coordinates.
|
|
||||||
* @param z Array of z coordinates.
|
|
||||||
* @param color Array of colors (if enabled).
|
|
||||||
* @param u0 Array of u0 texture coordinates.
|
|
||||||
* @param v0 Array of v0 texture coordinates.
|
|
||||||
* @param u1 Array of u1 texture coordinates.
|
|
||||||
* @param v1 Array of v1 texture coordinates.
|
|
||||||
* @param count Number of sprites to push.
|
|
||||||
* @return An error code indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t spriteBatchPushv(
|
|
||||||
const float_t *minX,
|
|
||||||
const float_t *minY,
|
|
||||||
const float_t *maxX,
|
|
||||||
const float_t *maxY,
|
|
||||||
const float_t *z,
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
const color_t *color,
|
|
||||||
#endif
|
|
||||||
const float_t *u0,
|
|
||||||
const float_t *v0,
|
|
||||||
const float_t *u1,
|
|
||||||
const float_t *v1,
|
|
||||||
const size_t count
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pushes a 2D sprite (z=0) to the batch.
|
|
||||||
*
|
|
||||||
* @param minX The minimum x coordinate of the sprite.
|
|
||||||
* @param minY The minimum y coordinate of the sprite.
|
|
||||||
* @param maxX The maximum x coordinate of the sprite.
|
|
||||||
* @param maxY The maximum y coordinate of the sprite.
|
|
||||||
* @param color The color to tint the sprite with.
|
|
||||||
* @param u0 Texture u coordinate for the top-left corner.
|
|
||||||
* @param v0 Texture v coordinate for the top-left corner.
|
|
||||||
* @param u1 Texture u coordinate for the bottom-right corner.
|
|
||||||
* @param v1 Texture v coordinate for the bottom-right corner.
|
|
||||||
* @return An error code indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t spriteBatchPush(
|
|
||||||
const float_t minX,
|
|
||||||
const float_t minY,
|
|
||||||
const float_t maxX,
|
|
||||||
const float_t maxY,
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
const color_t color,
|
|
||||||
#endif
|
|
||||||
const float_t u0,
|
|
||||||
const float_t v0,
|
|
||||||
const float_t u1,
|
|
||||||
const float_t v1
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pushes a 3D sprite to the batch.
|
|
||||||
*
|
|
||||||
* @param min The minimum (x,y,z) coordinate of the sprite.
|
|
||||||
* @param max The maximum (x,y,z) coordinate of the sprite.
|
|
||||||
* @param color The color to tint the sprite with.
|
|
||||||
* @param uvMin Texture coordinate for the top-left corner.
|
|
||||||
* @param uvMax Texture coordinate for the bottom-right corner.
|
|
||||||
* @return An error code indicating success or failure.
|
|
||||||
*/
|
|
||||||
errorret_t spriteBatchPushZ(
|
|
||||||
const vec3 min,
|
|
||||||
const vec3 max,
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
const color_t color,
|
|
||||||
#endif
|
|
||||||
const vec2 uvMin,
|
|
||||||
const vec2 uvMax
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clears the sprite batch. Calling flush after this renders nothing.
|
|
||||||
*/
|
*/
|
||||||
void spriteBatchClear();
|
void spriteBatchClear();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flushes the sprite batch, rendering all queued sprites.
|
* Uploads and draws all buffered sprites. If a material type has been set via
|
||||||
|
* spriteBatchSetState or spriteBatchCheckState, the shader is bound and the
|
||||||
|
* material is applied first. If matType is NULL the caller is responsible for
|
||||||
|
* having the correct shader already bound. Does nothing if the buffer is empty.
|
||||||
*
|
*
|
||||||
* @return An error code indicating success or failure.
|
* @return Error state.
|
||||||
*/
|
*/
|
||||||
errorret_t spriteBatchFlush();
|
errorret_t spriteBatchFlush();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disposes of the sprite batch, freeing any allocated resources.
|
* Disposes of the sprite batch and frees its internal mesh buffer.
|
||||||
*
|
*
|
||||||
* @return An error code indicating success or failure.
|
* @return Error state.
|
||||||
*/
|
*/
|
||||||
errorret_t spriteBatchDispose();
|
errorret_t spriteBatchDispose();
|
||||||
|
|||||||
@@ -10,6 +10,6 @@
|
|||||||
#include "display/texture/tileset.h"
|
#include "display/texture/tileset.h"
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
texture_t texture;
|
texture_t *texture;
|
||||||
tileset_t tileset;
|
tileset_t *tileset;
|
||||||
} font_t;
|
} font_t;
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
#include "display/spritebatch/spritebatch.h"
|
#include "display/spritebatch/spritebatch.h"
|
||||||
|
#include "asset/asset.h"
|
||||||
#include "asset/loader/display/assettextureloader.h"
|
#include "asset/loader/display/assettextureloader.h"
|
||||||
#include "asset/loader/display/assettilesetloader.h"
|
#include "asset/loader/display/assettilesetloader.h"
|
||||||
#include "display/shader/shaderunlit.h"
|
#include "display/shader/shaderunlit.h"
|
||||||
@@ -16,49 +17,60 @@
|
|||||||
font_t FONT_DEFAULT;
|
font_t FONT_DEFAULT;
|
||||||
|
|
||||||
errorret_t textInit(void) {
|
errorret_t textInit(void) {
|
||||||
errorChain(assetTextureLoad(
|
assetloaderinput_t input = { .texture = TEXTURE_FORMAT_RGBA };
|
||||||
"ui/minogram.png", &FONT_DEFAULT.texture, TEXTURE_FORMAT_RGBA
|
assetentry_t *entryTexture = assetLock(
|
||||||
));
|
"ui/minogram.png", ASSET_LOADER_TYPE_TEXTURE, &input
|
||||||
errorChain(assetTilesetLoad("ui/minogram.dtf", &FONT_DEFAULT.tileset));
|
);
|
||||||
|
assetentry_t *entryTileset = assetLock(
|
||||||
|
"ui/minogram.dtf", ASSET_LOADER_TYPE_TILESET, NULL
|
||||||
|
);
|
||||||
|
errorChain(assetRequireLoaded(entryTexture));
|
||||||
|
errorChain(assetRequireLoaded(entryTileset));
|
||||||
|
|
||||||
|
FONT_DEFAULT.texture = &entryTexture->data.texture;
|
||||||
|
FONT_DEFAULT.tileset = &entryTileset->data.tileset;
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t textDispose(void) {
|
errorret_t textDispose(void) {
|
||||||
errorChain(textureDispose(&FONT_DEFAULT.texture));
|
FONT_DEFAULT.texture = NULL;
|
||||||
|
FONT_DEFAULT.tileset = NULL;
|
||||||
|
assetUnlock("ui/minogram.png");
|
||||||
|
assetUnlock("ui/minogram.dtf");
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t textDrawChar(
|
spritebatchsprite_t textGetSprite(
|
||||||
const float_t x,
|
const vec2 pos, const char_t c, const font_t *font
|
||||||
const float_t y,
|
|
||||||
const char_t c,
|
|
||||||
#if MESH_ENABLE_COLOR
|
|
||||||
const color_t color,
|
|
||||||
#endif
|
|
||||||
font_t *font
|
|
||||||
) {
|
) {
|
||||||
|
assertNotNull(font, "Font cannot be NULL");
|
||||||
|
|
||||||
|
// Change char from ASCII to a tile index.
|
||||||
int32_t tileIndex = (int32_t)(c) - TEXT_CHAR_START;
|
int32_t tileIndex = (int32_t)(c) - TEXT_CHAR_START;
|
||||||
if(tileIndex < 0 || tileIndex >= font->tileset.tileCount) {
|
if(tileIndex < 0 || tileIndex >= font->tileset->tileCount) {
|
||||||
tileIndex = ((int32_t)'@') - TEXT_CHAR_START;
|
tileIndex = ((int32_t)'@') - TEXT_CHAR_START;
|
||||||
}
|
}
|
||||||
assertTrue(
|
assertTrue(
|
||||||
tileIndex >= 0 && tileIndex <= font->tileset.tileCount,
|
tileIndex >= 0 && tileIndex <= font->tileset->tileCount,
|
||||||
"Character is out of bounds for font tiles"
|
"Character is out of bounds for font tiles"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Create sprite.
|
||||||
vec4 uv;
|
vec4 uv;
|
||||||
tilesetTileGetUV(&font->tileset, tileIndex, uv);
|
tilesetTileGetUV(font->tileset, tileIndex, uv);
|
||||||
|
|
||||||
errorChain(spriteBatchPush(
|
spritebatchsprite_t sprite;
|
||||||
x, y,
|
sprite.min[0] = pos[0];
|
||||||
x + font->tileset.tileWidth,
|
sprite.min[1] = pos[1];
|
||||||
y + font->tileset.tileHeight,
|
sprite.min[2] = 0.0f;
|
||||||
#if MESH_ENABLE_COLOR
|
sprite.max[0] = pos[0] + font->tileset->tileWidth;
|
||||||
color,
|
sprite.max[1] = pos[1] + font->tileset->tileHeight;
|
||||||
#endif
|
sprite.max[2] = 0.0f;
|
||||||
uv[0], uv[1], uv[2], uv[3]
|
sprite.uvMin[0] = uv[0];
|
||||||
));
|
sprite.uvMin[1] = uv[1];
|
||||||
errorOk();
|
sprite.uvMax[0] = uv[2];
|
||||||
|
sprite.uvMax[1] = uv[3];
|
||||||
|
return sprite;
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t textDraw(
|
errorret_t textDraw(
|
||||||
@@ -70,10 +82,20 @@ errorret_t textDraw(
|
|||||||
) {
|
) {
|
||||||
assertNotNull(text, "Text cannot be NULL");
|
assertNotNull(text, "Text cannot be NULL");
|
||||||
|
|
||||||
|
spritebatchsprite_t sprite;
|
||||||
|
shadermaterial_t material = {
|
||||||
|
.unlit = {
|
||||||
|
.color = color,
|
||||||
|
.texture = font->texture
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
float_t posX = x;
|
float_t posX = x;
|
||||||
float_t posY = y;
|
float_t posY = y;
|
||||||
|
|
||||||
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, &font->texture));
|
errorChain(shaderSetTexture(
|
||||||
|
&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, font->texture
|
||||||
|
));
|
||||||
|
|
||||||
#if MESH_ENABLE_COLOR
|
#if MESH_ENABLE_COLOR
|
||||||
#else
|
#else
|
||||||
@@ -85,23 +107,18 @@ errorret_t textDraw(
|
|||||||
while((c = text[i++]) != '\0') {
|
while((c = text[i++]) != '\0') {
|
||||||
if(c == '\n') {
|
if(c == '\n') {
|
||||||
posX = x;
|
posX = x;
|
||||||
posY += font->tileset.tileHeight;
|
posY += font->tileset->tileHeight;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(c == ' ') {
|
if(c == ' ') {
|
||||||
posX += font->tileset.tileWidth;
|
posX += font->tileset->tileWidth;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
errorChain(textDrawChar(
|
sprite = textGetSprite((vec2){posX, posY}, c, font);
|
||||||
posX, posY, c,
|
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
|
||||||
#if MESH_ENABLE_COLOR
|
posX += font->tileset->tileWidth;
|
||||||
color,
|
|
||||||
#endif
|
|
||||||
font
|
|
||||||
));
|
|
||||||
posX += font->tileset.tileWidth;
|
|
||||||
}
|
}
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
@@ -117,7 +134,7 @@ void textMeasure(
|
|||||||
assertNotNull(outHeight, "Output height pointer cannot be NULL");
|
assertNotNull(outHeight, "Output height pointer cannot be NULL");
|
||||||
|
|
||||||
int32_t width = 0;
|
int32_t width = 0;
|
||||||
int32_t height = font->tileset.tileHeight;
|
int32_t height = font->tileset->tileHeight;
|
||||||
int32_t lineWidth = 0;
|
int32_t lineWidth = 0;
|
||||||
|
|
||||||
char_t c;
|
char_t c;
|
||||||
@@ -126,11 +143,11 @@ void textMeasure(
|
|||||||
if(c == '\n') {
|
if(c == '\n') {
|
||||||
if(lineWidth > width) width = lineWidth;
|
if(lineWidth > width) width = lineWidth;
|
||||||
lineWidth = 0;
|
lineWidth = 0;
|
||||||
height += font->tileset.tileHeight;
|
height += font->tileset->tileHeight;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
lineWidth += font->tileset.tileWidth;
|
lineWidth += font->tileset->tileWidth;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(lineWidth > width) width = lineWidth;
|
if(lineWidth > width) width = lineWidth;
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "asset/asset.h"
|
#include "asset/asset.h"
|
||||||
#include "display/text/font.h"
|
#include "display/text/font.h"
|
||||||
|
#include "display/spritebatch/spritebatch.h"
|
||||||
|
|
||||||
#define TEXT_CHAR_START '!'
|
#define TEXT_CHAR_START '!'
|
||||||
|
|
||||||
@@ -28,23 +29,17 @@ errorret_t textInit(void);
|
|||||||
errorret_t textDispose(void);
|
errorret_t textDispose(void);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Draws a single character at the specified position.
|
* Builds a sprite for a single character at the given position.
|
||||||
*
|
*
|
||||||
* @param x The x-coordinate to draw the character at.
|
* @param pos The (x, y) position of the character in screen/world space.
|
||||||
* @param y The y-coordinate to draw the character at.
|
* @param c The character to build a sprite for.
|
||||||
* @param c The character to draw.
|
* @param font Font to use for tile lookup.
|
||||||
* @param color The color to draw the character in.
|
* @return The populated sprite ready for spriteBatchBuffer.
|
||||||
* @param font Font to use for rendering.
|
|
||||||
* @return Either an error or success result.
|
|
||||||
*/
|
*/
|
||||||
errorret_t textDrawChar(
|
spritebatchsprite_t textGetSprite(
|
||||||
const float_t x,
|
const vec2 pos,
|
||||||
const float_t y,
|
|
||||||
const char_t c,
|
const char_t c,
|
||||||
#if MESH_ENABLE_COLOR
|
const font_t *font
|
||||||
const color_t color,
|
|
||||||
#endif
|
|
||||||
font_t *font
|
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+12
-11
@@ -23,18 +23,19 @@
|
|||||||
#include "network/network.h"
|
#include "network/network.h"
|
||||||
#include "system/system.h"
|
#include "system/system.h"
|
||||||
#include "console/console.h"
|
#include "console/console.h"
|
||||||
|
#include "script/script.h"
|
||||||
#include "item/backpack.h"
|
#include "item/backpack.h"
|
||||||
#include "save/save.h"
|
#include "save/save.h"
|
||||||
|
|
||||||
#include "scene/initial/initialscene.h"
|
|
||||||
|
|
||||||
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;
|
||||||
ENGINE.argv = argv;
|
ENGINE.argv = argv;
|
||||||
|
ENGINE.version = DUSK_VERSION;
|
||||||
|
|
||||||
// Init systems. Order is important.
|
// Init systems. Order is important.
|
||||||
errorChain(systemInit());
|
errorChain(systemInit());
|
||||||
@@ -47,17 +48,18 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
|||||||
errorChain(displayInit());
|
errorChain(displayInit());
|
||||||
errorChain(uiInit());
|
errorChain(uiInit());
|
||||||
errorChain(uiTextboxInit());
|
errorChain(uiTextboxInit());
|
||||||
|
|
||||||
errorChain(cutsceneInit());
|
errorChain(cutsceneInit());
|
||||||
errorChain(sceneInit());
|
errorChain(sceneInit());
|
||||||
entityManagerInit();
|
entityManagerInit();
|
||||||
backpackInit();
|
backpackInit();
|
||||||
physicsManagerInit();
|
physicsManagerInit();
|
||||||
errorChain(networkInit());
|
errorChain(networkInit());
|
||||||
|
errorChain(scriptInit());
|
||||||
|
|
||||||
/* Run the init script. */
|
|
||||||
consolePrint("Engine initialized");
|
consolePrint("Engine initialized");
|
||||||
sceneSet(SCENE_TYPE_INITIAL);
|
|
||||||
|
errorChain(scriptExecFile("init.js"));
|
||||||
|
errorChain(sceneSet("testscene.js"));
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
@@ -68,18 +70,16 @@ errorret_t engineUpdate(void) {
|
|||||||
timeUpdate();
|
timeUpdate();
|
||||||
inputUpdate();
|
inputUpdate();
|
||||||
consoleUpdate();
|
consoleUpdate();
|
||||||
|
entityManagerUpdate();
|
||||||
uiUpdate();
|
uiUpdate();
|
||||||
errorChain(uiTextboxUpdate());
|
errorChain(uiTextboxUpdate());
|
||||||
physicsManagerUpdate();
|
physicsManagerUpdate();
|
||||||
errorChain(displayUpdate());
|
errorChain(displayUpdate());
|
||||||
|
errorChain(cutsceneUpdate());
|
||||||
|
sceneUpdate();
|
||||||
|
errorChain(assetUpdate());
|
||||||
|
|
||||||
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
|
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
|
||||||
|
|
||||||
// Scene update occurs last because only after rendering would we want to do
|
|
||||||
// scene switching, refer to sceneSet() for information.
|
|
||||||
errorChain(cutsceneUpdate());
|
|
||||||
errorChain(sceneUpdate());
|
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,6 +98,7 @@ errorret_t engineDispose(void) {
|
|||||||
consoleDispose();
|
consoleDispose();
|
||||||
errorChain(displayDispose());
|
errorChain(displayDispose());
|
||||||
// errorChain(saveDispose());
|
// errorChain(saveDispose());
|
||||||
|
errorChain(scriptDispose());
|
||||||
errorChain(assetDispose());
|
errorChain(assetDispose());
|
||||||
|
|
||||||
errorOk();
|
errorOk();
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ typedef struct {
|
|||||||
bool_t running;
|
bool_t running;
|
||||||
int32_t argc;
|
int32_t argc;
|
||||||
const char_t **argv;
|
const char_t **argv;
|
||||||
|
const char_t *version;
|
||||||
} engine_t;
|
} engine_t;
|
||||||
|
|
||||||
extern engine_t ENGINE;
|
extern engine_t ENGINE;
|
||||||
|
|||||||
@@ -12,12 +12,13 @@
|
|||||||
componentdefinition_t COMPONENT_DEFINITIONS[] = {
|
componentdefinition_t COMPONENT_DEFINITIONS[] = {
|
||||||
[COMPONENT_TYPE_NULL] = { 0 },
|
[COMPONENT_TYPE_NULL] = { 0 },
|
||||||
|
|
||||||
#define X(enm, type, field, iMethod, dMethod) \
|
#define X(enm, type, field, iMethod, dMethod, rMethod) \
|
||||||
[COMPONENT_TYPE_##enm] = { \
|
[COMPONENT_TYPE_##enm] = { \
|
||||||
.enumName = #enm, \
|
.enumName = #enm, \
|
||||||
.name = #field, \
|
.name = #field, \
|
||||||
.init = iMethod, \
|
.init = iMethod, \
|
||||||
.dispose = dMethod \
|
.dispose = dMethod, \
|
||||||
|
.render = rMethod \
|
||||||
},
|
},
|
||||||
|
|
||||||
#include "componentlist.h"
|
#include "componentlist.h"
|
||||||
@@ -114,6 +115,19 @@ entityid_t componentGetEntitiesWithComponent(
|
|||||||
return written;
|
return written;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
errorret_t componentRenderAll(void) {
|
||||||
|
for(entityid_t eid = 0; eid < ENTITY_COUNT_MAX; eid++) {
|
||||||
|
if(!(ENTITY_MANAGER.entities[eid].state & ENTITY_STATE_ACTIVE)) continue;
|
||||||
|
for(componentid_t cid = 0; cid < ENTITY_COMPONENT_COUNT_MAX; cid++) {
|
||||||
|
component_t *cmp = &ENTITY_MANAGER.components[componentGetIndex(eid, cid)];
|
||||||
|
if(cmp->type == COMPONENT_TYPE_NULL) continue;
|
||||||
|
if(!COMPONENT_DEFINITIONS[cmp->type].render) continue;
|
||||||
|
errorChain(COMPONENT_DEFINITIONS[cmp->type].render(eid, cid));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
errorOk();
|
||||||
|
}
|
||||||
|
|
||||||
void componentDispose(
|
void componentDispose(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId
|
const componentid_t componentId
|
||||||
|
|||||||
@@ -8,13 +8,13 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "entitybase.h"
|
#include "entitybase.h"
|
||||||
|
|
||||||
#define X(enumName, type, field, init, dispose) \
|
#define X(enumName, type, field, init, dispose, render) \
|
||||||
// do nothing
|
// do nothing
|
||||||
#include "componentlist.h"
|
#include "componentlist.h"
|
||||||
#undef X
|
#undef X
|
||||||
|
|
||||||
typedef union {
|
typedef union {
|
||||||
#define X(enumName, type, field, init, dispose) type field;
|
#define X(enumName, type, field, init, dispose, render) type field;
|
||||||
#include "componentlist.h"
|
#include "componentlist.h"
|
||||||
#undef X
|
#undef X
|
||||||
} componentdata_t;
|
} componentdata_t;
|
||||||
@@ -24,12 +24,13 @@ typedef struct {
|
|||||||
const char_t *name;
|
const char_t *name;
|
||||||
void (*init)(const entityid_t, const componentid_t);
|
void (*init)(const entityid_t, const componentid_t);
|
||||||
void (*dispose)(const entityid_t, const componentid_t);
|
void (*dispose)(const entityid_t, const componentid_t);
|
||||||
|
errorret_t (*render)(const entityid_t, const componentid_t);
|
||||||
} componentdefinition_t;
|
} componentdefinition_t;
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
COMPONENT_TYPE_NULL,
|
COMPONENT_TYPE_NULL,
|
||||||
|
|
||||||
#define X(enumName, type, field, init, dispose) \
|
#define X(enumName, type, field, init, dispose, render) \
|
||||||
COMPONENT_TYPE_##enumName,
|
COMPONENT_TYPE_##enumName,
|
||||||
#include "componentlist.h"
|
#include "componentlist.h"
|
||||||
#undef X
|
#undef X
|
||||||
@@ -100,11 +101,20 @@ entityid_t componentGetEntitiesWithComponent(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Disposes of a component for the entity with component ID.
|
* Disposes of a component for the entity with component ID.
|
||||||
*
|
*
|
||||||
* @param entityId The entity ID.
|
* @param entityId The entity ID.
|
||||||
* @param componentId The component ID.
|
* @param componentId The component ID.
|
||||||
*/
|
*/
|
||||||
void componentDispose(
|
void componentDispose(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId
|
const componentid_t componentId
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls the render callback on every active component that defines one.
|
||||||
|
* Iterates all active entities and all their component slots. No-op for
|
||||||
|
* components whose definition has render == NULL.
|
||||||
|
*
|
||||||
|
* @return Error state.
|
||||||
|
*/
|
||||||
|
errorret_t componentRenderAll(void);
|
||||||
@@ -5,5 +5,4 @@
|
|||||||
|
|
||||||
add_subdirectory(display)
|
add_subdirectory(display)
|
||||||
add_subdirectory(physics)
|
add_subdirectory(physics)
|
||||||
add_subdirectory(script)
|
|
||||||
add_subdirectory(trigger)
|
add_subdirectory(trigger)
|
||||||
@@ -16,7 +16,7 @@ void entityCameraInit(const entityid_t ent, const componentid_t comp) {
|
|||||||
ent, comp, COMPONENT_TYPE_CAMERA
|
ent, comp, COMPONENT_TYPE_CAMERA
|
||||||
);
|
);
|
||||||
cam->nearClip = 0.1f;
|
cam->nearClip = 0.1f;
|
||||||
cam->farClip = 100.0f;
|
cam->farClip = 5000.0f;
|
||||||
cam->projType = ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE;
|
cam->projType = ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE;
|
||||||
cam->perspective.fov = glm_rad(45.0f);
|
cam->perspective.fov = glm_rad(45.0f);
|
||||||
}
|
}
|
||||||
@@ -66,7 +66,7 @@ entityid_t entityCameraGetCurrent(void) {
|
|||||||
entityid_t count = componentGetEntitiesWithComponent(
|
entityid_t count = componentGetEntitiesWithComponent(
|
||||||
COMPONENT_TYPE_CAMERA, camEnts, camComps
|
COMPONENT_TYPE_CAMERA, camEnts, camComps
|
||||||
);
|
);
|
||||||
if(count == 0) return ENTITY_COUNT_MAX;
|
if(count == 0) return ENTITY_ID_INVALID;
|
||||||
return camEnts[0];
|
return camEnts[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,6 +83,30 @@ void entityCameraGetForward(const entityid_t entityId, vec2 out) {
|
|||||||
out[1] = fz;
|
out[1] = fz;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void entityCameraLookAtPixelPerfect(
|
||||||
|
const entityid_t ent,
|
||||||
|
const componentid_t posComp,
|
||||||
|
const componentid_t camComp,
|
||||||
|
const vec3 point,
|
||||||
|
const vec3 eyeOffset,
|
||||||
|
const float_t scale
|
||||||
|
) {
|
||||||
|
entitycamera_t *cam = (entitycamera_t *)componentGetData(
|
||||||
|
ent, camComp, COMPONENT_TYPE_CAMERA
|
||||||
|
);
|
||||||
|
float_t dist = (
|
||||||
|
(float_t)SCREEN.height / (2.0f * scale * tanf(cam->perspective.fov * 0.5f))
|
||||||
|
);
|
||||||
|
|
||||||
|
vec3 eye = {
|
||||||
|
point[0] + eyeOffset[0],
|
||||||
|
point[1] + dist + eyeOffset[1],
|
||||||
|
point[2] + eyeOffset[2]
|
||||||
|
};
|
||||||
|
vec3 up = { 0.0f, 0.0f, -1.0f };
|
||||||
|
entityPositionLookAt(ent, posComp, eye, (float_t *)point, up);
|
||||||
|
}
|
||||||
|
|
||||||
void entityCameraGetRight(const entityid_t entityId, vec2 out) {
|
void entityCameraGetRight(const entityid_t entityId, vec2 out) {
|
||||||
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
|
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
|
||||||
entityposition_t *pos = entityPositionGet(entityId, posComp);
|
entityposition_t *pos = entityPositionGet(entityId, posComp);
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ void entityCameraGetProjection(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the entity ID of the first active camera, or ENTITY_COUNT_MAX if
|
* Returns the entity ID of the first active camera, or ENTITY_ID_INVALID if
|
||||||
* none are active.
|
* none are active.
|
||||||
*/
|
*/
|
||||||
entityid_t entityCameraGetCurrent(void);
|
entityid_t entityCameraGetCurrent(void);
|
||||||
@@ -76,4 +76,24 @@ void entityCameraGetForward(const entityid_t entityId, vec2 out);
|
|||||||
* @param entityId The camera entity ID.
|
* @param entityId The camera entity ID.
|
||||||
* @param out Output vec2: {rightX, rightZ} normalized.
|
* @param out Output vec2: {rightX, rightZ} normalized.
|
||||||
*/
|
*/
|
||||||
void entityCameraGetRight(const entityid_t entityId, vec2 out);
|
void entityCameraGetRight(const entityid_t entityId, vec2 out);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Positions the camera to look at a 3D point at a pixel-perfect distance
|
||||||
|
* derived from the camera's FOV and screen height.
|
||||||
|
*
|
||||||
|
* @param ent The camera entity ID.
|
||||||
|
* @param posComp The position component ID.
|
||||||
|
* @param camComp The camera component ID.
|
||||||
|
* @param point World position to look at.
|
||||||
|
* @param eyeOffset Offset added to the eye position only (not the target).
|
||||||
|
* @param scale Pixels per world unit. 1.0 = pixel perfect, 2.0 = 2px per unit.
|
||||||
|
*/
|
||||||
|
void entityCameraLookAtPixelPerfect(
|
||||||
|
const entityid_t ent,
|
||||||
|
const componentid_t posComp,
|
||||||
|
const componentid_t camComp,
|
||||||
|
const vec3 point,
|
||||||
|
const vec3 eyeOffset,
|
||||||
|
const float_t scale
|
||||||
|
);
|
||||||
@@ -7,25 +7,82 @@
|
|||||||
|
|
||||||
#include "entity/entitymanager.h"
|
#include "entity/entitymanager.h"
|
||||||
|
|
||||||
// Lazily recompute worldTransform from the parent chain.
|
// Decompose localTransform into the PRS cache. Only called when PRS_DIRTY.
|
||||||
static void entityPositionUpdateWorld(entityposition_t *pos) {
|
static void entityPositionEnsurePRS(entityposition_t *pos) {
|
||||||
if(!pos->dirty) return;
|
if(!(pos->flags & ENTITY_POSITION_FLAG_PRS_DIRTY)) return;
|
||||||
|
entityPositionDecompose(pos);
|
||||||
|
pos->flags &= ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
}
|
||||||
|
|
||||||
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
// Rebuild localTransform from the PRS cache. Only rebuilds what changed.
|
||||||
glm_mat4_copy(pos->localTransform, pos->worldTransform);
|
static void entityPositionEnsureLocal(entityposition_t *pos) {
|
||||||
} else {
|
const uint8_t dirty = pos->flags & (
|
||||||
|
ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY
|
||||||
|
);
|
||||||
|
if(!dirty) return;
|
||||||
|
|
||||||
|
if(dirty & ENTITY_POSITION_FLAG_ROTATION_DIRTY) {
|
||||||
|
// Rotation or scale changed: rebuild columns 0-2 analytically (XYZ euler order).
|
||||||
|
const float c0 = cosf(pos->rotation[0]), s0 = sinf(pos->rotation[0]);
|
||||||
|
const float c1 = cosf(pos->rotation[1]), s1 = sinf(pos->rotation[1]);
|
||||||
|
const float c2 = cosf(pos->rotation[2]), s2 = sinf(pos->rotation[2]);
|
||||||
|
const float s0s1 = s0 * s1;
|
||||||
|
const float c0s1 = c0 * s1;
|
||||||
|
|
||||||
|
pos->localTransform[0][0] = c1 * c2 * pos->scale[0];
|
||||||
|
pos->localTransform[0][1] = (c0 * s2 + s0s1 * c2) * pos->scale[0];
|
||||||
|
pos->localTransform[0][2] = (s0 * s2 - c0s1 * c2) * pos->scale[0];
|
||||||
|
pos->localTransform[0][3] = 0.0f;
|
||||||
|
|
||||||
|
pos->localTransform[1][0] = -c1 * s2 * pos->scale[1];
|
||||||
|
pos->localTransform[1][1] = (c0 * c2 - s0s1 * s2) * pos->scale[1];
|
||||||
|
pos->localTransform[1][2] = (s0 * c2 + c0s1 * s2) * pos->scale[1];
|
||||||
|
pos->localTransform[1][3] = 0.0f;
|
||||||
|
|
||||||
|
pos->localTransform[2][0] = s1 * pos->scale[2];
|
||||||
|
pos->localTransform[2][1] = -s0 * c1 * pos->scale[2];
|
||||||
|
pos->localTransform[2][2] = c0 * c1 * pos->scale[2];
|
||||||
|
pos->localTransform[2][3] = 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(dirty & ENTITY_POSITION_FLAG_POSITION_DIRTY) {
|
||||||
|
// Only position changed: update column 3 only (no trig needed).
|
||||||
|
pos->localTransform[3][0] = pos->position[0];
|
||||||
|
pos->localTransform[3][1] = pos->position[1];
|
||||||
|
pos->localTransform[3][2] = pos->position[2];
|
||||||
|
pos->localTransform[3][3] = 1.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos->flags &= ~(ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recompute worldTransform from the parent chain. Only called when WORLD_DIRTY.
|
||||||
|
static void entityPositionEnsureWorld(entityposition_t *pos) {
|
||||||
|
if(!(pos->flags & ENTITY_POSITION_FLAG_WORLD_DIRTY)) return;
|
||||||
|
entityPositionEnsureLocal(pos);
|
||||||
|
|
||||||
|
if(pos->parentEntityId != ENTITY_ID_INVALID) {
|
||||||
|
// Parented: world = parent.world × local. worldTransform must be written
|
||||||
|
// 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
|
||||||
);
|
);
|
||||||
entityPositionUpdateWorld(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) {
|
||||||
|
// Parentless root with children: children need a valid worldTransform to
|
||||||
|
// multiply against, but world == local, so just copy.
|
||||||
|
glm_mat4_copy(pos->localTransform, pos->worldTransform);
|
||||||
}
|
}
|
||||||
|
// Parentless leaf: world == local. Getters read localTransform directly;
|
||||||
|
// no copy needed.
|
||||||
|
|
||||||
pos->dirty = false;
|
pos->flags &= ~ENTITY_POSITION_FLAG_WORLD_DIRTY;
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionMarkDirty(entityposition_t *pos) {
|
void entityPositionMarkDirty(entityposition_t *pos) {
|
||||||
pos->dirty = true;
|
if(pos->flags & ENTITY_POSITION_FLAG_WORLD_DIRTY) return;
|
||||||
|
pos->flags |= ENTITY_POSITION_FLAG_WORLD_DIRTY;
|
||||||
for(uint8_t i = 0; i < pos->childCount; i++) {
|
for(uint8_t i = 0; i < pos->childCount; i++) {
|
||||||
entityposition_t *child = componentGetData(
|
entityposition_t *child = componentGetData(
|
||||||
pos->childEntityIds[i], pos->childComponentIds[i], COMPONENT_TYPE_POSITION
|
pos->childEntityIds[i], pos->childComponentIds[i], COMPONENT_TYPE_POSITION
|
||||||
@@ -42,29 +99,31 @@ void entityPositionInit(
|
|||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
|
|
||||||
|
pos->flags = 0;
|
||||||
|
pos->parentEntityId = ENTITY_ID_INVALID;
|
||||||
|
pos->parentComponentId = COMPONENT_ID_INVALID;
|
||||||
|
pos->childCount = 0;
|
||||||
glm_vec3_zero(pos->position);
|
glm_vec3_zero(pos->position);
|
||||||
glm_vec3_zero(pos->rotation);
|
glm_vec3_zero(pos->rotation);
|
||||||
glm_vec3_one(pos->scale);
|
glm_vec3_one(pos->scale);
|
||||||
glm_mat4_identity(pos->localTransform);
|
glm_mat4_identity(pos->localTransform);
|
||||||
glm_mat4_identity(pos->worldTransform);
|
glm_mat4_identity(pos->worldTransform);
|
||||||
pos->dirty = false;
|
|
||||||
pos->parentEntityId = ENTITY_ID_INVALID;
|
|
||||||
pos->parentComponentId = COMPONENT_ID_INVALID;
|
|
||||||
pos->childCount = 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionLookAt(
|
void entityPositionLookAt(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
|
vec3 eye,
|
||||||
vec3 target,
|
vec3 target,
|
||||||
vec3 up,
|
vec3 up
|
||||||
vec3 eye
|
|
||||||
) {
|
) {
|
||||||
entityposition_t *pos = componentGetData(
|
entityposition_t *pos = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
glm_lookat(eye, target, up, pos->localTransform);
|
glm_lookat(eye, target, up, pos->localTransform);
|
||||||
entityPositionDecompose(pos);
|
// localTransform is now authoritative; PRS cache is stale.
|
||||||
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_PRS_DIRTY)
|
||||||
|
& ~(ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY);
|
||||||
entityPositionMarkDirty(pos);
|
entityPositionMarkDirty(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,8 +135,11 @@ void entityPositionGetTransform(
|
|||||||
entityposition_t *pos = componentGetData(
|
entityposition_t *pos = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
entityPositionUpdateWorld(pos);
|
entityPositionEnsureWorld(pos);
|
||||||
glm_mat4_copy(pos->worldTransform, dest);
|
glm_mat4_copy(
|
||||||
|
pos->parentEntityId == ENTITY_ID_INVALID ? pos->localTransform : pos->worldTransform,
|
||||||
|
dest
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionGetLocalTransform(
|
void entityPositionGetLocalTransform(
|
||||||
@@ -88,10 +150,11 @@ void entityPositionGetLocalTransform(
|
|||||||
entityposition_t *pos = componentGetData(
|
entityposition_t *pos = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
|
entityPositionEnsureLocal(pos);
|
||||||
glm_mat4_copy(pos->localTransform, dest);
|
glm_mat4_copy(pos->localTransform, dest);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionGetPosition(
|
void entityPositionGetLocalPosition(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 dest
|
vec3 dest
|
||||||
@@ -99,10 +162,59 @@ void entityPositionGetPosition(
|
|||||||
entityposition_t *pos = componentGetData(
|
entityposition_t *pos = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
|
entityPositionEnsurePRS(pos);
|
||||||
glm_vec3_copy(pos->position, dest);
|
glm_vec3_copy(pos->position, dest);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionSetPosition(
|
void entityPositionGetWorldPosition(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 dest
|
||||||
|
) {
|
||||||
|
entityposition_t *pos = componentGetData(
|
||||||
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
||||||
|
entityPositionEnsurePRS(pos);
|
||||||
|
glm_vec3_copy(pos->position, dest);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entityPositionEnsureWorld(pos);
|
||||||
|
dest[0] = pos->worldTransform[3][0];
|
||||||
|
dest[1] = pos->worldTransform[3][1];
|
||||||
|
dest[2] = pos->worldTransform[3][2];
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityPositionSetWorldPosition(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 position
|
||||||
|
) {
|
||||||
|
entityposition_t *pos = componentGetData(
|
||||||
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
||||||
|
glm_vec3_copy(position, pos->position);
|
||||||
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_POSITION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entityposition_t *parent = componentGetData(
|
||||||
|
pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
entityPositionEnsureWorld(parent);
|
||||||
|
mat4 invParent;
|
||||||
|
glm_mat4_inv(parent->worldTransform, invParent);
|
||||||
|
vec3 localPos;
|
||||||
|
glm_mat4_mulv3(invParent, position, 1.0f, localPos);
|
||||||
|
glm_vec3_copy(localPos, pos->position);
|
||||||
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_POSITION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityPositionSetLocalPosition(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 position
|
vec3 position
|
||||||
@@ -111,10 +223,12 @@ void entityPositionSetPosition(
|
|||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
glm_vec3_copy(position, pos->position);
|
glm_vec3_copy(position, pos->position);
|
||||||
entityPositionRebuild(pos);
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_POSITION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionGetRotation(
|
void entityPositionGetLocalRotation(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 dest
|
vec3 dest
|
||||||
@@ -122,10 +236,48 @@ void entityPositionGetRotation(
|
|||||||
entityposition_t *pos = componentGetData(
|
entityposition_t *pos = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
|
entityPositionEnsurePRS(pos);
|
||||||
glm_vec3_copy(pos->rotation, dest);
|
glm_vec3_copy(pos->rotation, dest);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionSetRotation(
|
void entityPositionGetWorldRotation(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 dest
|
||||||
|
) {
|
||||||
|
entityposition_t *pos = componentGetData(
|
||||||
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
||||||
|
entityPositionEnsurePRS(pos);
|
||||||
|
glm_vec3_copy(pos->rotation, dest);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entityPositionEnsureWorld(pos);
|
||||||
|
const float (*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 sy = sqrtf(wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][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 r10 = sy > 0.0f ? wt[1][0]/sy : 0.0f;
|
||||||
|
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 r11 = sy > 0.0f ? wt[1][1]/sy : 0.0f;
|
||||||
|
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 sinBeta = glm_clamp(r20, -1.0f, 1.0f);
|
||||||
|
dest[1] = asinf(sinBeta);
|
||||||
|
const float cosBeta = cosf(dest[1]);
|
||||||
|
if(fabsf(cosBeta) > 1e-6f) {
|
||||||
|
dest[0] = atan2f(-r21, r22);
|
||||||
|
dest[2] = atan2f(-r10, r00);
|
||||||
|
} else {
|
||||||
|
dest[2] = 0.0f;
|
||||||
|
dest[0] = (sinBeta > 0.0f) ? atan2f(r01, r11) : -atan2f(r01, r11);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityPositionSetLocalRotation(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 rotation
|
vec3 rotation
|
||||||
@@ -134,10 +286,87 @@ void entityPositionSetRotation(
|
|||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
glm_vec3_copy(rotation, pos->rotation);
|
glm_vec3_copy(rotation, pos->rotation);
|
||||||
entityPositionRebuild(pos);
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionGetScale(
|
void entityPositionSetWorldRotation(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 rotation
|
||||||
|
) {
|
||||||
|
entityposition_t *pos = componentGetData(
|
||||||
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
||||||
|
glm_vec3_copy(rotation, pos->rotation);
|
||||||
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entityposition_t *parent = componentGetData(
|
||||||
|
pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
entityPositionEnsureWorld(parent);
|
||||||
|
|
||||||
|
// Build target world rotation matrix (unit scale) from XYZ euler.
|
||||||
|
const float c0 = cosf(rotation[0]), s0 = sinf(rotation[0]);
|
||||||
|
const float c1 = cosf(rotation[1]), s1 = sinf(rotation[1]);
|
||||||
|
const float c2 = cosf(rotation[2]), s2 = sinf(rotation[2]);
|
||||||
|
const float s0s1 = s0*s1, c0s1 = c0*s1;
|
||||||
|
// 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 wr10 = -c1*s2, wr11 = c0*c2 - s0s1*s2, wr12 = s0*c2 + c0s1*s2;
|
||||||
|
const float wr20 = s1, wr21 = -s0*c1, wr22 = c0*c1;
|
||||||
|
|
||||||
|
// Normalize parent world columns to extract pure rotation.
|
||||||
|
const float (*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 psy = sqrtf(pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][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 pr01 = psx > 0.f ? pt[0][1]/psx : 0.f;
|
||||||
|
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 pr11 = psy > 0.f ? pt[1][1]/psy : 0.f;
|
||||||
|
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 pr21 = psz > 0.f ? pt[2][1]/psz : 0.f;
|
||||||
|
const float pr22 = psz > 0.f ? pt[2][2]/psz : 0.f;
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// euler extraction (stored column-major: [col][row] = math [row][col]).
|
||||||
|
// sinBeta = stored[2][0] = math[0][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]
|
||||||
|
// 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 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 lr01 = pr10*wr00 + pr11*wr10 + pr12*wr20; // math[1][0]
|
||||||
|
const float 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 lr22 = pr20*wr02 + pr21*wr12 + pr22*wr22; // math[2][2] → r22
|
||||||
|
|
||||||
|
const float sinBeta = glm_clamp(lr20, -1.0f, 1.0f);
|
||||||
|
pos->rotation[1] = asinf(sinBeta);
|
||||||
|
const float cosBeta = cosf(pos->rotation[1]);
|
||||||
|
if(fabsf(cosBeta) > 1e-6f) {
|
||||||
|
pos->rotation[0] = atan2f(-lr21, lr22);
|
||||||
|
pos->rotation[2] = atan2f(-lr10, lr00);
|
||||||
|
} else {
|
||||||
|
pos->rotation[2] = 0.0f;
|
||||||
|
pos->rotation[0] = (sinBeta > 0.0f) ? atan2f(lr01, lr11) : -atan2f(lr01, lr11);
|
||||||
|
}
|
||||||
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityPositionGetLocalScale(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 dest
|
vec3 dest
|
||||||
@@ -145,10 +374,31 @@ void entityPositionGetScale(
|
|||||||
entityposition_t *pos = componentGetData(
|
entityposition_t *pos = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
|
entityPositionEnsurePRS(pos);
|
||||||
glm_vec3_copy(pos->scale, dest);
|
glm_vec3_copy(pos->scale, dest);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionSetScale(
|
void entityPositionGetWorldScale(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 dest
|
||||||
|
) {
|
||||||
|
entityposition_t *pos = componentGetData(
|
||||||
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
||||||
|
entityPositionEnsurePRS(pos);
|
||||||
|
glm_vec3_copy(pos->scale, dest);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entityPositionEnsureWorld(pos);
|
||||||
|
const float (*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[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]);
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityPositionSetLocalScale(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 scale
|
vec3 scale
|
||||||
@@ -157,7 +407,40 @@ void entityPositionSetScale(
|
|||||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
);
|
);
|
||||||
glm_vec3_copy(scale, pos->scale);
|
glm_vec3_copy(scale, pos->scale);
|
||||||
entityPositionRebuild(pos);
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityPositionSetWorldScale(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 scale
|
||||||
|
) {
|
||||||
|
entityposition_t *pos = componentGetData(
|
||||||
|
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
||||||
|
glm_vec3_copy(scale, pos->scale);
|
||||||
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entityposition_t *parent = componentGetData(
|
||||||
|
pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
|
||||||
|
);
|
||||||
|
entityPositionEnsureWorld(parent);
|
||||||
|
const float (*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 psy = sqrtf(pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]);
|
||||||
|
const float 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[1] = psy > 0.0f ? scale[1] / psy : scale[1];
|
||||||
|
pos->scale[2] = psz > 0.0f ? scale[2] / psz : scale[2];
|
||||||
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
|
||||||
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
|
entityPositionMarkDirty(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionSetParent(
|
void entityPositionSetParent(
|
||||||
@@ -218,12 +501,8 @@ entityposition_t *entityPositionGet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
void entityPositionRebuild(entityposition_t *pos) {
|
void entityPositionRebuild(entityposition_t *pos) {
|
||||||
glm_mat4_identity(pos->localTransform);
|
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY)
|
||||||
glm_translate(pos->localTransform, pos->position);
|
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||||
glm_rotate_x(pos->localTransform, pos->rotation[0], pos->localTransform);
|
|
||||||
glm_rotate_y(pos->localTransform, pos->rotation[1], pos->localTransform);
|
|
||||||
glm_rotate_z(pos->localTransform, pos->rotation[2], pos->localTransform);
|
|
||||||
glm_scale(pos->localTransform, pos->scale);
|
|
||||||
entityPositionMarkDirty(pos);
|
entityPositionMarkDirty(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,36 +560,33 @@ 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.
|
// Normalize columns to isolate the rotation matrix (9 floats, no mat4 needed).
|
||||||
float invS0 = pos->scale[0] > 0.0f ? 1.0f / pos->scale[0] : 0.0f;
|
const float invS0 = pos->scale[0] > 0.0f ? 1.0f / pos->scale[0] : 0.0f;
|
||||||
float invS1 = pos->scale[1] > 0.0f ? 1.0f / pos->scale[1] : 0.0f;
|
const float invS1 = pos->scale[1] > 0.0f ? 1.0f / pos->scale[1] : 0.0f;
|
||||||
float invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f;
|
const float invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f;
|
||||||
|
|
||||||
mat4 r;
|
const float r00 = pos->localTransform[0][0] * invS0;
|
||||||
glm_mat4_identity(r);
|
const float r01 = pos->localTransform[0][1] * invS0;
|
||||||
r[0][0] = pos->localTransform[0][0] * invS0;
|
const float r02 = pos->localTransform[0][2] * invS0;
|
||||||
r[0][1] = pos->localTransform[0][1] * invS0;
|
const float r10 = pos->localTransform[1][0] * invS1;
|
||||||
r[0][2] = pos->localTransform[0][2] * invS0;
|
const float r11 = pos->localTransform[1][1] * invS1;
|
||||||
r[1][0] = pos->localTransform[1][0] * invS1;
|
const float r20 = pos->localTransform[2][0] * invS2;
|
||||||
r[1][1] = pos->localTransform[1][1] * invS1;
|
const float r21 = pos->localTransform[2][1] * invS2;
|
||||||
r[1][2] = pos->localTransform[1][2] * invS1;
|
const float r22 = pos->localTransform[2][2] * invS2;
|
||||||
r[2][0] = pos->localTransform[2][0] * invS2;
|
|
||||||
r[2][1] = pos->localTransform[2][1] * invS2;
|
|
||||||
r[2][2] = 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)
|
||||||
float sinBeta = glm_clamp(r[2][0], -1.0f, 1.0f);
|
const float sinBeta = glm_clamp(r20, -1.0f, 1.0f);
|
||||||
pos->rotation[1] = asinf(sinBeta);
|
pos->rotation[1] = asinf(sinBeta);
|
||||||
float cosBeta = cosf(pos->rotation[1]);
|
const float cosBeta = cosf(pos->rotation[1]);
|
||||||
|
|
||||||
if(fabsf(cosBeta) > 1e-6f) {
|
if(fabsf(cosBeta) > 1e-6f) {
|
||||||
pos->rotation[0] = atan2f(-r[2][1], r[2][2]);
|
pos->rotation[0] = atan2f(-r21, r22);
|
||||||
pos->rotation[2] = atan2f(-r[1][0], r[0][0]);
|
pos->rotation[2] = atan2f(-r10, r00);
|
||||||
} else {
|
} else {
|
||||||
// Gimbal lock: pin Z to 0, recover X.
|
// Gimbal lock: pin Z to 0, recover X.
|
||||||
pos->rotation[2] = 0.0f;
|
pos->rotation[2] = 0.0f;
|
||||||
pos->rotation[0] = (sinBeta > 0.0f)
|
pos->rotation[0] = (sinBeta > 0.0f)
|
||||||
? atan2f(r[0][1], r[1][1])
|
? atan2f(r01, r11)
|
||||||
: -atan2f(r[0][1], r[1][1]);
|
: -atan2f(r01, r11);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,24 +8,81 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "entity/entitybase.h"
|
#include "entity/entitybase.h"
|
||||||
|
|
||||||
|
/** Maximum number of child position components this node can track. */
|
||||||
#define ENTITY_POSITION_CHILDREN_MAX 8
|
#define ENTITY_POSITION_CHILDREN_MAX 8
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PRS cache is stale. localTransform was written directly (e.g. lookAt) and
|
||||||
|
* position/rotation/scale need to be decomposed before they can be read.
|
||||||
|
*/
|
||||||
|
#define ENTITY_POSITION_FLAG_PRS_DIRTY (1 << 0)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Columns 0-2 of localTransform are stale. Rotation or scale changed; the
|
||||||
|
* basis vectors need to be rebuilt analytically before the matrix can be used.
|
||||||
|
* Does not imply column 3 (translation) is stale.
|
||||||
|
*/
|
||||||
|
#define ENTITY_POSITION_FLAG_ROTATION_DIRTY (1 << 1)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Column 3 of localTransform is stale. Position changed; only the translation
|
||||||
|
* column needs to be written. Does not imply columns 0-2 are stale.
|
||||||
|
*/
|
||||||
|
#define ENTITY_POSITION_FLAG_POSITION_DIRTY (1 << 2)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
#define ENTITY_POSITION_FLAG_WORLD_DIRTY (1 << 3)
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
mat4 localTransform;
|
/*
|
||||||
mat4 worldTransform;
|
* Hot fields — flag checks and parent/child traversal (markDirty, ensureWorld)
|
||||||
vec3 position;
|
* only touch these. Kept at the front so they share the first cache line.
|
||||||
vec3 rotation;
|
*/
|
||||||
vec3 scale;
|
|
||||||
bool dirty;
|
/** Bitmask of ENTITY_POSITION_FLAG_* values describing which caches are stale. */
|
||||||
|
uint8_t flags;
|
||||||
|
/** 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. */
|
||||||
componentid_t parentComponentId;
|
componentid_t parentComponentId;
|
||||||
|
/** Number of currently registered children. */
|
||||||
uint8_t childCount;
|
uint8_t childCount;
|
||||||
|
/** Entity IDs of child nodes. */
|
||||||
entityid_t childEntityIds[ENTITY_POSITION_CHILDREN_MAX];
|
entityid_t childEntityIds[ENTITY_POSITION_CHILDREN_MAX];
|
||||||
|
/** Component IDs of child position components. */
|
||||||
componentid_t childComponentIds[ENTITY_POSITION_CHILDREN_MAX];
|
componentid_t childComponentIds[ENTITY_POSITION_CHILDREN_MAX];
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Warm fields — read/written by PRS getters/setters.
|
||||||
|
* 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. */
|
||||||
|
vec3 position;
|
||||||
|
/** Cached local euler rotation (XYZ, radians). May be stale when ENTITY_POSITION_FLAG_PRS_DIRTY is set. */
|
||||||
|
vec3 rotation;
|
||||||
|
/** Cached local scale (XYZ). May be stale when ENTITY_POSITION_FLAG_PRS_DIRTY is set. */
|
||||||
|
vec3 scale;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Cold fields — only touched when actually rebuilding transforms.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Local transform matrix, rebuilt lazily from position/rotation/scale. */
|
||||||
|
mat4 localTransform;
|
||||||
|
/** World transform matrix, recomputed lazily from the parent chain. */
|
||||||
|
mat4 worldTransform;
|
||||||
} entityposition_t;
|
} entityposition_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the entity position component.
|
* Initializes the entity position component, setting identity transforms and
|
||||||
|
* zeroing all parent/child state.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
*/
|
*/
|
||||||
void entityPositionInit(
|
void entityPositionInit(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -35,26 +92,26 @@ void entityPositionInit(
|
|||||||
/**
|
/**
|
||||||
* Transforms the entity's local transform to look at a target point.
|
* Transforms the entity's local transform to look at a target point.
|
||||||
*
|
*
|
||||||
* @param entityId The entity ID.
|
* @param entityId The entity ID.
|
||||||
* @param componentId The component ID.
|
* @param componentId The component ID.
|
||||||
* @param target The target point to look at.
|
* @param eye The eye/camera position.
|
||||||
* @param up The up vector.
|
* @param target The target point to look at.
|
||||||
* @param eye The eye/camera position.
|
* @param up The up vector.
|
||||||
*/
|
*/
|
||||||
void entityPositionLookAt(
|
void entityPositionLookAt(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
|
vec3 eye,
|
||||||
vec3 target,
|
vec3 target,
|
||||||
vec3 up,
|
vec3 up
|
||||||
vec3 eye
|
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the world-space transform matrix, recomputing it lazily if dirty.
|
* Gets the world-space transform matrix, recomputing it lazily if dirty.
|
||||||
*
|
*
|
||||||
* @param entityId The entity ID.
|
* @param entityId The entity ID.
|
||||||
* @param componentId The component ID.
|
* @param componentId The component ID.
|
||||||
* @param dest Destination matrix.
|
* @param dest Destination matrix.
|
||||||
*/
|
*/
|
||||||
void entityPositionGetTransform(
|
void entityPositionGetTransform(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -65,9 +122,9 @@ void entityPositionGetTransform(
|
|||||||
/**
|
/**
|
||||||
* Gets the local transform matrix (does not include parent transforms).
|
* Gets the local transform matrix (does not include parent transforms).
|
||||||
*
|
*
|
||||||
* @param entityId The entity ID.
|
* @param entityId The entity ID.
|
||||||
* @param componentId The component ID.
|
* @param componentId The component ID.
|
||||||
* @param dest Destination matrix.
|
* @param dest Destination matrix.
|
||||||
*/
|
*/
|
||||||
void entityPositionGetLocalTransform(
|
void entityPositionGetLocalTransform(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -76,54 +133,171 @@ void entityPositionGetLocalTransform(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the cached local position.
|
* Gets the cached local position (XYZ). Decomposes localTransform into PRS
|
||||||
|
* first if ENTITY_POSITION_FLAG_PRS_DIRTY is set; never triggers a matrix
|
||||||
|
* rebuild or world-transform update.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param dest Destination vector.
|
||||||
*/
|
*/
|
||||||
void entityPositionGetPosition(
|
void entityPositionGetLocalPosition(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 dest
|
vec3 dest
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the local position and marks the world transform dirty.
|
* Gets the world-space position. For parentless entities this is the same as
|
||||||
|
* the local position.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param dest Destination vector.
|
||||||
*/
|
*/
|
||||||
void entityPositionSetPosition(
|
void entityPositionGetWorldPosition(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 dest
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the world-space position. For parentless entities this is equivalent to
|
||||||
|
* entityPositionSetLocalPosition. For parented entities the position is
|
||||||
|
* converted to local space via the inverted parent world transform.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param position The desired world-space position.
|
||||||
|
*/
|
||||||
|
void entityPositionSetWorldPosition(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 position
|
vec3 position
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the cached local euler rotation (XYZ, radians).
|
* Sets the local position, marks localTransform and worldTransform (self +
|
||||||
|
* descendants) dirty.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param position The new local position.
|
||||||
*/
|
*/
|
||||||
void entityPositionGetRotation(
|
void entityPositionSetLocalPosition(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 position
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the cached local euler rotation (XYZ, radians). Decomposes
|
||||||
|
* localTransform first if ENTITY_POSITION_FLAG_PRS_DIRTY is set.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param dest Destination vector.
|
||||||
|
*/
|
||||||
|
void entityPositionGetLocalRotation(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 dest
|
vec3 dest
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the local euler rotation (XYZ, radians) and marks the world transform dirty.
|
* Gets the world-space euler rotation (XYZ, radians) by decomposing the world
|
||||||
|
* transform. For parentless entities this is the same as local rotation.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param dest Destination vector.
|
||||||
*/
|
*/
|
||||||
void entityPositionSetRotation(
|
void entityPositionGetWorldRotation(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 dest
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the local euler rotation (XYZ, radians) and marks transforms dirty.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param rotation The new local rotation.
|
||||||
|
*/
|
||||||
|
void entityPositionSetLocalRotation(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 rotation
|
vec3 rotation
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the cached local scale.
|
* Sets the world-space euler rotation (XYZ, radians). For parentless entities
|
||||||
|
* this is equivalent to entityPositionSetLocalRotation. For parented entities
|
||||||
|
* the rotation is converted to local space by removing the parent world
|
||||||
|
* rotation.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param rotation The desired world-space euler rotation.
|
||||||
*/
|
*/
|
||||||
void entityPositionGetScale(
|
void entityPositionSetWorldRotation(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 rotation
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the cached local scale. Decomposes localTransform first if
|
||||||
|
* ENTITY_POSITION_FLAG_PRS_DIRTY is set.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param dest Destination vector.
|
||||||
|
*/
|
||||||
|
void entityPositionGetLocalScale(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 dest
|
vec3 dest
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the local scale and marks the world transform dirty.
|
* Gets the world-space scale by extracting column lengths from the world
|
||||||
|
* transform. For parentless entities this is the same as local scale.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param dest Destination vector.
|
||||||
*/
|
*/
|
||||||
void entityPositionSetScale(
|
void entityPositionGetWorldScale(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 dest
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the local scale and marks transforms dirty.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param scale The new local scale.
|
||||||
|
*/
|
||||||
|
void entityPositionSetLocalScale(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
vec3 scale
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the world-space scale. For parentless entities this is equivalent to
|
||||||
|
* entityPositionSetLocalScale. For parented entities the scale is converted to
|
||||||
|
* local space by dividing by the parent world scale (assumes no shear).
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @param scale The desired world-space scale.
|
||||||
|
*/
|
||||||
|
void entityPositionSetWorldScale(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
vec3 scale
|
vec3 scale
|
||||||
@@ -133,9 +307,9 @@ void entityPositionSetScale(
|
|||||||
* Sets the parent of this entity's position component.
|
* Sets the parent of this entity's position component.
|
||||||
* Pass ENTITY_ID_INVALID / COMPONENT_ID_INVALID to detach from any parent.
|
* Pass ENTITY_ID_INVALID / COMPONENT_ID_INVALID to detach from any parent.
|
||||||
*
|
*
|
||||||
* @param entityId The child entity ID.
|
* @param entityId The child entity ID.
|
||||||
* @param componentId The child component ID.
|
* @param componentId The child component ID.
|
||||||
* @param parentEntityId The parent entity ID.
|
* @param parentEntityId The parent entity ID.
|
||||||
* @param parentComponentId The parent component ID.
|
* @param parentComponentId The parent component ID.
|
||||||
*/
|
*/
|
||||||
void entityPositionSetParent(
|
void entityPositionSetParent(
|
||||||
@@ -147,7 +321,13 @@ void entityPositionSetParent(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a direct pointer to the entity position component data.
|
* Returns a direct pointer to the entity position component data.
|
||||||
* After modifying localTransform directly, call entityPositionMarkDirty().
|
* After modifying localTransform directly, call entityPositionMarkDirty() to
|
||||||
|
* set ENTITY_POSITION_FLAG_WORLD_DIRTY on self and descendants. After
|
||||||
|
* modifying PRS directly, call entityPositionRebuild() instead.
|
||||||
|
*
|
||||||
|
* @param entityId The entity ID.
|
||||||
|
* @param componentId The component ID.
|
||||||
|
* @return Pointer to the component data.
|
||||||
*/
|
*/
|
||||||
entityposition_t *entityPositionGet(
|
entityposition_t *entityPositionGet(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -155,13 +335,22 @@ entityposition_t *entityPositionGet(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rebuilds the local transform matrix from the cached position/rotation/scale,
|
* Signals that the PRS cache was modified externally. Sets both
|
||||||
* then marks this node and all descendants dirty.
|
* ENTITY_POSITION_FLAG_ROTATION_DIRTY and ENTITY_POSITION_FLAG_POSITION_DIRTY
|
||||||
|
* so all of localTransform is rebuilt lazily on the next read, clears
|
||||||
|
* ENTITY_POSITION_FLAG_PRS_DIRTY, and propagates ENTITY_POSITION_FLAG_WORLD_DIRTY
|
||||||
|
* to self and all descendants.
|
||||||
|
*
|
||||||
|
* @param pos The position component whose PRS was modified.
|
||||||
*/
|
*/
|
||||||
void entityPositionRebuild(entityposition_t *pos);
|
void entityPositionRebuild(entityposition_t *pos);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Marks this node and all descendants as having a stale world transform.
|
* Sets ENTITY_POSITION_FLAG_WORLD_DIRTY on this node and all descendants,
|
||||||
|
* indicating that worldTransform must be recomputed before it is read.
|
||||||
|
* Call this after modifying localTransform directly.
|
||||||
|
*
|
||||||
|
* @param pos The position component to mark dirty.
|
||||||
*/
|
*/
|
||||||
void entityPositionMarkDirty(entityposition_t *pos);
|
void entityPositionMarkDirty(entityposition_t *pos);
|
||||||
|
|
||||||
@@ -169,7 +358,7 @@ void entityPositionMarkDirty(entityposition_t *pos);
|
|||||||
* Disposes this entity and all of its position-component descendants
|
* Disposes this entity and all of its position-component descendants
|
||||||
* recursively. Detaches from any parent before destroying.
|
* recursively. Detaches from any parent before destroying.
|
||||||
*
|
*
|
||||||
* @param entityId The root entity ID.
|
* @param entityId The root entity ID.
|
||||||
* @param componentId The root position component ID.
|
* @param componentId The root position component ID.
|
||||||
*/
|
*/
|
||||||
void entityPositionDisposeDeep(
|
void entityPositionDisposeDeep(
|
||||||
@@ -180,5 +369,7 @@ void entityPositionDisposeDeep(
|
|||||||
/**
|
/**
|
||||||
* Decomposes the local transform matrix back into the position, rotation
|
* Decomposes the local transform matrix back into the position, rotation
|
||||||
* (XYZ euler, radians), and scale cache fields.
|
* (XYZ euler, radians), and scale cache fields.
|
||||||
|
*
|
||||||
|
* @param pos The position component to decompose.
|
||||||
*/
|
*/
|
||||||
void entityPositionDecompose(entityposition_t *pos);
|
void entityPositionDecompose(entityposition_t *pos);
|
||||||
|
|||||||
@@ -7,8 +7,12 @@
|
|||||||
|
|
||||||
#include "entityrenderable.h"
|
#include "entityrenderable.h"
|
||||||
#include "entity/entitymanager.h"
|
#include "entity/entitymanager.h"
|
||||||
|
#include "display/shader/shadermaterial.h"
|
||||||
#include "display/shader/shaderunlit.h"
|
#include "display/shader/shaderunlit.h"
|
||||||
|
#include "display/display.h"
|
||||||
#include "display/mesh/cube.h"
|
#include "display/mesh/cube.h"
|
||||||
|
#include "util/memory.h"
|
||||||
|
#include "assert/assert.h"
|
||||||
|
|
||||||
void entityRenderableInit(
|
void entityRenderableInit(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -17,20 +21,21 @@ void entityRenderableInit(
|
|||||||
entityrenderable_t *r = componentGetData(
|
entityrenderable_t *r = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||||
);
|
);
|
||||||
r->type = ENTITY_RENDERABLE_TYPE_MATERIAL;
|
memoryZero(r, sizeof(entityrenderable_t));
|
||||||
r->mesh = &CUBE_MESH_SIMPLE;
|
r->type = ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL;
|
||||||
r->shader = &SHADER_UNLIT;
|
r->data.material.shaderType = SHADER_LIST_SHADER_UNLIT;
|
||||||
r->material.unlit.color = COLOR_WHITE;
|
r->data.material.material.unlit.color = COLOR_WHITE;
|
||||||
|
r->data.material.meshes[0] = &CUBE_MESH_SIMPLE;
|
||||||
|
r->data.material.meshOffsets[0] = 0;
|
||||||
|
r->data.material.meshCounts[0] = -1;
|
||||||
|
r->data.material.meshCount = 1;
|
||||||
|
r->data.material.state.flags = DISPLAY_STATE_FLAG_DEPTH_TEST;
|
||||||
}
|
}
|
||||||
|
|
||||||
entityrenderabletype_t entityRenderableGetType(
|
void entityRenderableDispose(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId
|
const componentid_t componentId
|
||||||
) {
|
) {
|
||||||
entityrenderable_t *r = componentGetData(
|
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
|
||||||
);
|
|
||||||
return r->type;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityRenderableSetType(
|
void entityRenderableSetType(
|
||||||
@@ -44,106 +49,94 @@ void entityRenderableSetType(
|
|||||||
r->type = type;
|
r->type = type;
|
||||||
}
|
}
|
||||||
|
|
||||||
mesh_t * entityRenderableGetMesh(
|
void entityRenderableSetPriority(
|
||||||
const entityid_t entityId,
|
|
||||||
const componentid_t componentId
|
|
||||||
) {
|
|
||||||
entityrenderable_t *r = componentGetData(
|
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
|
||||||
);
|
|
||||||
return r->mesh;
|
|
||||||
}
|
|
||||||
|
|
||||||
void entityRenderableSetMesh(
|
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
mesh_t *mesh
|
const int8_t priority
|
||||||
) {
|
) {
|
||||||
entityrenderable_t *r = componentGetData(
|
entityrenderable_t *r = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||||
);
|
);
|
||||||
r->mesh = mesh;
|
r->priority = priority;
|
||||||
}
|
}
|
||||||
|
|
||||||
shader_t * entityRenderableGetShader(
|
void entityRenderableSetDraw(
|
||||||
const entityid_t entityId,
|
|
||||||
const componentid_t componentId
|
|
||||||
) {
|
|
||||||
entityrenderable_t *r = componentGetData(
|
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
|
||||||
);
|
|
||||||
return r->shader;
|
|
||||||
}
|
|
||||||
|
|
||||||
void entityRenderableSetShader(
|
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId,
|
const componentid_t componentId,
|
||||||
shader_t *shader
|
errorret_t (*draw)(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
void *user
|
||||||
|
),
|
||||||
|
void *user
|
||||||
) {
|
) {
|
||||||
|
assertNotNull(draw, "Draw callback cannot be null");
|
||||||
entityrenderable_t *r = componentGetData(
|
entityrenderable_t *r = componentGetData(
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||||
);
|
);
|
||||||
r->shader = shader;
|
r->type = ENTITY_RENDERABLE_TYPE_CUSTOM;
|
||||||
|
r->data.custom.draw = draw;
|
||||||
|
r->data.custom.drawUser = user;
|
||||||
}
|
}
|
||||||
|
|
||||||
shadermaterial_t * entityRenderableGetShaderMaterial(
|
static errorret_t entityRenderableDrawSpritebatch(
|
||||||
const entityid_t entityId,
|
const entityrenderablespritebatch_t *sb
|
||||||
const componentid_t componentId
|
|
||||||
) {
|
) {
|
||||||
entityrenderable_t *r = componentGetData(
|
if(sb->spriteCount == 0) errorOk();
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
|
||||||
);
|
errorChain(displaySetState((displaystate_t){
|
||||||
return &r->material;
|
.flags = DISPLAY_STATE_FLAG_BLEND
|
||||||
|
}));
|
||||||
|
|
||||||
|
spriteBatchClear();
|
||||||
|
shadermaterial_t mat;
|
||||||
|
memoryZero(&mat, sizeof(shadermaterial_t));
|
||||||
|
mat.unlit.texture = sb->texture;
|
||||||
|
mat.unlit.color = COLOR_WHITE;
|
||||||
|
errorChain(spriteBatchBuffer(
|
||||||
|
sb->sprites, sb->spriteCount,
|
||||||
|
SHADER_LIST_DEFS[SHADER_LIST_SHADER_UNLIT].shader, mat
|
||||||
|
));
|
||||||
|
return spriteBatchFlush();
|
||||||
}
|
}
|
||||||
|
|
||||||
void entityRenderableSetColor(
|
static errorret_t entityRenderableDrawMaterial(
|
||||||
const entityid_t entityId,
|
const entityrenderablematerial_t *m
|
||||||
const componentid_t componentId,
|
|
||||||
const color_t color
|
|
||||||
) {
|
) {
|
||||||
entityrenderable_t *r = componentGetData(
|
errorChain(displaySetState(m->state));
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
shader_t *shader = SHADER_LIST_DEFS[m->shaderType].shader;
|
||||||
);
|
assertNotNull(shader, "Shader cannot be null for material type");
|
||||||
r->material.unlit.color = color;
|
errorChain(shaderBind(shader));
|
||||||
}
|
errorChain(shaderSetMaterial(shader, &m->material));
|
||||||
|
for(uint8_t i = 0; i < m->meshCount; i++) {
|
||||||
void entityRenderableSpriteBatchAdd(
|
errorChain(meshDraw(m->meshes[i], m->meshOffsets[i], m->meshCounts[i]));
|
||||||
const entityid_t entityId,
|
}
|
||||||
const componentid_t componentId,
|
errorOk();
|
||||||
const spritebatchsprite_t *sprite
|
}
|
||||||
) {
|
|
||||||
entityrenderable_t *r = componentGetData(
|
static errorret_t entityRenderableDrawCustom(
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
const entityid_t entityId,
|
||||||
);
|
const componentid_t componentId,
|
||||||
if(r->spritebatch.spriteCount >= ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX) return;
|
const entityrenderablecustom_t *custom
|
||||||
r->spritebatch.sprites[r->spritebatch.spriteCount++] = *sprite;
|
) {
|
||||||
}
|
return custom->draw(entityId, componentId, custom->drawUser);
|
||||||
|
}
|
||||||
void entityRenderableSpriteBatchClear(
|
|
||||||
const entityid_t entityId,
|
errorret_t entityRenderableDraw(
|
||||||
const componentid_t componentId
|
const entityid_t entityId,
|
||||||
) {
|
const componentid_t componentId
|
||||||
entityrenderable_t *r = componentGetData(
|
) {
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
entityrenderable_t *r = componentGetData(
|
||||||
);
|
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||||
r->spritebatch.spriteCount = 0;
|
);
|
||||||
}
|
switch(r->type) {
|
||||||
|
case ENTITY_RENDERABLE_TYPE_SPRITEBATCH:
|
||||||
void entityRenderableDispose(
|
return entityRenderableDrawSpritebatch(&r->data.spritebatch);
|
||||||
const entityid_t entityId,
|
case ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL:
|
||||||
const componentid_t componentId
|
return entityRenderableDrawMaterial(&r->data.material);
|
||||||
) {
|
case ENTITY_RENDERABLE_TYPE_CUSTOM:
|
||||||
entityrenderable_t *r = componentGetData(
|
return entityRenderableDrawCustom(entityId, componentId, &r->data.custom);
|
||||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
default:
|
||||||
);
|
assertUnreachable("Invalid renderable type");
|
||||||
if(
|
|
||||||
r->type == ENTITY_RENDERABLE_TYPE_CALLBACK &&
|
|
||||||
r->userFree &&
|
|
||||||
r->user
|
|
||||||
) {
|
|
||||||
r->userFree(r->user);
|
|
||||||
r->user = NULL;
|
|
||||||
}
|
}
|
||||||
r->mesh = NULL;
|
|
||||||
r->shader = NULL;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,49 +10,66 @@
|
|||||||
#include "display/mesh/mesh.h"
|
#include "display/mesh/mesh.h"
|
||||||
#include "display/shader/shadermaterial.h"
|
#include "display/shader/shadermaterial.h"
|
||||||
#include "display/spritebatch/spritebatch.h"
|
#include "display/spritebatch/spritebatch.h"
|
||||||
|
#include "display/displaystate.h"
|
||||||
|
|
||||||
#define ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX 64
|
#define ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX 64
|
||||||
|
#define ENTITY_RENDERABLE_MESHES_MAX 8
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
ENTITY_RENDERABLE_TYPE_MATERIAL = 0,
|
ENTITY_RENDERABLE_TYPE_CUSTOM = 0,
|
||||||
ENTITY_RENDERABLE_TYPE_SPRITEBATCH,
|
ENTITY_RENDERABLE_TYPE_SPRITEBATCH,
|
||||||
ENTITY_RENDERABLE_TYPE_CALLBACK,
|
ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL,
|
||||||
} entityrenderabletype_t;
|
} entityrenderabletype_t;
|
||||||
|
|
||||||
typedef errorret_t (*entityrenderablecallback_t)(
|
|
||||||
const entityid_t entityId,
|
|
||||||
const componentid_t componentId,
|
|
||||||
const mat4 view,
|
|
||||||
const mat4 proj,
|
|
||||||
const mat4 model,
|
|
||||||
void *user
|
|
||||||
);
|
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
spritebatchsprite_t sprites[ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX];
|
spritebatchsprite_t sprites[ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX];
|
||||||
uint16_t spriteCount;
|
uint32_t spriteCount;
|
||||||
|
texture_t *texture;
|
||||||
} entityrenderablespritebatch_t;
|
} entityrenderablespritebatch_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
mesh_t *meshes[ENTITY_RENDERABLE_MESHES_MAX];
|
||||||
|
int32_t meshOffsets[ENTITY_RENDERABLE_MESHES_MAX];
|
||||||
|
int32_t meshCounts[ENTITY_RENDERABLE_MESHES_MAX];
|
||||||
|
uint8_t meshCount;
|
||||||
|
shaderlistshader_t shaderType;
|
||||||
|
shadermaterial_t material;
|
||||||
|
displaystate_t state;
|
||||||
|
} entityrenderablematerial_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
errorret_t (*draw)(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
void *user
|
||||||
|
);
|
||||||
|
void *drawUser;
|
||||||
|
} entityrenderablecustom_t;
|
||||||
|
|
||||||
|
typedef union entityrenderabledata_u {
|
||||||
|
entityrenderablespritebatch_t spritebatch;
|
||||||
|
entityrenderablematerial_t material;
|
||||||
|
entityrenderablecustom_t custom;
|
||||||
|
} entityrenderabledata_t;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
entityrenderabletype_t type;
|
entityrenderabletype_t type;
|
||||||
shader_t *shader;
|
entityrenderabledata_t data;
|
||||||
union {
|
|
||||||
struct {
|
/**
|
||||||
mesh_t *mesh;
|
* Render priority. 0 = auto (derived from type/flags). Higher values render
|
||||||
shadermaterial_t material;
|
* later (on top of lower values). Range: [-128..127] with 0 is auto.
|
||||||
};
|
*/
|
||||||
entityrenderablespritebatch_t spritebatch;
|
int8_t priority;
|
||||||
struct {
|
|
||||||
entityrenderablecallback_t callback;
|
|
||||||
void (*userFree)(void *user);
|
|
||||||
void *user;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
} entityrenderable_t;
|
} entityrenderable_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the entity renderable component. Defaults to
|
* Initializes the entity renderable component. Defaults to
|
||||||
* ENTITY_RENDERABLE_TYPE_MATERIAL, the unlit shader, white color, no mesh.
|
* ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL with the unlit shader, a white cube,
|
||||||
|
* and depth-test enabled.
|
||||||
|
*
|
||||||
|
* @param entityId The entity to initialize the component for.
|
||||||
|
* @param componentId The renderable component of the entity.
|
||||||
*/
|
*/
|
||||||
void entityRenderableInit(
|
void entityRenderableInit(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -60,7 +77,10 @@ void entityRenderableInit(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disposes the entity renderable component, freeing any callback user data.
|
* Disposes the entity renderable component.
|
||||||
|
*
|
||||||
|
* @param entityId The entity to dispose the component for.
|
||||||
|
* @param componentId The renderable component of the entity.
|
||||||
*/
|
*/
|
||||||
void entityRenderableDispose(
|
void entityRenderableDispose(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -68,15 +88,12 @@ void entityRenderableDispose(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the renderable type.
|
* Sets the rendering type for the renderable component. Resets type-specific
|
||||||
*/
|
* data to zero.
|
||||||
entityrenderabletype_t entityRenderableGetType(
|
*
|
||||||
const entityid_t entityId,
|
* @param entityId The entity to configure.
|
||||||
const componentid_t componentId
|
* @param componentId The renderable component.
|
||||||
);
|
* @param type The rendering type to use.
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the renderable type.
|
|
||||||
*/
|
*/
|
||||||
void entityRenderableSetType(
|
void entityRenderableSetType(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
@@ -85,73 +102,46 @@ void entityRenderableSetType(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the mesh pointer (ENTITY_RENDERABLE_TYPE_MATERIAL only).
|
* Sets the render priority. 0 = auto (derived from type/flags). Higher values
|
||||||
|
* render later (on top). Use non-zero to force ordering.
|
||||||
|
*
|
||||||
|
* @param entityId The entity to configure.
|
||||||
|
* @param componentId The renderable component.
|
||||||
|
* @param priority The priority value, or 0 for auto.
|
||||||
*/
|
*/
|
||||||
mesh_t * entityRenderableGetMesh(
|
void entityRenderableSetPriority(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId
|
const componentid_t componentId,
|
||||||
);
|
const int8_t priority
|
||||||
|
);
|
||||||
/**
|
|
||||||
* Sets the mesh pointer (ENTITY_RENDERABLE_TYPE_MATERIAL only).
|
/**
|
||||||
*/
|
* Sets the draw callback, switching the type to ENTITY_RENDERABLE_TYPE_CUSTOM.
|
||||||
void entityRenderableSetMesh(
|
*
|
||||||
const entityid_t entityId,
|
* @param entityId The entity to configure.
|
||||||
const componentid_t componentId,
|
* @param componentId The renderable component of the entity.
|
||||||
mesh_t *mesh
|
* @param draw The draw callback to assign.
|
||||||
);
|
* @param user Userdata passed to the callback.
|
||||||
|
*/
|
||||||
/**
|
void entityRenderableSetDraw(
|
||||||
* Gets the shader pointer.
|
const entityid_t entityId,
|
||||||
*/
|
const componentid_t componentId,
|
||||||
shader_t * entityRenderableGetShader(
|
errorret_t (*draw)(
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId
|
const componentid_t componentId,
|
||||||
);
|
void *user
|
||||||
|
),
|
||||||
/**
|
void *user
|
||||||
* Sets the shader pointer.
|
);
|
||||||
*/
|
|
||||||
void entityRenderableSetShader(
|
/**
|
||||||
const entityid_t entityId,
|
* Draws the entity using its renderable component data.
|
||||||
const componentid_t componentId,
|
*
|
||||||
shader_t *shader
|
* @param entityId The entity to draw.
|
||||||
);
|
* @param componentId The renderable component of the entity.
|
||||||
|
* @return Any error state that happened.
|
||||||
/**
|
*/
|
||||||
* Gets a pointer to the shader material union
|
errorret_t entityRenderableDraw(
|
||||||
* (ENTITY_RENDERABLE_TYPE_MATERIAL only).
|
|
||||||
*/
|
|
||||||
shadermaterial_t * entityRenderableGetShaderMaterial(
|
|
||||||
const entityid_t entityId,
|
|
||||||
const componentid_t componentId
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the unlit color (ENTITY_RENDERABLE_TYPE_MATERIAL only).
|
|
||||||
*/
|
|
||||||
void entityRenderableSetColor(
|
|
||||||
const entityid_t entityId,
|
|
||||||
const componentid_t componentId,
|
|
||||||
const color_t color
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Appends a sprite to the spritebatch renderable
|
|
||||||
* (ENTITY_RENDERABLE_TYPE_SPRITEBATCH only).
|
|
||||||
* Does nothing if the sprite buffer is full.
|
|
||||||
*/
|
|
||||||
void entityRenderableSpriteBatchAdd(
|
|
||||||
const entityid_t entityId,
|
|
||||||
const componentid_t componentId,
|
|
||||||
const spritebatchsprite_t *sprite
|
|
||||||
);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clears all buffered sprites from the spritebatch renderable
|
|
||||||
* (ENTITY_RENDERABLE_TYPE_SPRITEBATCH only).
|
|
||||||
*/
|
|
||||||
void entityRenderableSpriteBatchClear(
|
|
||||||
const entityid_t entityId,
|
const entityid_t entityId,
|
||||||
const componentid_t componentId
|
const componentid_t componentId
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -16,9 +16,10 @@
|
|||||||
// Field name (lowercase)
|
// Field name (lowercase)
|
||||||
// Init function (optional)
|
// Init function (optional)
|
||||||
// Dispose function (optional)
|
// Dispose function (optional)
|
||||||
|
// Render function (optional)
|
||||||
|
|
||||||
X(POSITION, entityposition_t, position, entityPositionInit, NULL)
|
X(POSITION, entityposition_t, position, entityPositionInit, NULL, NULL)
|
||||||
X(CAMERA, entitycamera_t, camera, entityCameraInit, NULL)
|
X(CAMERA, entitycamera_t, camera, entityCameraInit, NULL, NULL)
|
||||||
X(RENDERABLE, entityrenderable_t, renderable, entityRenderableInit, entityRenderableDispose)
|
X(RENDERABLE, entityrenderable_t, renderable, entityRenderableInit, entityRenderableDispose, NULL)
|
||||||
X(PHYSICS, entityphysics_t, physics, entityPhysicsInit, entityPhysicsDispose)
|
X(PHYSICS, entityphysics_t, physics, entityPhysicsInit, entityPhysicsDispose, NULL)
|
||||||
X(TRIGGER, entitytrigger_t, trigger, entityTriggerInit, NULL)
|
X(TRIGGER, entitytrigger_t, trigger, entityTriggerInit, NULL, NULL)
|
||||||
|
|||||||
@@ -80,10 +80,21 @@ void entityDisposeDeep(const entityid_t entityId) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void entityUpdate(const entityid_t entityId) {
|
||||||
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
||||||
|
for(uint8_t i = 0; i < ent->updateCount; i++) {
|
||||||
|
ent->onUpdate[i](entityId, ent->updateComponentId[i], ent->updateUser[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void entityDispose(const entityid_t entityId) {
|
void entityDispose(const entityid_t entityId) {
|
||||||
componentindex_t compInd;
|
componentindex_t compInd;
|
||||||
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
||||||
|
|
||||||
|
for(uint8_t i = 0; i < ent->disposeCount; 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++) {
|
||||||
compInd = componentGetIndex(entityId, i);
|
compInd = componentGetIndex(entityId, i);
|
||||||
componenttype_t type = ENTITY_MANAGER.components[compInd].type;
|
componenttype_t type = ENTITY_MANAGER.components[compInd].type;
|
||||||
@@ -95,4 +106,66 @@ void entityDispose(const entityid_t entityId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ent->state = 0;
|
ent->state = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityUpdateAdd(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const entitycallback_t callback,
|
||||||
|
const componentid_t componentId,
|
||||||
|
void *user
|
||||||
|
) {
|
||||||
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
||||||
|
assertTrue(
|
||||||
|
ent->updateCount < ENTITY_UPDATE_CALLBACK_COUNT_MAX,
|
||||||
|
"Entity update callback slots full"
|
||||||
|
);
|
||||||
|
ent->onUpdate[ent->updateCount] = callback;
|
||||||
|
ent->updateComponentId[ent->updateCount] = componentId;
|
||||||
|
ent->updateUser[ent->updateCount] = user;
|
||||||
|
ent->updateCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityUpdateRemove(const entityid_t entityId, const entitycallback_t callback) {
|
||||||
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
||||||
|
for(uint8_t i = 0; i < ent->updateCount; i++) {
|
||||||
|
if(ent->onUpdate[i] != callback) continue;
|
||||||
|
ent->updateCount--;
|
||||||
|
for(uint8_t j = i; j < ent->updateCount; j++) {
|
||||||
|
ent->onUpdate[j] = ent->onUpdate[j + 1];
|
||||||
|
ent->updateComponentId[j] = ent->updateComponentId[j + 1];
|
||||||
|
ent->updateUser[j] = ent->updateUser[j + 1];
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityDisposeAdd(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const entitycallback_t callback,
|
||||||
|
const componentid_t componentId,
|
||||||
|
void *user
|
||||||
|
) {
|
||||||
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
||||||
|
assertTrue(
|
||||||
|
ent->disposeCount < ENTITY_DISPOSE_CALLBACK_COUNT_MAX,
|
||||||
|
"Entity dispose callback slots full"
|
||||||
|
);
|
||||||
|
ent->onDispose[ent->disposeCount] = callback;
|
||||||
|
ent->disposeComponentId[ent->disposeCount] = componentId;
|
||||||
|
ent->disposeUser[ent->disposeCount] = user;
|
||||||
|
ent->disposeCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityDisposeRemove(const entityid_t entityId, const entitycallback_t callback) {
|
||||||
|
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
|
||||||
|
for(uint8_t i = 0; i < ent->disposeCount; i++) {
|
||||||
|
if(ent->onDispose[i] != callback) continue;
|
||||||
|
ent->disposeCount--;
|
||||||
|
for(uint8_t j = i; j < ent->disposeCount; j++) {
|
||||||
|
ent->onDispose[j] = ent->onDispose[j + 1];
|
||||||
|
ent->disposeComponentId[j] = ent->disposeComponentId[j + 1];
|
||||||
|
ent->disposeUser[j] = ent->disposeUser[j + 1];
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -10,8 +10,25 @@
|
|||||||
|
|
||||||
#define ENTITY_STATE_ACTIVE (1 << 0)
|
#define ENTITY_STATE_ACTIVE (1 << 0)
|
||||||
|
|
||||||
|
#define ENTITY_UPDATE_CALLBACK_COUNT_MAX 5
|
||||||
|
#define ENTITY_DISPOSE_CALLBACK_COUNT_MAX 5
|
||||||
|
|
||||||
|
typedef void (*entitycallback_t)(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const componentid_t componentId,
|
||||||
|
void *user
|
||||||
|
);
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
uint8_t state;
|
uint8_t state;
|
||||||
|
uint8_t updateCount;
|
||||||
|
uint8_t disposeCount;
|
||||||
|
entitycallback_t onUpdate[ENTITY_UPDATE_CALLBACK_COUNT_MAX];
|
||||||
|
componentid_t updateComponentId[ENTITY_UPDATE_CALLBACK_COUNT_MAX];
|
||||||
|
void *updateUser[ENTITY_UPDATE_CALLBACK_COUNT_MAX];
|
||||||
|
entitycallback_t onDispose[ENTITY_DISPOSE_CALLBACK_COUNT_MAX];
|
||||||
|
componentid_t disposeComponentId[ENTITY_DISPOSE_CALLBACK_COUNT_MAX];
|
||||||
|
void *disposeUser[ENTITY_DISPOSE_CALLBACK_COUNT_MAX];
|
||||||
} entity_t;
|
} entity_t;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,7 +64,15 @@ componentid_t entityGetComponent(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disposes of an entity with the given ID.
|
* Runs all registered update callbacks for the entity.
|
||||||
|
*
|
||||||
|
* @param entityId The ID of the entity to update.
|
||||||
|
*/
|
||||||
|
void entityUpdate(const entityid_t entityId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disposes of an entity with the given ID. Fires all dispose callbacks before
|
||||||
|
* cleaning up components and state.
|
||||||
*
|
*
|
||||||
* @param entityId The ID of the entity to dispose of.
|
* @param entityId The ID of the entity to dispose of.
|
||||||
*/
|
*/
|
||||||
@@ -60,4 +85,47 @@ void entityDispose(const entityid_t entityId);
|
|||||||
*
|
*
|
||||||
* @param entityId The root entity ID.
|
* @param entityId The root entity ID.
|
||||||
*/
|
*/
|
||||||
void entityDisposeDeep(const entityid_t entityId);
|
void entityDisposeDeep(const entityid_t entityId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers an update callback, invoked each time entityUpdate is called.
|
||||||
|
*
|
||||||
|
* @param entityId The entity to register on.
|
||||||
|
* @param callback The function to call.
|
||||||
|
*/
|
||||||
|
void entityUpdateAdd(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const entitycallback_t callback,
|
||||||
|
const componentid_t componentId,
|
||||||
|
void *user
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a previously registered update callback.
|
||||||
|
*
|
||||||
|
* @param entityId The entity to remove from.
|
||||||
|
* @param callback The function to remove.
|
||||||
|
*/
|
||||||
|
void entityUpdateRemove(const entityid_t entityId, const entitycallback_t callback);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a dispose callback, invoked at the start of entityDispose before
|
||||||
|
* any component or state cleanup.
|
||||||
|
*
|
||||||
|
* @param entityId The entity to register on.
|
||||||
|
* @param callback The function to call.
|
||||||
|
*/
|
||||||
|
void entityDisposeAdd(
|
||||||
|
const entityid_t entityId,
|
||||||
|
const entitycallback_t callback,
|
||||||
|
const componentid_t componentId,
|
||||||
|
void *user
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a previously registered dispose callback.
|
||||||
|
*
|
||||||
|
* @param entityId The entity to remove from.
|
||||||
|
* @param callback The function to remove.
|
||||||
|
*/
|
||||||
|
void entityDisposeRemove(const entityid_t entityId, const entitycallback_t callback);
|
||||||
@@ -8,11 +8,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "dusk.h"
|
#include "dusk.h"
|
||||||
|
|
||||||
#define ENTITY_COUNT_MAX 20
|
#define ENTITY_COUNT_MAX 64
|
||||||
#define ENTITY_COMPONENT_COUNT_MAX 8
|
#define ENTITY_COMPONENT_COUNT_MAX 16
|
||||||
|
|
||||||
#define ENTITY_ID_INVALID 0xFF
|
#define ENTITY_ID_INVALID 0xFF
|
||||||
#define COMPONENT_ID_INVALID 0xFF
|
#define COMPONENT_ID_INVALID 0xFF
|
||||||
|
|
||||||
typedef uint8_t entityid_t;
|
typedef uint8_t entityid_t;
|
||||||
typedef uint8_t componentid_t;
|
typedef uint8_t componentid_t;
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ void entityManagerInit(void) {
|
|||||||
memoryZero(&ENTITY_MANAGER, sizeof(entitymanager_t));
|
memoryZero(&ENTITY_MANAGER, sizeof(entitymanager_t));
|
||||||
memorySet(
|
memorySet(
|
||||||
ENTITY_MANAGER.entitiesWithComponent, COMPONENT_ID_INVALID,
|
ENTITY_MANAGER.entitiesWithComponent, COMPONENT_ID_INVALID,
|
||||||
sizeof(entityid_t) * COMPONENT_TYPE_COUNT * ENTITY_COUNT_MAX
|
sizeof(componentid_t) * COMPONENT_TYPE_COUNT * ENTITY_COUNT_MAX
|
||||||
);
|
);
|
||||||
|
|
||||||
consolePrint(
|
consolePrint(
|
||||||
@@ -36,6 +36,16 @@ entityid_t entityManagerAdd() {
|
|||||||
return ENTITY_ID_INVALID;
|
return ENTITY_ID_INVALID;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void entityManagerUpdate(void) {
|
||||||
|
entityid_t i = 0;
|
||||||
|
while(i < ENTITY_COUNT_MAX) {
|
||||||
|
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) != 0) {
|
||||||
|
entityUpdate(i);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void entityManagerDispose(void) {
|
void entityManagerDispose(void) {
|
||||||
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
|
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
|
||||||
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) == 0) continue;
|
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) == 0) continue;
|
||||||
|
|||||||
@@ -28,6 +28,11 @@ void entityManagerInit(void);
|
|||||||
*/
|
*/
|
||||||
entityid_t entityManagerAdd();
|
entityid_t entityManagerAdd();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates all active entities.
|
||||||
|
*/
|
||||||
|
void entityManagerUpdate(void);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disposes of the entity manager, in turn freeing all entities and components.
|
* Disposes of the entity manager, in turn freeing all entities and components.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
#include "util/string.h"
|
#include "util/string.h"
|
||||||
#include "log/log.h"
|
#include "log/log.h"
|
||||||
|
|
||||||
errorstate_t ERROR_STATE = { 0 };
|
THREAD_LOCAL errorstate_t ERROR_STATE = { 0 };
|
||||||
|
|
||||||
errorret_t errorThrowImpl(
|
errorret_t errorThrowImpl(
|
||||||
errorstate_t *state,
|
errorstate_t *state,
|
||||||
@@ -64,7 +64,7 @@ errorret_t errorOkImpl() {
|
|||||||
ERROR_STATE.code == ERROR_OK,
|
ERROR_STATE.code == ERROR_OK,
|
||||||
"Global error state is not OK (Likely missing errorCatch)"
|
"Global error state is not OK (Likely missing errorCatch)"
|
||||||
);
|
);
|
||||||
|
|
||||||
return (errorret_t) {
|
return (errorret_t) {
|
||||||
.code = ERROR_OK,
|
.code = ERROR_OK,
|
||||||
.state = NULL
|
.state = NULL
|
||||||
@@ -77,7 +77,7 @@ errorret_t errorChainImpl(
|
|||||||
const char_t *function,
|
const char_t *function,
|
||||||
const int32_t line
|
const int32_t line
|
||||||
) {
|
) {
|
||||||
if(retval.code == ERROR_OK) return retval;
|
if(errorIsOk(retval)) return retval;
|
||||||
|
|
||||||
assertNotNull(retval.state, "Error state NULL (Likely missing errorOk)");
|
assertNotNull(retval.state, "Error state NULL (Likely missing errorOk)");
|
||||||
assertNotNull(retval.state->message, "Message cannot be NULL");
|
assertNotNull(retval.state->message, "Message cannot be NULL");
|
||||||
@@ -111,18 +111,19 @@ errorret_t errorChainImpl(
|
|||||||
}
|
}
|
||||||
|
|
||||||
void errorCatch(errorret_t retval) {
|
void errorCatch(errorret_t retval) {
|
||||||
if(retval.code == ERROR_OK) return;
|
if(errorIsOk(retval)) return;
|
||||||
|
|
||||||
assertNotNull(retval.state, "Error state cannot be NULL");
|
assertNotNull(retval.state, "Error state cannot be NULL");
|
||||||
assertNotNull(retval.state->message, "Message cannot be NULL");
|
assertNotNull(retval.state->message, "Message cannot be NULL");
|
||||||
|
|
||||||
// Clear the error state
|
// Clear the error state
|
||||||
memoryFree((void*)retval.state->message);
|
memoryFree((void*)retval.state->message);
|
||||||
|
memoryFree((void*)retval.state->lines);
|
||||||
retval.state->code = ERROR_OK;
|
retval.state->code = ERROR_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
errorret_t errorPrint(const errorret_t retval) {
|
errorret_t errorPrint(const errorret_t retval) {
|
||||||
if(retval.code == ERROR_OK) return retval;
|
if(errorIsOk(retval)) return retval;
|
||||||
|
|
||||||
assertNotNull(retval.state, "Error state cannot be NULL");
|
assertNotNull(retval.state, "Error state cannot be NULL");
|
||||||
assertNotNull(retval.state->message, "Message cannot be NULL");
|
assertNotNull(retval.state->message, "Message cannot be NULL");
|
||||||
|
|||||||
+19
-31
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "dusk.h"
|
#include "dusk.h"
|
||||||
|
#include "thread/threadlocal.h"
|
||||||
|
|
||||||
typedef uint8_t errorcode_t;
|
typedef uint8_t errorcode_t;
|
||||||
|
|
||||||
@@ -26,7 +27,7 @@ static const errorcode_t ERROR_NOT_OK = 1;
|
|||||||
|
|
||||||
static const char_t *ERROR_PRINT_FORMAT = "Error (%d): %s\n%s";
|
static const char_t *ERROR_PRINT_FORMAT = "Error (%d): %s\n%s";
|
||||||
static const char_t *ERROR_LINE_FORMAT = " at %s:%d in function %s\n";
|
static const char_t *ERROR_LINE_FORMAT = " at %s:%d in function %s\n";
|
||||||
extern errorstate_t ERROR_STATE;
|
extern THREAD_LOCAL errorstate_t ERROR_STATE;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the error state with the provided code and message.
|
* Sets the error state with the provided code and message.
|
||||||
@@ -52,7 +53,7 @@ errorret_t errorThrowImpl(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns an error state with no error.
|
* Returns an error state with no error.
|
||||||
*
|
*
|
||||||
* @return An error state with code ERROR_OK.
|
* @return An error state with code ERROR_OK.
|
||||||
*/
|
*/
|
||||||
errorret_t errorOkImpl();
|
errorret_t errorOkImpl();
|
||||||
@@ -88,34 +89,6 @@ void errorCatch(errorret_t retval);
|
|||||||
*/
|
*/
|
||||||
errorret_t errorPrint(const errorret_t retval);
|
errorret_t errorPrint(const errorret_t retval);
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates an error with a specific error state.
|
|
||||||
*
|
|
||||||
* @param state The error state to set.
|
|
||||||
* @param message The format string for the error message.
|
|
||||||
* @param ... Additional arguments for the format string.
|
|
||||||
* @return The error code.
|
|
||||||
*/
|
|
||||||
#define errorCreate(state, message, ... ) \
|
|
||||||
errorThrowImpl(\
|
|
||||||
(state), ERROR_NOT_OK, __FILE__, __func__, __LINE__, (message), \
|
|
||||||
##__VA_ARGS__ \
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Throws an error with a specific error state.
|
|
||||||
*
|
|
||||||
* @param state The error state to set.
|
|
||||||
* @param message The format string for the error message.
|
|
||||||
* @param ... Additional arguments for the format string.
|
|
||||||
* @return The error code.
|
|
||||||
*/
|
|
||||||
#define errorThrowState(state, message, ... ) \
|
|
||||||
return errorThrowImpl(\
|
|
||||||
(state), ERROR_NOT_OK, __FILE__, __func__, __LINE__, (message), \
|
|
||||||
##__VA_ARGS__ \
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Throws an error with a formatted message.
|
* Throws an error with a formatted message.
|
||||||
*
|
*
|
||||||
@@ -154,12 +127,27 @@ errorret_t errorPrint(const errorret_t retval);
|
|||||||
return errorChainImpl(errorChainRetval, __FILE__, __func__, __LINE__); \
|
return errorChainImpl(errorChainRetval, __FILE__, __func__, __LINE__); \
|
||||||
} \
|
} \
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns without an error.
|
* Returns without an error.
|
||||||
|
*
|
||||||
|
* @return An error state with code ERROR_OK.
|
||||||
*/
|
*/
|
||||||
#define errorOk() \
|
#define errorOk() \
|
||||||
return errorOkImpl()
|
return errorOkImpl()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns non-zero if retval indicates success.
|
||||||
|
*
|
||||||
|
* @param retval errorret_t to test.
|
||||||
|
*/
|
||||||
|
#define errorIsOk(retval) ((retval).code == ERROR_OK)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns non-zero if retval indicates failure.
|
||||||
|
*
|
||||||
|
* @param retval errorret_t to test.
|
||||||
|
*/
|
||||||
|
#define errorIsNotOk(retval) ((retval).code != ERROR_OK)
|
||||||
|
|
||||||
// EOF
|
// EOF
|
||||||
+31
-19
@@ -9,43 +9,53 @@
|
|||||||
#include "assert/assert.h"
|
#include "assert/assert.h"
|
||||||
#include "util/memory.h"
|
#include "util/memory.h"
|
||||||
|
|
||||||
void eventInit(event_t *event) {
|
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");
|
||||||
memoryZero(event, sizeof(event_t));
|
assertNotNull((void *)callbacks, "callbacks must not be NULL");
|
||||||
|
assertTrue(size > 0, "size must be greater than 0");
|
||||||
|
|
||||||
|
event->callbacks = callbacks;
|
||||||
|
event->users = users;
|
||||||
|
event->size = size;
|
||||||
|
event->count = 0;
|
||||||
|
memoryZero(callbacks, sizeof(eventcallback_t) * size);
|
||||||
|
if(users) memoryZero(users, sizeof(void *) * size);
|
||||||
}
|
}
|
||||||
|
|
||||||
void eventSubscribe(event_t *event, eventcallback_t callback, void *user) {
|
void eventSubscribe(event_t *event, eventcallback_t callback, void *user) {
|
||||||
assertNotNull(event, "event must not be NULL");
|
assertNotNull(event, "event must not be NULL");
|
||||||
assertNotNull((void *)callback, "callback must not be NULL");
|
assertNotNull(callback, "callback must not be NULL");
|
||||||
|
|
||||||
for(uint8_t i = 0; i < event->count; i++) {
|
// Ensure callback isn't already susbcribed
|
||||||
if(event->callbacks[i] == callback && event->users[i] == user) return;
|
for(uint32_t i = 0; i < event->count; i++) {
|
||||||
|
if(event->callbacks[i] != callback) continue;
|
||||||
|
assertUnreachable("Callback already registered, cannot subscribe twice.");
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(
|
assertTrue(event->count < event->size, "event subscriber capacity exceeded");
|
||||||
event->count < EVENT_SUBSCRIBER_COUNT_MAX,
|
|
||||||
"EVENT_SUBSCRIBER_COUNT_MAX exceeded"
|
|
||||||
);
|
|
||||||
|
|
||||||
event->callbacks[event->count] = callback;
|
event->callbacks[event->count] = callback;
|
||||||
event->users[event->count] = user;
|
if(user) {
|
||||||
|
assertNotNull(event->users, "Cannot add user pointer.");
|
||||||
|
event->users[event->count] = user;
|
||||||
|
}
|
||||||
event->count++;
|
event->count++;
|
||||||
}
|
}
|
||||||
|
|
||||||
void eventUnsubscribe(event_t *event, eventcallback_t callback, void *user) {
|
void eventUnsubscribe(event_t *event, eventcallback_t callback) {
|
||||||
assertNotNull(event, "event must not be NULL");
|
assertNotNull(event, "event must not be NULL");
|
||||||
assertNotNull((void *)callback, "callback must not be NULL");
|
assertNotNull(callback, "callback must not be NULL");
|
||||||
|
|
||||||
for(uint8_t i = 0; i < event->count; i++) {
|
for(uint32_t i = 0; i < event->count; i++) {
|
||||||
if(event->callbacks[i] != callback || event->users[i] != user) continue;
|
if(event->callbacks[i] != callback) continue;
|
||||||
|
|
||||||
uint8_t last = event->count - 1;
|
uint32_t last = event->count - 1;
|
||||||
if(i != last) {
|
if(i != last) {
|
||||||
event->callbacks[i] = event->callbacks[last];
|
event->callbacks[i] = event->callbacks[last];
|
||||||
event->users[i] = event->users[last];
|
if(event->users) event->users[i] = event->users[last];
|
||||||
}
|
}
|
||||||
event->callbacks[last] = NULL;
|
event->callbacks[last] = NULL;
|
||||||
event->users[last] = NULL;
|
if(event->users) event->users[last] = NULL;
|
||||||
event->count--;
|
event->count--;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -53,7 +63,9 @@ void eventUnsubscribe(event_t *event, eventcallback_t callback, void *user) {
|
|||||||
|
|
||||||
void eventInvoke(const event_t *event, void *params) {
|
void eventInvoke(const event_t *event, void *params) {
|
||||||
assertNotNull(event, "event must not be NULL");
|
assertNotNull(event, "event must not be NULL");
|
||||||
for(uint8_t i = 0; i < event->count; i++) {
|
|
||||||
event->callbacks[i](params, event->users[i]);
|
for(uint32_t i = 0; i < event->count; i++) {
|
||||||
|
void *u = event->users ? event->users[i] : NULL;
|
||||||
|
event->callbacks[i](params, u);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user